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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
26,611 |
Bug 26611 Code completion assumes multiple args of same type will take same value
|
Build 20021115 (M3) 1) Start with the following JCU: public abstract class A { private int fieldInt = 5; public void foo(int a, int b, int c) { } public void bar() { int integer = 5; fo<cursor-is-here> } } 2) Invoke code assist at the cursor position indicated above 3) From the list of completions, select the method foo -> It guesses the parameter values, and highlights and underlines the first value, "integer". So far so good. 4) Type "fieldInt" as the first parameter value. -> It replaces all three parameters with the value "fieldInt". Not expected, but fine. 5) Hit tab to accept the guess for the first parameter. -> The cursor goes to the end of the line. What I expect: The method "foo" has three distinct parameters. I would expect to have to hit tab three times, once for each parameter. This template assumes that there is only one variable to complete, and that all three parameters of type "int" will have the same value.
|
resolved fixed
|
423d78c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-19T17:06:10Z | 2002-11-18T20:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/ParameterGuesser.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.text.java;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import org.eclipse.jdt.core.CompletionRequestorAdapter;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.Assert;
import org.eclipse.jdt.internal.corext.util.SuperTypeHierarchyCache;
import org.eclipse.jdt.internal.ui.util.StringMatcher;
/**
* This class triggers a code-completion that will track all local ane member variables for later
* use as a parameter guessing proposal.
*
* @author Andrew McCullough
*/
public class ParameterGuesser {
private static final class Variable {
/**
* Variable type. Used to choose the best guess based on scope (Local beats instance beats inherited)
*/
public static final int LOCAL= 0;
public static final int FIELD= 1;
public static final int INHERITED_FIELD= 2;
public final String typePackage;
public final String typeName;
public final String name;
public final int variableType;
public final int positionScore;
public boolean alreadyMatched;
/**
* Creates a variable.
*/
public Variable(String typePackage, String typeName, String name, int variableType, int positionScore) {
this.typePackage= typePackage;
this.typeName= typeName;
this.name= name;
this.variableType= variableType;
this.positionScore= positionScore;
}
/*
* @see Object#toString()
*/
public String toString() {
StringBuffer buffer= new StringBuffer();
if (typePackage.length() != 0) {
buffer.append(typePackage);
buffer.append('.');
}
buffer.append(typeName);
buffer.append(' ');
buffer.append(name);
buffer.append(" ("); //$NON-NLS-1$
buffer.append(variableType);
buffer.append(')');
return buffer.toString();
}
}
private static final class VariableCollector extends CompletionRequestorAdapter {
/** The enclosing type name */
private String fEnclosingTypeName;
/** The local and member variables */
private List fVariables;
public List collect(int codeAssistOffset, ICompilationUnit compilationUnit) throws JavaModelException {
Assert.isTrue(codeAssistOffset >= 0);
Assert.isNotNull(compilationUnit);
fVariables= new ArrayList();
String source= compilationUnit.getSource();
if (source == null)
return fVariables;
fEnclosingTypeName= getEnclosingTypeName(codeAssistOffset, compilationUnit);
// find some whitepace to start our variable-finding code complete from.
// this allows the VariableTracker to find all available variables (no prefix to match for the code completion)
int completionOffset= getCompletionOffset(source, codeAssistOffset);
compilationUnit.codeComplete(completionOffset, this);
return fVariables;
}
private static String getEnclosingTypeName(int codeAssistOffset, ICompilationUnit compilationUnit) throws JavaModelException {
IJavaElement element= compilationUnit.getElementAt(codeAssistOffset);
if (element == null)
return null;
element= element.getAncestor(IJavaElement.TYPE);
if (element == null)
return null;
return element.getElementName();
}
private static int getCompletionOffset(String source, int start) {
int index= start;
while (index > 0 && !Character.isWhitespace(source.charAt(index - 1)))
index--;
return index;
}
/**
* Determine if the declaring type matches the type of the code completion invokation
*/
private final boolean isInherited(String declaringTypeName) {
return !declaringTypeName.equals(fEnclosingTypeName);
}
private void addVariable(int varType, char[] typePackageName, char[] typeName, char[] name) {
fVariables.add(new Variable(new String(typePackageName), new String(typeName), new String(name), varType, fVariables.size()));
}
/*
* @see ICompletionRequestor#acceptField(char[], char[], char[], char[], char[], char[], int, int, int, int)
*/
public void acceptField(char[] declaringTypePackageName, char[] declaringTypeName, char[] name,
char[] typePackageName, char[] typeName, char[] completionName, int modifiers, int completionStart,
int completionEnd, int relevance)
{
if (!isInherited(new String(declaringTypeName)))
addVariable(Variable.FIELD, typePackageName, typeName, name);
else
addVariable(Variable.INHERITED_FIELD, typePackageName, typeName, name);
}
/*
* @see ICompletionRequestor#acceptLocalVariable(char[], char[], char[], int, int, int, int)
*/
public void acceptLocalVariable(char[] name, char[] typePackageName, char[] typeName, int modifiers,
int completionStart, int completionEnd, int relevance)
{
addVariable(Variable.LOCAL, typePackageName, typeName, name);
}
}
/** The compilation unit we are computing the completion for */
private final ICompilationUnit fCompilationUnit;
/** The code assist offset. */
private final int fCodeAssistOffset;
/** Local and member variables of the compilation unit */
private List fVariables;
/**
* Creates a parameter guesser for compilation unit and offset.
*
* @param codeAssistOffset the offset at which to perform code assist
* @param compilationUnit the compilation unit in which code assist is performed
*/
public ParameterGuesser(int codeAssistOffset, ICompilationUnit compilationUnit) {
Assert.isTrue(codeAssistOffset >= 0);
Assert.isNotNull(compilationUnit);
fCodeAssistOffset= codeAssistOffset;
fCompilationUnit= compilationUnit;
}
/**
* Returns the offset at which code assist is performed.
*/
public int getCodeAssistOffset() {
return fCodeAssistOffset;
}
/**
* Returns the compilation unit in which code assist is performed.
*/
public ICompilationUnit getCompilationUnit() {
return fCompilationUnit;
}
/**
* Returns the name of the variable/field that best matches the type and name of the argument.
* .
* @param paramPackage - the package of the parameter we are trying to match
* @param paramType - the qualified name of the parameter we are trying to match
* @param paramName - the name of the paramater (used to find similarly named matches)
* @return returns the name of the best match, or <code>null</code> if no match found
*/
public String guessParameterName(String paramPackage, String paramType, String paramName) throws JavaModelException {
if (fVariables == null) {
VariableCollector variableCollector= new VariableCollector();
fVariables= variableCollector.collect(fCodeAssistOffset, fCompilationUnit);
}
List typeMatches= findFieldsMatchingType(fVariables, paramPackage, paramType);
return chooseBestMatch(typeMatches, paramName);
}
/**
* Determine the best match of all possible type matches. The input into this method is all
* possible completions that match the type of the argument. The purpose of this method is to
* choose among them based on the following simple rules:
*
* 1) Local Variables > Instance/Class Variables > Inherited Instance/Class Variables
*
* 2) A longer case insensitive substring match will prevail
*
* 3) A better source position score will prevail (the declaration point of the variable, or
* "how close to the point of completion?"
*
* 4) Variables that have not been used already during this completion will prevail over
* those that have already been used (this avoids the same String/int/char from being passed
* in for multiple arguments)
*
* @return returns <code>null</code> if no match is found
*/
private static String chooseBestMatch(List typeMatches, String paramName) {
if (typeMatches == null)
return null;
Variable bestMatch= null;
int bestSubstringScore= 0;
for (Iterator i= typeMatches.iterator(); i.hasNext(); ) {
Variable variable= (Variable) i.next();
int subStringScore= getLongestCommonSubstring(variable.name, paramName).length();
if (bestMatch == null) {
bestMatch= variable;
bestSubstringScore= subStringScore;
} else if (variable.variableType < bestMatch.variableType) {
bestMatch= variable;
} else if (subStringScore > bestSubstringScore) {
bestMatch= variable;
bestSubstringScore= subStringScore;
} else if (variable.positionScore > bestMatch.positionScore) {
bestMatch= variable;
} else if (bestMatch.alreadyMatched && !variable.alreadyMatched) {
bestMatch= variable;
}
}
bestMatch.alreadyMatched= true;
return bestMatch.name;
}
/**
* Finds a local or member variable that matched the type of the parameter
*/
private List findFieldsMatchingType(List variables, String typePackage, String typeName) throws JavaModelException {
if (typeName == null || typeName.length() == 0)
return null;
// traverse the lists in reverse order, since it is empirically true that the code
// completion engine returns variables in the order they are found -- and we want to find
// matches closest to the codecompletion point.. No idea if this behavior is guaranteed.
List matches= new ArrayList();
for (ListIterator iterator= variables.listIterator(variables.size()); iterator.hasPrevious(); ) {
Variable variable= (Variable) iterator.previous();
if (isTypeMatch(variable, typePackage, typeName))
matches.add(variable);
}
return matches.isEmpty() ? null : matches;
}
/**
* Return true if variable is a match for the given type. This method will search the SuperTypeHierarchy
* of the vairable's type and see if the argument's type is included. This method is approximately
* the same as: if (argumentVar.getClass().isAssignableFrom(field.getClass()))
*/
private boolean isTypeMatch(Variable variable, String typePackage, String typeName) throws JavaModelException {
// this should look at fully qualified name, but currently the ComepletionEngine is not
// sending the packag names...
// if there is no package specified, do the check on type name only. This will work for primitives
// and for local variables that cannot be resolved.
if (typePackage == null || variable.typePackage == null ||
typePackage.length() == 0 || variable.typePackage.length() == 0) {
if (variable.typeName.equals(typeName))
return true;
}
// if we get to here, we're doing a "fully qualified match" -- meaning including packages, no primitives
// and no unresolved variables.
// if there is an exact textual match, there is no need to search type hierarchy.. this is
// a quick way to pick up an exact match.
if (variable.typeName.equals(typeName) && variable.typePackage.equals(typePackage))
return true;
// otherwise, we get a match/nomatch by searching the type hierarchy
return isAssignable(variable, typePackage, typeName);
}
/**
* Returns true if variable is assignable to a type, false otherwise.
*/
private boolean isAssignable(Variable variable, String typePackage, String typeName) throws JavaModelException {
// check for an exact match (fast)
StringBuffer paramTypeName= new StringBuffer();
if (typePackage.length() != 0) {
paramTypeName.append(typePackage);
paramTypeName.append('.');
}
paramTypeName.append(typeName);
StringBuffer varTypeName= new StringBuffer();
if (variable.typePackage.length() != 0) {
varTypeName.append(variable.typePackage);
varTypeName.append('.');
}
varTypeName.append(variable.typeName);
IJavaProject project= fCompilationUnit.getJavaProject();
IType paramType= project.findType(paramTypeName.toString());
IType varType= project.findType(varTypeName.toString());
if (varType == null || paramType == null)
return false;
ITypeHierarchy hierarchy= SuperTypeHierarchyCache.getTypeHierarchy(varType);
return hierarchy.contains(paramType);
}
/**
* Returns the longest common substring of two strings.
*/
private static String getLongestCommonSubstring(String first, String second) {
String shorter= (first.length() <= second.length()) ? first : second;
String longer= shorter == first ? second : first;
int minLength= shorter.length();
StringBuffer pattern= new StringBuffer(shorter.length() + 2);
String longestCommonSubstring= ""; //$NON-NLS-1$
for (int i= 0; i < minLength; i++) {
for (int j= i + 1; j <= minLength; j++) {
if (j - i < longestCommonSubstring.length())
continue;
String substring= shorter.substring(i, j);
pattern.setLength(0);
pattern.append('*');
pattern.append(substring);
pattern.append('*');
StringMatcher matcher= new StringMatcher(pattern.toString(), true, false);
if (matcher.match(longer))
longestCommonSubstring= substring;
}
}
return longestCommonSubstring;
}
}
|
26,611 |
Bug 26611 Code completion assumes multiple args of same type will take same value
|
Build 20021115 (M3) 1) Start with the following JCU: public abstract class A { private int fieldInt = 5; public void foo(int a, int b, int c) { } public void bar() { int integer = 5; fo<cursor-is-here> } } 2) Invoke code assist at the cursor position indicated above 3) From the list of completions, select the method foo -> It guesses the parameter values, and highlights and underlines the first value, "integer". So far so good. 4) Type "fieldInt" as the first parameter value. -> It replaces all three parameters with the value "fieldInt". Not expected, but fine. 5) Hit tab to accept the guess for the first parameter. -> The cursor goes to the end of the line. What I expect: The method "foo" has three distinct parameters. I would expect to have to hit tab three times, once for each parameter. This template assumes that there is only one variable to complete, and that all three parameters of type "int" will have the same value.
|
resolved fixed
|
423d78c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-19T17:06:10Z | 2002-11-18T20:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/ParameterGuessingProposal.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.text.java;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.Region;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.corext.template.TemplateMessages;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager;
import org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI;
/**
* This is a {@link org.eclipse.jdt.internal.ui.text.java.JavaCompletionProposal} which includes templates
* that represent the best guess completion for each parameter of a method.
*
* @author Andrew McCullough
*/
public class ParameterGuessingProposal extends JavaCompletionProposal {
private final char[] fName;
private final char[][] fParameterNames;
private final char[][] fParamaterTypePackageNames;
private final char[][] fParameterTypeNames;
private final int fCodeAssistOffset;
private final ICompilationUnit fCompilationUnit;
private final ITextViewer fViewer;
private IRegion fSelectedRegion; // initialized by apply()
/**
* Creates a template proposal with a template and its context.
* @param template the template
* @param context the context in which the template was requested.
* @param image the icon of the proposal.
*/
public ParameterGuessingProposal(
int replacementOffset, int replacementLength, Image image,
String displayString, ITextViewer viewer, int relevance,
char[] name, char[][] paramaterTypePackageNames, char[][] parameterTypeNames, char[][] parameterNames,
int codeAssistOffset, ICompilationUnit compilationUnit)
{
// replacementString is set in apply()
super("", replacementOffset, replacementLength, image, displayString, relevance);
fName= name;
fParamaterTypePackageNames= paramaterTypePackageNames;
fParameterTypeNames= parameterTypeNames;
fParameterNames= parameterNames;
fViewer= viewer;
fCodeAssistOffset= codeAssistOffset;
fCompilationUnit= compilationUnit;
}
private boolean appendArguments(IDocument document, int offset) {
IPreferenceStore preferenceStore= JavaPlugin.getDefault().getPreferenceStore();
if (preferenceStore.getBoolean(PreferenceConstants.CODEASSIST_INSERT_COMPLETION) ^ fToggleEating)
return true;
try {
IRegion region= document.getLineInformationOfOffset(offset);
String line= document.get(region.getOffset(), region.getLength());
int index= offset - region.getOffset();
while (index != line.length() && Character.isUnicodeIdentifierPart(line.charAt(index)))
++index;
if (index == line.length())
return true;
return line.charAt(index) != '(';
} catch (BadLocationException e) {
return true;
}
}
/*
* @see ICompletionProposalExtension#apply(IDocument, char)
*/
public void apply(IDocument document, char trigger, int offset) {
try {
int parameterCount= fParameterNames.length;
int[] positionOffsets= new int[parameterCount];
int[] positionLengths= new int[parameterCount];
String replacementString;
if (appendArguments(document, offset)) {
parameterCount= fParameterNames.length;
positionOffsets= new int[parameterCount];
positionLengths= new int[parameterCount];
replacementString= computeGuessingCompletion(positionOffsets, positionLengths);
} else {
parameterCount= 0;
positionOffsets= new int[0];
positionLengths= new int[0];
replacementString= new String(fName);
}
setReplacementString(replacementString);
super.apply(document, trigger, offset);
int replacementOffset= getReplacementOffset();
if (LinkedPositionManager.hasActiveManager(document)) {
fSelectedRegion= (positionOffsets.length == 0)
? new Region(replacementOffset + replacementString.length(), 0)
: new Region(replacementOffset + positionOffsets[0], positionLengths[0]);
} else {
LinkedPositionManager manager= new LinkedPositionManager(document);
for (int i= 0; i != positionOffsets.length; i++)
manager.addPosition(replacementOffset + positionOffsets[i], positionLengths[i]);
LinkedPositionUI editor= new LinkedPositionUI(fViewer, manager);
editor.setFinalCaretOffset(replacementOffset + replacementString.length());
editor.enter();
fSelectedRegion= editor.getSelectedRegion();
}
} catch (BadLocationException e) {
JavaPlugin.log(e);
openErrorDialog(e);
} catch (JavaModelException e) {
JavaPlugin.log(e);
openErrorDialog(e);
}
}
private String[] guessParameters() throws JavaModelException {
// find matches in reverse order. Do this because people tend to declare the variable meant for the last
// parameter last. That is, local variables for the last parameter in the method completion are more
// likely to be closer to the point of codecompletion. As an example consider a "delegation" completion:
//
// public void myMethod(int param1, int param2, int param3) {
// someOtherObject.yourMethod(param1, param2, param3);
// }
//
// The other consideration is giving preference to variables that have not previously been used in this
// code completion (which avoids "someOtherObject.yourMethod(param1, param1, param1)";
String[] parameters= new String[fParameterNames.length];
if (fCompilationUnit == null) {
for (int i= 0; i != fParameterNames.length; i++)
parameters[i]= new String(fParameterNames[i]);
return parameters;
} else {
ParameterGuesser guesser= new ParameterGuesser(fCodeAssistOffset, fCompilationUnit);
for (int i= fParameterNames.length - 1; i >= 0; i--) {
String parameter= guesser.guessParameterName(
new String(fParamaterTypePackageNames[i]),
new String(fParameterTypeNames[i]),
new String(fParameterNames[i]));
parameters[i]= (parameter == null) ? new String(fParameterNames[i]) : parameter;
}
return parameters;
}
}
/**
* Creates the completion string. Offsets and Lengths are set to the offsets and lengths
* of the parameters.
*/
private String computeGuessingCompletion(int[] offsets, int[] lengths) throws JavaModelException {
StringBuffer buffer= new StringBuffer();
buffer.append(fName);
buffer.append('(');
String[] parameters= guessParameters();
for (int i= 0; i < parameters.length; i++) {
if (i != 0)
buffer.append(", ");
offsets[i]= buffer.length();
buffer.append(parameters[i]);
lengths[i]= buffer.length() - offsets[i];
}
buffer.append(')');
return buffer.toString();
}
/*
* @see ICompletionProposal#getSelection(IDocument)
*/
public Point getSelection(IDocument document) {
if (fSelectedRegion == null)
return new Point(getReplacementOffset(), 0);
return new Point(fSelectedRegion.getOffset(), fSelectedRegion.getLength());
}
private void openErrorDialog(Exception e) {
Shell shell= fViewer.getTextWidget().getShell();
MessageDialog.openError(shell, TemplateMessages.getString("TemplateEvaluator.error.title"), e.getMessage()); //$NON-NLS-1$
}
/*
* @see java.lang.Object#toString()
*/
public String toString() {
return getDisplayString() + super.toString();
}
}
|
26,314 |
Bug 26314 Goto Matching Bracket bug with selection
|
20021113 1. In this code action.setChecked(elements[i].equals(fHierarchyView.getInputElement())); select the last bracket with a selection of length 1. 2. press ctrl + shift + P 3. wrong bracket is matched
|
resolved fixed
|
37cb754
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-19T17:24:38Z | 2002-11-14T16:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/CompilationUnitEditor.java
|
/**********************************************************************
Copyright (c) 2000, 2002 IBM Corp. and others.
All rights reserved. This program and the accompanying materials
are made available under the terms of the Common Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/cpl-v10.html
Contributors:
IBM Corporation - Initial implementation
**********************************************************************/
package org.eclipse.jdt.internal.ui.javaeditor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.core.runtime.Preferences.IPropertyChangeListener;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.custom.VerifyKeyListener;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Layout;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DocumentCommand;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ILineTracker;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextOperationTarget;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.ITextViewerExtension;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.IWidgetTokenKeeper;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.contentassist.ContentAssistant;
import org.eclipse.jface.text.contentassist.IContentAssistant;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.IVerticalRuler;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.actions.WorkspaceModifyOperation;
import org.eclipse.ui.dialogs.SaveAsDialog;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.texteditor.ContentAssistAction;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.IEditorStatusLine;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.MarkerAnnotation;
import org.eclipse.ui.texteditor.TextOperationAction;
import org.eclipse.ui.views.tasklist.TaskList;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IImportContainer;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.actions.GenerateActionGroup;
import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds;
import org.eclipse.jdt.ui.actions.RefactorActionGroup;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.compare.LocalHistoryActionGroup;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.GoToNextPreviousMemberAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.SelectionHistory;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectEnclosingAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectHistoryAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectNextAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectPreviousAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectionAction;
import org.eclipse.jdt.internal.ui.preferences.JavaEditorPreferencePage;
import org.eclipse.jdt.internal.ui.text.ContentAssistPreference;
import org.eclipse.jdt.internal.ui.text.JavaPairMatcher;
import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionSourceViewer;
import org.eclipse.jdt.internal.ui.text.java.IReconcilingParticipant;
import org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager;
import org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI;
import org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.ExitFlags;
/**
* Java specific text editor.
*/
public class CompilationUnitEditor extends JavaEditor implements IReconcilingParticipant {
interface ITextConverter {
void customizeDocumentCommand(IDocument document, DocumentCommand command);
};
class AdaptedRulerLayout extends Layout {
protected int fGap;
protected AdaptedSourceViewer fAdaptedSourceViewer;
protected AdaptedRulerLayout(int gap, AdaptedSourceViewer asv) {
fGap= gap;
fAdaptedSourceViewer= asv;
}
protected Point computeSize(Composite composite, int wHint, int hHint, boolean flushCache) {
Control[] children= composite.getChildren();
Point s= children[children.length - 1].computeSize(SWT.DEFAULT, SWT.DEFAULT, flushCache);
if (fAdaptedSourceViewer.isVerticalRulerVisible())
s.x += fAdaptedSourceViewer.getVerticalRuler().getWidth() + fGap;
return s;
}
protected void layout(Composite composite, boolean flushCache) {
Rectangle clArea= composite.getClientArea();
if (fAdaptedSourceViewer.isVerticalRulerVisible()) {
StyledText textWidget= fAdaptedSourceViewer.getTextWidget();
Rectangle trim= textWidget.computeTrim(0, 0, 0, 0);
int scrollbarHeight= trim.height;
IVerticalRuler vr= fAdaptedSourceViewer.getVerticalRuler();
int vrWidth=vr.getWidth();
int orWidth= 0;
if (fAdaptedSourceViewer.isOverviewRulerVisible()) {
OverviewRuler or= fAdaptedSourceViewer.getOverviewRuler();
orWidth= or.getWidth();
or.getControl().setBounds(clArea.width - orWidth, scrollbarHeight, orWidth, clArea.height - 3*scrollbarHeight);
}
textWidget.setBounds(vrWidth + fGap, 0, clArea.width - vrWidth - orWidth - 2*fGap, clArea.height);
vr.getControl().setBounds(0, 0, vrWidth, clArea.height - scrollbarHeight);
} else {
StyledText textWidget= fAdaptedSourceViewer.getTextWidget();
textWidget.setBounds(0, 0, clArea.width, clArea.height);
}
}
};
class AdaptedSourceViewer extends JavaCorrectionSourceViewer {
private List fTextConverters;
private OverviewRuler fOverviewRuler;
private boolean fIsOverviewRulerVisible;
private boolean fIgnoreTextConverters= false;
private IVerticalRuler fCachedVerticalRuler;
private boolean fCachedIsVerticalRulerVisible;
public AdaptedSourceViewer(Composite parent, IVerticalRuler ruler, int styles) {
super(parent, ruler, styles, CompilationUnitEditor.this);
fCachedVerticalRuler= ruler;
fCachedIsVerticalRulerVisible= (ruler != null);
fOverviewRuler= new OverviewRuler(VERTICAL_RULER_WIDTH);
delayedCreateControl(parent, styles);
}
/*
* @see ISourceViewer#showAnnotations(boolean)
*/
public void showAnnotations(boolean show) {
fCachedIsVerticalRulerVisible= (show && fCachedVerticalRuler != null);
super.showAnnotations(show);
}
public IContentAssistant getContentAssistant() {
return fContentAssistant;
}
/*
* @see ITextOperationTarget#doOperation(int)
*/
public void doOperation(int operation) {
if (getTextWidget() == null)
return;
switch (operation) {
case CONTENTASSIST_PROPOSALS:
String msg= fContentAssistant.showPossibleCompletions();
setStatusLineErrorMessage(msg);
return;
case UNDO:
fIgnoreTextConverters= true;
break;
case REDO:
fIgnoreTextConverters= true;
break;
}
super.doOperation(operation);
}
public void insertTextConverter(ITextConverter textConverter, int index) {
throw new UnsupportedOperationException();
}
public void addTextConverter(ITextConverter textConverter) {
if (fTextConverters == null) {
fTextConverters= new ArrayList(1);
fTextConverters.add(textConverter);
} else if (!fTextConverters.contains(textConverter))
fTextConverters.add(textConverter);
}
public void removeTextConverter(ITextConverter textConverter) {
if (fTextConverters != null) {
fTextConverters.remove(textConverter);
if (fTextConverters.size() == 0)
fTextConverters= null;
}
}
/*
* @see TextViewer#customizeDocumentCommand(DocumentCommand)
*/
protected void customizeDocumentCommand(DocumentCommand command) {
super.customizeDocumentCommand(command);
if (!fIgnoreTextConverters && fTextConverters != null) {
for (Iterator e = fTextConverters.iterator(); e.hasNext();)
((ITextConverter) e.next()).customizeDocumentCommand(getDocument(), command);
}
fIgnoreTextConverters= false;
}
public IVerticalRuler getVerticalRuler() {
return fCachedVerticalRuler;
}
public boolean isVerticalRulerVisible() {
return fCachedIsVerticalRulerVisible;
}
public OverviewRuler getOverviewRuler() {
return fOverviewRuler;
}
/*
* @see TextViewer#createControl(Composite, int)
*/
protected void createControl(Composite parent, int styles) {
// do nothing here
}
protected void delayedCreateControl(Composite parent, int styles) {
//create the viewer
super.createControl(parent, styles);
Control control= getControl();
if (control instanceof Composite) {
Composite composite= (Composite) control;
composite.setLayout(new AdaptedRulerLayout(GAP_SIZE, this));
fOverviewRuler.createControl(composite, this);
}
}
public void hideOverviewRuler() {
fIsOverviewRulerVisible= false;
Control control= getControl();
if (control instanceof Composite) {
Composite composite= (Composite) control;
composite.layout();
}
}
public void showOverviewRuler() {
fIsOverviewRulerVisible= true;
Control control= getControl();
if (control instanceof Composite) {
Composite composite= (Composite) control;
composite.layout();
}
}
public boolean isOverviewRulerVisible() {
return fIsOverviewRulerVisible;
}
/*
* @see ISourceViewer#setDocument(IDocument, IAnnotationModel, int, int)
*/
public void setDocument(IDocument document, IAnnotationModel annotationModel, int visibleRegionOffset, int visibleRegionLength) {
super.setDocument(document, annotationModel, visibleRegionOffset, visibleRegionLength);
fOverviewRuler.setModel(annotationModel);
}
// http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
public void updateIndentationPrefixes() {
SourceViewerConfiguration configuration= getSourceViewerConfiguration();
String[] types= configuration.getConfiguredContentTypes(this);
for (int i= 0; i < types.length; i++) {
String[] prefixes= configuration.getIndentPrefixes(this, types[i]);
if (prefixes != null && prefixes.length > 0)
setIndentPrefixes(prefixes, types[i]);
}
}
/*
* @see IWidgetTokenOwner#requestWidgetToken(IWidgetTokenKeeper)
*/
public boolean requestWidgetToken(IWidgetTokenKeeper requester) {
if (WorkbenchHelp.isContextHelpDisplayed())
return false;
return super.requestWidgetToken(requester);
}
};
static class TabConverter implements ITextConverter {
private int fTabRatio;
private ILineTracker fLineTracker;
public TabConverter() {
}
public void setNumberOfSpacesPerTab(int ratio) {
fTabRatio= ratio;
}
public void setLineTracker(ILineTracker lineTracker) {
fLineTracker= lineTracker;
}
private int insertTabString(StringBuffer buffer, int offsetInLine) {
if (fTabRatio == 0)
return 0;
int remainder= offsetInLine % fTabRatio;
remainder= fTabRatio - remainder;
for (int i= 0; i < remainder; i++)
buffer.append(' ');
return remainder;
}
public void customizeDocumentCommand(IDocument document, DocumentCommand command) {
String text= command.text;
if (text == null)
return;
int index= text.indexOf('\t');
if (index > -1) {
StringBuffer buffer= new StringBuffer();
fLineTracker.set(command.text);
int lines= fLineTracker.getNumberOfLines();
try {
for (int i= 0; i < lines; i++) {
int offset= fLineTracker.getLineOffset(i);
int endOffset= offset + fLineTracker.getLineLength(i);
String line= text.substring(offset, endOffset);
int position= 0;
if (i == 0) {
IRegion firstLine= document.getLineInformationOfOffset(command.offset);
position= command.offset - firstLine.getOffset();
}
int length= line.length();
for (int j= 0; j < length; j++) {
char c= line.charAt(j);
if (c == '\t') {
position += insertTabString(buffer, position);
} else {
buffer.append(c);
++ position;
}
}
}
command.text= buffer.toString();
} catch (BadLocationException x) {
}
}
}
};
private class PropertyChangeListener implements IPropertyChangeListener {
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
handlePreferencePropertyChanged(event);
}
}
/* Preference key for code formatter tab size */
private final static String CODE_FORMATTER_TAB_SIZE= JavaCore.FORMATTER_TAB_SIZE;
/** Preference key for matching brackets */
private final static String MATCHING_BRACKETS= PreferenceConstants.EDITOR_MATCHING_BRACKETS;
/** Preference key for matching brackets color */
private final static String MATCHING_BRACKETS_COLOR= PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR;
/** Preference key for highlighting current line */
private final static String CURRENT_LINE= PreferenceConstants.EDITOR_CURRENT_LINE;
/** Preference key for highlight color of current line */
private final static String CURRENT_LINE_COLOR= PreferenceConstants.EDITOR_CURRENT_LINE_COLOR;
/** Preference key for showing print marging ruler */
private final static String PRINT_MARGIN= PreferenceConstants.EDITOR_PRINT_MARGIN;
/** Preference key for print margin ruler color */
private final static String PRINT_MARGIN_COLOR= PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR;
/** Preference key for print margin ruler column */
private final static String PRINT_MARGIN_COLUMN= PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN;
/** Preference key for inserting spaces rather than tabs */
private final static String SPACES_FOR_TABS= PreferenceConstants.EDITOR_SPACES_FOR_TABS;
/** Preference key for error indication */
private final static String ERROR_INDICATION= PreferenceConstants.EDITOR_PROBLEM_INDICATION;
/** Preference key for error color */
private final static String ERROR_INDICATION_COLOR= PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR;
/** Preference key for warning indication */
private final static String WARNING_INDICATION= PreferenceConstants.EDITOR_WARNING_INDICATION;
/** Preference key for warning color */
private final static String WARNING_INDICATION_COLOR= PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR;
/** Preference key for task indication */
private final static String TASK_INDICATION= PreferenceConstants.EDITOR_TASK_INDICATION;
/** Preference key for task color */
private final static String TASK_INDICATION_COLOR= PreferenceConstants.EDITOR_TASK_INDICATION_COLOR;
/** Preference key for bookmark indication */
private final static String BOOKMARK_INDICATION= PreferenceConstants.EDITOR_BOOKMARK_INDICATION;
/** Preference key for bookmark color */
private final static String BOOKMARK_INDICATION_COLOR= PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR;
/** Preference key for search result indication */
private final static String SEARCH_RESULT_INDICATION= PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION;
/** Preference key for search result color */
private final static String SEARCH_RESULT_INDICATION_COLOR= PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR;
/** Preference key for unknown annotation indication */
private final static String UNKNOWN_INDICATION= PreferenceConstants.EDITOR_UNKNOWN_INDICATION;
/** Preference key for unknown annotation color */
private final static String UNKNOWN_INDICATION_COLOR= PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR;
/** Preference key for linked position color */
private final static String LINKED_POSITION_COLOR= PreferenceConstants.EDITOR_LINKED_POSITION_COLOR;
/** Preference key for shwoing the overview ruler */
private final static String OVERVIEW_RULER= PreferenceConstants.EDITOR_OVERVIEW_RULER;
/** Preference key for error indication in overview ruler */
private final static String ERROR_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for warning indication in overview ruler */
private final static String WARNING_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for task indication in overview ruler */
private final static String TASK_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for bookmark indication in overview ruler */
private final static String BOOKMARK_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for search result indication in overview ruler */
private final static String SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for unknown annotation indication in overview ruler */
private final static String UNKNOWN_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for automatically closing strings */
private final static String CLOSE_STRINGS= PreferenceConstants.EDITOR_CLOSE_STRINGS;
/** Preference key for automatically wrapping Java strings */
private final static String WRAP_STRINGS= PreferenceConstants.EDITOR_WRAP_STRINGS;
/** Preference key for automatically closing brackets and parenthesis */
private final static String CLOSE_BRACKETS= PreferenceConstants.EDITOR_CLOSE_BRACKETS;
/** Preference key for automatically closing javadocs and comments */
private final static String CLOSE_JAVADOCS= PreferenceConstants.EDITOR_CLOSE_JAVADOCS;
/** Preference key for automatically adding javadoc tags */
private final static String ADD_JAVADOC_TAGS= PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS;
/** Preference key for automatically formatting javadocs */
private final static String FORMAT_JAVADOCS= PreferenceConstants.EDITOR_FORMAT_JAVADOCS;
/** Preference key for smart paste */
private final static String SMART_PASTE= PreferenceConstants.EDITOR_SMART_PASTE;
private final static class AnnotationInfo {
public String fColorPreference;
public String fOverviewRulerPreference;
public String fEditorPreference;
};
private final static Map ANNOTATION_MAP;
static {
AnnotationInfo info;
ANNOTATION_MAP= new HashMap();
info= new AnnotationInfo();
info.fColorPreference= TASK_INDICATION_COLOR;
info.fOverviewRulerPreference= TASK_INDICATION_IN_OVERVIEW_RULER;
info.fEditorPreference= TASK_INDICATION;
ANNOTATION_MAP.put(AnnotationType.TASK, info);
info= new AnnotationInfo();
info.fColorPreference= ERROR_INDICATION_COLOR;
info.fOverviewRulerPreference= ERROR_INDICATION_IN_OVERVIEW_RULER;
info.fEditorPreference= ERROR_INDICATION;
ANNOTATION_MAP.put(AnnotationType.ERROR, info);
info= new AnnotationInfo();
info.fColorPreference= WARNING_INDICATION_COLOR;
info.fOverviewRulerPreference= WARNING_INDICATION_IN_OVERVIEW_RULER;
info.fEditorPreference= WARNING_INDICATION;
ANNOTATION_MAP.put(AnnotationType.WARNING, info);
info= new AnnotationInfo();
info.fColorPreference= BOOKMARK_INDICATION_COLOR;
info.fOverviewRulerPreference= BOOKMARK_INDICATION_IN_OVERVIEW_RULER;
info.fEditorPreference= BOOKMARK_INDICATION;
ANNOTATION_MAP.put(AnnotationType.BOOKMARK, info);
info= new AnnotationInfo();
info.fColorPreference= SEARCH_RESULT_INDICATION_COLOR;
info.fOverviewRulerPreference= SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER;
info.fEditorPreference= SEARCH_RESULT_INDICATION;
ANNOTATION_MAP.put(AnnotationType.SEARCH_RESULT, info);
info= new AnnotationInfo();
info.fColorPreference= UNKNOWN_INDICATION_COLOR;
info.fOverviewRulerPreference= UNKNOWN_INDICATION_IN_OVERVIEW_RULER;
info.fEditorPreference= UNKNOWN_INDICATION;
ANNOTATION_MAP.put(AnnotationType.UNKNOWN, info);
};
private final static AnnotationType[] ANNOTATION_LAYERS= new AnnotationType[] {
AnnotationType.UNKNOWN,
AnnotationType.BOOKMARK,
AnnotationType.TASK,
AnnotationType.SEARCH_RESULT,
AnnotationType.WARNING,
AnnotationType.ERROR
};
/** The editor's save policy */
protected ISavePolicy fSavePolicy;
/** Listener to annotation model changes that updates the error tick in the tab image */
private JavaEditorErrorTickUpdater fJavaEditorErrorTickUpdater;
/** The editor's paint manager */
private PaintManager fPaintManager;
/** The editor's bracket painter */
private BracketPainter fBracketPainter;
/** The editor's bracket matcher */
private JavaPairMatcher fBracketMatcher;
/** The editor's line painter */
private LinePainter fLinePainter;
/** The editor's print margin ruler painter */
private PrintMarginPainter fPrintMarginPainter;
/** The editor's problem painter */
private ProblemPainter fProblemPainter;
/** The editor's tab converter */
private TabConverter fTabConverter;
/** History for structure select action */
private SelectionHistory fSelectionHistory;
/** The preference property change listener for java core. */
private IPropertyChangeListener fPropertyChangeListener= new PropertyChangeListener();
/** The remembered java element */
private IJavaElement fRememberedElement;
/** The remembered selection */
private ITextSelection fRememberedSelection;
/** The remembered java element offset */
private int fRememberedElementOffset;
/** The bracket inserter. */
private BracketInserter fBracketInserter= new BracketInserter();
/** The standard action groups added to the menu */
private GenerateActionGroup fGenerateActionGroup;
private CompositeActionGroup fContextMenuGroup;
/**
* Creates a new compilation unit editor.
*/
public CompilationUnitEditor() {
super();
setDocumentProvider(JavaPlugin.getDefault().getCompilationUnitDocumentProvider());
setEditorContextMenuId("#CompilationUnitEditorContext"); //$NON-NLS-1$
setRulerContextMenuId("#CompilationUnitRulerContext"); //$NON-NLS-1$
setOutlinerContextMenuId("#CompilationUnitOutlinerContext"); //$NON-NLS-1$
// don't set help contextId, we install our own help context
fSavePolicy= null;
fJavaEditorErrorTickUpdater= new JavaEditorErrorTickUpdater(this);
}
/*
* @see AbstractTextEditor#createActions()
*/
protected void createActions() {
super.createActions();
Action action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "CorrectionAssistProposal.", this, JavaCorrectionSourceViewer.CORRECTIONASSIST_PROPOSALS); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.CORRECTION_ASSIST_PROPOSALS);
setAction("CorrectionAssistProposal", action); //$NON-NLS-1$
action= new ContentAssistAction(JavaEditorMessages.getResourceBundle(), "ContentAssistProposal.", this); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS);
setAction("ContentAssistProposal", action); //$NON-NLS-1$
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "ContentAssistContextInformation.", this, ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONTENT_ASSIST_CONTEXT_INFORMATION);
setAction("ContentAssistContextInformation", action); //$NON-NLS-1$
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Comment.", this, ITextOperationTarget.PREFIX); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.COMMENT);
setAction("Comment", action); //$NON-NLS-1$
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Uncomment.", this, ITextOperationTarget.STRIP_PREFIX); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.UNCOMMENT);
setAction("Uncomment", action); //$NON-NLS-1$
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Format.", this, ISourceViewer.FORMAT); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.FORMAT);
setAction("Format", action); //$NON-NLS-1$
markAsStateDependentAction("CorrectionAssistProposal", true); //$NON-NLS-1$
markAsStateDependentAction("ContentAssistProposal", true); //$NON-NLS-1$
markAsStateDependentAction("ContentAssistContextInformation", true); //$NON-NLS-1$
markAsStateDependentAction("Comment", true); //$NON-NLS-1$
markAsStateDependentAction("Uncomment", true); //$NON-NLS-1$
markAsStateDependentAction("Format", true); //$NON-NLS-1$
action= new GotoMatchingBracketAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_MATCHING_BRACKET);
setAction(GotoMatchingBracketAction.GOTO_MATCHING_BRACKET, action);
action= GoToNextPreviousMemberAction.newGoToNextMemberAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_NEXT_MEMBER);
setAction(GoToNextPreviousMemberAction.NEXT_MEMBER, action);
action= GoToNextPreviousMemberAction.newGoToPreviousMemberAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_PREVIOUS_MEMBER);
setAction(GoToNextPreviousMemberAction.PREVIOUS_MEMBER, action);
fSelectionHistory= new SelectionHistory(this);
action= new StructureSelectEnclosingAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_ENCLOSING);
setAction(StructureSelectionAction.ENCLOSING, action);
action= new StructureSelectNextAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_NEXT);
setAction(StructureSelectionAction.NEXT, action);
action= new StructureSelectPreviousAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_PREVIOUS);
setAction(StructureSelectionAction.PREVIOUS, action);
StructureSelectHistoryAction historyAction= new StructureSelectHistoryAction(this, fSelectionHistory);
historyAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_LAST);
setAction(StructureSelectionAction.HISTORY, historyAction);
fSelectionHistory.setHistoryAction(historyAction);
fGenerateActionGroup= new GenerateActionGroup(this, ITextEditorActionConstants.GROUP_EDIT);
ActionGroup rg= new RefactorActionGroup(this, ITextEditorActionConstants.GROUP_EDIT);
fActionGroups.addGroup(rg);
fActionGroups.addGroup(fGenerateActionGroup);
// We have to keep the context menu group separate to have better control over positioning
fContextMenuGroup= new CompositeActionGroup(new ActionGroup[] {
fGenerateActionGroup,
rg,
new LocalHistoryActionGroup(this, ITextEditorActionConstants.GROUP_EDIT)});
}
/*
* @see JavaEditor#getElementAt(int)
*/
protected IJavaElement getElementAt(int offset) {
return getElementAt(offset, true);
}
/**
* Returns the most narrow element including the given offset. If <code>reconcile</code>
* is <code>true</code> the editor's input element is reconciled in advance. If it is
* <code>false</code> this method only returns a result if the editor's input element
* does not need to be reconciled.
*
* @param offset the offset included by the retrieved element
* @param reconcile <code>true</code> if working copy should be reconciled
*/
protected IJavaElement getElementAt(int offset, boolean reconcile) {
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
ICompilationUnit unit= manager.getWorkingCopy(getEditorInput());
if (unit != null) {
try {
if (reconcile) {
synchronized (unit) {
unit.reconcile();
}
return unit.getElementAt(offset);
} else if (unit.isConsistent())
return unit.getElementAt(offset);
} catch (JavaModelException x) {
JavaPlugin.log(x.getStatus());
// nothing found, be tolerant and go on
}
}
return null;
}
/*
* @see JavaEditor#getCorrespondingElement(IJavaElement)
*/
protected IJavaElement getCorrespondingElement(IJavaElement element) {
try {
return EditorUtility.getWorkingCopy(element, true);
} catch (JavaModelException x) {
JavaPlugin.log(x.getStatus());
// nothing found, be tolerant and go on
}
return null;
}
/*
* @see AbstractTextEditor#editorContextMenuAboutToShow(IMenuManager)
*/
public void editorContextMenuAboutToShow(IMenuManager menu) {
super.editorContextMenuAboutToShow(menu);
addAction(menu, ITextEditorActionConstants.GROUP_EDIT, "Format"); //$NON-NLS-1$
ActionContext context= new ActionContext(getSelectionProvider().getSelection());
fContextMenuGroup.setContext(context);
fContextMenuGroup.fillContextMenu(menu);
fContextMenuGroup.setContext(null);
}
/*
* @see JavaEditor#setOutlinePageInput(JavaOutlinePage, IEditorInput)
*/
protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input) {
if (page != null) {
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
page.setInput(manager.getWorkingCopy(input));
}
}
/*
* @see AbstractTextEditor#performSaveOperation(WorkspaceModifyOperation, IProgressMonitor)
*/
protected void performSaveOperation(WorkspaceModifyOperation operation, IProgressMonitor progressMonitor) {
IDocumentProvider p= getDocumentProvider();
if (p instanceof CompilationUnitDocumentProvider) {
CompilationUnitDocumentProvider cp= (CompilationUnitDocumentProvider) p;
cp.setSavePolicy(fSavePolicy);
}
try {
super.performSaveOperation(operation, progressMonitor);
} finally {
if (p instanceof CompilationUnitDocumentProvider) {
CompilationUnitDocumentProvider cp= (CompilationUnitDocumentProvider) p;
cp.setSavePolicy(null);
}
}
}
/*
* @see AbstractTextEditor#doSave(IProgressMonitor)
*/
public void doSave(IProgressMonitor progressMonitor) {
IDocumentProvider p= getDocumentProvider();
if (p == null) {
// editor has been closed
return;
}
if (p.isDeleted(getEditorInput())) {
if (isSaveAsAllowed()) {
/*
* 1GEUSSR: ITPUI:ALL - User should never loose changes made in the editors.
* Changed Behavior to make sure that if called inside a regular save (because
* of deletion of input element) there is a way to report back to the caller.
*/
performSaveAs(progressMonitor);
} else {
/*
* 1GF5YOX: ITPJUI:ALL - Save of delete file claims it's still there
* Missing resources.
*/
Shell shell= getSite().getShell();
MessageDialog.openError(shell, JavaEditorMessages.getString("CompilationUnitEditor.error.saving.title1"), JavaEditorMessages.getString("CompilationUnitEditor.error.saving.message1")); //$NON-NLS-1$ //$NON-NLS-2$
}
} else {
setStatusLineErrorMessage(null);
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
ICompilationUnit unit= manager.getWorkingCopy(getEditorInput());
if (unit != null) {
synchronized (unit) {
performSaveOperation(createSaveOperation(false), progressMonitor);
}
} else
performSaveOperation(createSaveOperation(false), progressMonitor);
}
}
/**
* Jumps to the error next according to the given direction.
*/
public void gotoError(boolean forward) {
ISelectionProvider provider= getSelectionProvider();
ITextSelection s= (ITextSelection) provider.getSelection();
Position errorPosition= new Position(0, 0);
IProblemAnnotation nextError= getNextError(s.getOffset(), forward, errorPosition);
if (nextError != null) {
IMarker marker= null;
if (nextError instanceof MarkerAnnotation)
marker= ((MarkerAnnotation) nextError).getMarker();
else {
Iterator e= nextError.getOverlaidIterator();
if (e != null) {
while (e.hasNext()) {
Object o= e.next();
if (o instanceof MarkerAnnotation) {
marker= ((MarkerAnnotation) o).getMarker();
break;
}
}
}
}
if (marker != null) {
IWorkbenchPage page= getSite().getPage();
IViewPart view= view= page.findView("org.eclipse.ui.views.TaskList"); //$NON-NLS-1$
if (view instanceof TaskList) {
StructuredSelection ss= new StructuredSelection(marker);
((TaskList) view).setSelection(ss, true);
}
}
selectAndReveal(errorPosition.getOffset(), errorPosition.getLength());
setStatusLineErrorMessage(nextError.getMessage());
} else {
setStatusLineErrorMessage(null);
}
}
/**
* Jumps to the matching bracket.
*/
public void gotoMatchingBracket() {
if (fBracketMatcher == null)
fBracketMatcher= new JavaPairMatcher(new char[] { '{', '}', '(', ')', '[', ']' });
ISourceViewer sourceViewer= getSourceViewer();
IDocument document= sourceViewer.getDocument();
if (document == null)
return;
ISelectionProvider provider= getSelectionProvider();
ITextSelection selection= (ITextSelection) provider.getSelection();
int selectionLength= Math.abs(selection.getLength());
if (selectionLength > 1) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.invalidSelection")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
IRegion region= fBracketMatcher.match(document, selection.getOffset());
if (region == null) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.noMatchingBracket")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
int offset= region.getOffset();
int length= region.getLength();
if (length < 1)
return;
int anchor= fBracketMatcher.getAnchor();
int targetOffset= (JavaPairMatcher.RIGHT == anchor) ? offset : offset + length - 1;
IRegion visibleRegion= sourceViewer.getVisibleRegion();
if (targetOffset < visibleRegion.getOffset() || targetOffset >= visibleRegion.getOffset() + visibleRegion.getLength()) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.bracketOutsideSelectedElement")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
sourceViewer.setSelectedRange(targetOffset, selectionLength);
sourceViewer.revealRange(targetOffset, selectionLength);
}
/**
* Ses the given message as error message to this editor's status line.
* @param msg message to be set
*/
protected void setStatusLineErrorMessage(String msg) {
IEditorStatusLine statusLine= (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
if (statusLine != null)
statusLine.setMessage(true, msg, null);
}
private IProblemAnnotation getNextError(int offset, boolean forward, Position errorPosition) {
IProblemAnnotation nextError= null;
Position nextErrorPosition= null;
IDocument document= getDocumentProvider().getDocument(getEditorInput());
int endOfDocument= document.getLength();
int distance= 0;
IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
Iterator e= new ProblemAnnotationIterator(model, false);
while (e.hasNext()) {
IProblemAnnotation a= (IProblemAnnotation) e.next();
if (a.hasOverlay() || !a.isProblem())
continue;
Position p= model.getPosition((Annotation) a);
if (!p.includes(offset)) {
int currentDistance= 0;
if (forward) {
currentDistance= p.getOffset() - offset;
if (currentDistance < 0)
currentDistance= endOfDocument - offset + p.getOffset();
} else {
currentDistance= offset - p.getOffset();
if (currentDistance < 0)
currentDistance= offset + endOfDocument - p.getOffset();
}
if (nextError == null || currentDistance < distance) {
distance= currentDistance;
nextError= a;
nextErrorPosition= p;
}
}
}
if (nextErrorPosition != null) {
errorPosition.setOffset(nextErrorPosition.getOffset());
errorPosition.setLength(nextErrorPosition.getLength());
}
return nextError;
}
/*
* @see AbstractTextEditor#isSaveAsAllowed()
*/
public boolean isSaveAsAllowed() {
return true;
}
/**
* The compilation unit editor implementation of this <code>AbstractTextEditor</code>
* method asks the user for the workspace path of a file resource and saves the document
* there. See http://dev.eclipse.org/bugs/show_bug.cgi?id=6295
*/
protected void performSaveAs(IProgressMonitor progressMonitor) {
Shell shell= getSite().getShell();
IEditorInput input = getEditorInput();
SaveAsDialog dialog= new SaveAsDialog(shell);
IFile original= (input instanceof IFileEditorInput) ? ((IFileEditorInput) input).getFile() : null;
if (original != null)
dialog.setOriginalFile(original);
dialog.create();
IDocumentProvider provider= getDocumentProvider();
if (provider == null) {
// editor has been programmatically closed while the dialog was open
return;
}
if (provider.isDeleted(input) && original != null) {
String message= JavaEditorMessages.getFormattedString("CompilationUnitEditor.warning.save.delete", new Object[] { original.getName() }); //$NON-NLS-1$
dialog.setErrorMessage(null);
dialog.setMessage(message, IMessageProvider.WARNING);
}
if (dialog.open() == Dialog.CANCEL) {
if (progressMonitor != null)
progressMonitor.setCanceled(true);
return;
}
IPath filePath= dialog.getResult();
if (filePath == null) {
if (progressMonitor != null)
progressMonitor.setCanceled(true);
return;
}
IWorkspace workspace= ResourcesPlugin.getWorkspace();
IFile file= workspace.getRoot().getFile(filePath);
final IEditorInput newInput= new FileEditorInput(file);
WorkspaceModifyOperation op= new WorkspaceModifyOperation() {
public void execute(final IProgressMonitor monitor) throws CoreException {
getDocumentProvider().saveDocument(monitor, newInput, getDocumentProvider().getDocument(getEditorInput()), true);
}
};
boolean success= false;
try {
provider.aboutToChange(newInput);
new ProgressMonitorDialog(shell).run(false, true, op);
success= true;
} catch (InterruptedException x) {
} catch (InvocationTargetException x) {
Throwable t= x.getTargetException();
if (t instanceof CoreException) {
CoreException cx= (CoreException) t;
ErrorDialog.openError(shell, JavaEditorMessages.getString("CompilationUnitEditor.error.saving.title2"), JavaEditorMessages.getString("CompilationUnitEditor.error.saving.message2"), cx.getStatus()); //$NON-NLS-1$ //$NON-NLS-2$
} else {
MessageDialog.openError(shell, JavaEditorMessages.getString("CompilationUnitEditor.error.saving.title3"), JavaEditorMessages.getString("CompilationUnitEditor.error.saving.message3") + t.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
}
} finally {
provider.changed(newInput);
if (success)
setInput(newInput);
}
if (progressMonitor != null)
progressMonitor.setCanceled(!success);
}
/*
* @see AbstractTextEditor#doSetInput(IEditorInput)
*/
protected void doSetInput(IEditorInput input) throws CoreException {
super.doSetInput(input);
configureTabConverter();
}
private void startBracketHighlighting() {
if (fBracketPainter == null) {
ISourceViewer sourceViewer= getSourceViewer();
fBracketPainter= new BracketPainter(sourceViewer);
fBracketPainter.setHighlightColor(getColor(MATCHING_BRACKETS_COLOR));
fPaintManager.addPainter(fBracketPainter);
}
}
private void stopBracketHighlighting() {
if (fBracketPainter != null) {
fPaintManager.removePainter(fBracketPainter);
fBracketPainter.deactivate(true);
fBracketPainter.dispose();
fBracketPainter= null;
}
}
private boolean isBracketHighlightingEnabled() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(MATCHING_BRACKETS);
}
private void startLineHighlighting() {
if (fLinePainter == null) {
ISourceViewer sourceViewer= getSourceViewer();
fLinePainter= new LinePainter(sourceViewer);
fLinePainter.setHighlightColor(getColor(CURRENT_LINE_COLOR));
fPaintManager.addPainter(fLinePainter);
}
}
private void stopLineHighlighting() {
if (fLinePainter != null) {
fPaintManager.removePainter(fLinePainter);
fLinePainter.deactivate(true);
fLinePainter.dispose();
fLinePainter= null;
}
}
private boolean isLineHighlightingEnabled() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(CURRENT_LINE);
}
private void showPrintMargin() {
if (fPrintMarginPainter == null) {
fPrintMarginPainter= new PrintMarginPainter(getSourceViewer());
fPrintMarginPainter.setMarginRulerColor(getColor(PRINT_MARGIN_COLOR));
fPrintMarginPainter.setMarginRulerColumn(getPreferenceStore().getInt(PRINT_MARGIN_COLUMN));
fPaintManager.addPainter(fPrintMarginPainter);
}
}
private void hidePrintMargin() {
if (fPrintMarginPainter != null) {
fPaintManager.removePainter(fPrintMarginPainter);
fPrintMarginPainter.deactivate(true);
fPrintMarginPainter.dispose();
fPrintMarginPainter= null;
}
}
private boolean isPrintMarginVisible() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(PRINT_MARGIN);
}
private void startAnnotationIndication(AnnotationType annotationType) {
if (fProblemPainter == null) {
fProblemPainter= new ProblemPainter(this, getSourceViewer());
fPaintManager.addPainter(fProblemPainter);
}
fProblemPainter.setColor(annotationType, getColor(annotationType));
fProblemPainter.paintAnnotations(annotationType, true);
fProblemPainter.paint(IPainter.CONFIGURATION);
}
private void shutdownAnnotationIndication() {
if (fProblemPainter != null) {
if (!fProblemPainter.isPaintingAnnotations()) {
fPaintManager.removePainter(fProblemPainter);
fProblemPainter.deactivate(true);
fProblemPainter.dispose();
fProblemPainter= null;
} else {
fProblemPainter.paint(IPainter.CONFIGURATION);
}
}
}
private void stopAnnotationIndication(AnnotationType annotationType) {
if (fProblemPainter != null) {
fProblemPainter.paintAnnotations(annotationType, false);
shutdownAnnotationIndication();
}
}
private boolean isAnnotationIndicationEnabled(AnnotationType annotationType) {
IPreferenceStore store= getPreferenceStore();
AnnotationInfo info= (AnnotationInfo) ANNOTATION_MAP.get(annotationType);
if (info != null)
return store.getBoolean(info.fEditorPreference);
return false;
}
private boolean isAnnotationIndicationInOverviewRulerEnabled(AnnotationType annotationType) {
IPreferenceStore store= getPreferenceStore();
AnnotationInfo info= (AnnotationInfo) ANNOTATION_MAP.get(annotationType);
if (info != null)
return store.getBoolean(info.fOverviewRulerPreference);
return false;
}
private void showAnnotationIndicationInOverviewRuler(AnnotationType annotationType, boolean show) {
AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer();
OverviewRuler ruler= asv.getOverviewRuler();
if (ruler != null) {
ruler.setColor(annotationType, getColor(annotationType));
ruler.showAnnotation(annotationType, show);
ruler.update();
}
}
private void setColorInOverviewRuler(AnnotationType annotationType, Color color) {
AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer();
OverviewRuler ruler= asv.getOverviewRuler();
if (ruler != null) {
ruler.setColor(annotationType, color);
ruler.update();
}
}
private void configureTabConverter() {
if (fTabConverter != null) {
IDocumentProvider provider= getDocumentProvider();
if (provider instanceof CompilationUnitDocumentProvider) {
CompilationUnitDocumentProvider cup= (CompilationUnitDocumentProvider) provider;
fTabConverter.setLineTracker(cup.createLineTracker(getEditorInput()));
}
}
}
private int getTabSize() {
Preferences preferences= JavaCore.getPlugin().getPluginPreferences();
return preferences.getInt(CODE_FORMATTER_TAB_SIZE);
}
private void startTabConversion() {
if (fTabConverter == null) {
fTabConverter= new TabConverter();
configureTabConverter();
fTabConverter.setNumberOfSpacesPerTab(getTabSize());
AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer();
asv.addTextConverter(fTabConverter);
// http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
asv.updateIndentationPrefixes();
}
}
private void stopTabConversion() {
if (fTabConverter != null) {
AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer();
asv.removeTextConverter(fTabConverter);
// http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
asv.updateIndentationPrefixes();
fTabConverter= null;
}
}
private boolean isTabConversionEnabled() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(SPACES_FOR_TABS);
}
private void showOverviewRuler() {
AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer();
asv.showOverviewRuler();
OverviewRuler overviewRuler= asv.getOverviewRuler();
if (overviewRuler != null) {
for (int i= 0; i < ANNOTATION_LAYERS.length; i++) {
AnnotationType type= ANNOTATION_LAYERS[i];
overviewRuler.setLayer(type, i);
if (isAnnotationIndicationInOverviewRulerEnabled(type))
showAnnotationIndicationInOverviewRuler(type, true);
}
}
}
private void hideOverviewRuler() {
AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer();
asv.hideOverviewRuler();
}
private boolean isOverviewRulerVisible() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(OVERVIEW_RULER);
}
private Color getColor(String key) {
RGB rgb= PreferenceConverter.getColor(getPreferenceStore(), key);
return getColor(rgb);
}
private Color getColor(RGB rgb) {
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
return textTools.getColorManager().getColor(rgb);
}
private Color getColor(AnnotationType annotationType) {
AnnotationInfo info= (AnnotationInfo) ANNOTATION_MAP.get(annotationType);
if (info != null)
return getColor(info.fColorPreference);
return null;
}
/*
* @see AbstractTextEditor#dispose()
*/
public void dispose() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer instanceof ITextViewerExtension)
((ITextViewerExtension) sourceViewer).removeVerifyKeyListener(fBracketInserter);
if (fPropertyChangeListener != null) {
Preferences preferences= JavaCore.getPlugin().getPluginPreferences();
preferences.removePropertyChangeListener(fPropertyChangeListener);
fPropertyChangeListener= null;
}
if (fJavaEditorErrorTickUpdater != null) {
fJavaEditorErrorTickUpdater.dispose();
fJavaEditorErrorTickUpdater= null;
}
if (fSelectionHistory != null)
fSelectionHistory.dispose();
if (fPaintManager != null) {
fPaintManager.dispose();
fPaintManager= null;
}
if (fActionGroups != null)
fActionGroups.dispose();
super.dispose();
}
/*
* @see AbstractTextEditor#createPartControl(Composite)
*/
public void createPartControl(Composite parent) {
super.createPartControl(parent);
fPaintManager= new PaintManager(getSourceViewer());
if (isBracketHighlightingEnabled())
startBracketHighlighting();
if (isLineHighlightingEnabled())
startLineHighlighting();
if (isPrintMarginVisible())
showPrintMargin();
Iterator e= ANNOTATION_MAP.keySet().iterator();
while (e.hasNext()) {
AnnotationType type= (AnnotationType) e.next();
if (isAnnotationIndicationEnabled(type))
startAnnotationIndication(type);
}
if (isTabConversionEnabled())
startTabConversion();
if (isOverviewRulerVisible())
showOverviewRuler();
Preferences preferences= JavaCore.getPlugin().getPluginPreferences();
preferences.addPropertyChangeListener(fPropertyChangeListener);
IPreferenceStore preferenceStore= getPreferenceStore();
boolean closeBrackets= preferenceStore.getBoolean(CLOSE_BRACKETS);
boolean closeStrings= preferenceStore.getBoolean(CLOSE_STRINGS);
fBracketInserter.setCloseBracketsEnabled(closeBrackets);
fBracketInserter.setCloseStringsEnabled(closeStrings);
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer instanceof ITextViewerExtension)
((ITextViewerExtension) sourceViewer).prependVerifyKeyListener(fBracketInserter);
}
private static char getPeerCharacter(char character) {
switch (character) {
case '(':
return ')';
case ')':
return '(';
case '[':
return ']';
case ']':
return '[';
case '"':
return character;
default:
throw new IllegalArgumentException();
}
}
private static class ExitPolicy implements LinkedPositionUI.ExitPolicy {
final char fExitCharacter;
public ExitPolicy(char exitCharacter) {
fExitCharacter= exitCharacter;
}
/*
* @see org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.ExitPolicy#doExit(org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager, org.eclipse.swt.events.VerifyEvent, int, int)
*/
public ExitFlags doExit(LinkedPositionManager manager, VerifyEvent event, int offset, int length) {
if (event.character == fExitCharacter) {
if (manager.anyPositionIncludes(offset, length))
return new ExitFlags(LinkedPositionUI.COMMIT| LinkedPositionUI.UPDATE_CARET, false);
else
return new ExitFlags(LinkedPositionUI.COMMIT, true);
}
switch (event.character) {
case '\b':
if (manager.getFirstPosition().length == 0)
return new ExitFlags(0, false);
else
return null;
case '\n':
case '\r':
return new ExitFlags(LinkedPositionUI.COMMIT, true);
default:
return null;
}
}
}
private class BracketInserter implements VerifyKeyListener, LinkedPositionUI.ExitListener {
private boolean fCloseBrackets= true;
private boolean fCloseStrings= true;
private int fOffset;
private int fLength;
public void setCloseBracketsEnabled(boolean enabled) {
fCloseBrackets= enabled;
}
public void setCloseStringsEnabled(boolean enabled) {
fCloseStrings= enabled;
}
private boolean hasIdentifierToTheLeft(IDocument document, int offset) {
try {
int start= offset;
IRegion startLine= document.getLineInformationOfOffset(start);
int minStart= startLine.getOffset();
while (start != minStart && Character.isWhitespace(document.getChar(start - 1)))
--start;
return start != minStart && Character.isJavaIdentifierPart(document.getChar(start - 1));
} catch (BadLocationException e) {
return true;
}
}
private boolean hasIdentifierToTheRight(IDocument document, int offset) {
try {
int end= offset;
IRegion endLine= document.getLineInformationOfOffset(end);
int maxEnd= endLine.getOffset() + endLine.getLength();
while (end != maxEnd && Character.isWhitespace(document.getChar(end)))
++end;
return end != maxEnd && Character.isJavaIdentifierPart(document.getChar(end));
} catch (BadLocationException e) {
return true;
}
}
/*
* @see org.eclipse.swt.custom.VerifyKeyListener#verifyKey(org.eclipse.swt.events.VerifyEvent)
*/
public void verifyKey(VerifyEvent event) {
if (!event.doit)
return;
final ISourceViewer sourceViewer= getSourceViewer();
IDocument document= sourceViewer.getDocument();
final Point selection= sourceViewer.getSelectedRange();
final int offset= selection.x;
final int length= selection.y;
switch (event.character) {
case '(':
case '[':
if (!fCloseBrackets)
return;
if (hasIdentifierToTheRight(document, offset + length))
return;
case '"':
if (event.character == '"') {
if (!fCloseStrings)
return;
if (hasIdentifierToTheLeft(document, offset) || hasIdentifierToTheRight(document, offset + length))
return;
}
try {
ITypedRegion partition= document.getPartition(offset);
if (! IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType()) && partition.getOffset() != offset)
return;
final char character= event.character;
final char closingCharacter= getPeerCharacter(character);
final StringBuffer buffer= new StringBuffer();
buffer.append(character);
buffer.append(closingCharacter);
document.replace(offset, length, buffer.toString());
LinkedPositionManager manager= new LinkedPositionManager(document);
manager.addPosition(offset + 1, 0);
fOffset= offset;
fLength= 2;
LinkedPositionUI editor= new LinkedPositionUI(sourceViewer, manager);
editor.setCancelListener(this);
editor.setExitPolicy(new ExitPolicy(closingCharacter));
editor.setFinalCaretOffset(offset + 2);
editor.enter();
IRegion newSelection= editor.getSelectedRegion();
sourceViewer.setSelectedRange(newSelection.getOffset(), newSelection.getLength());
event.doit= false;
} catch (BadLocationException e) {
}
break;
}
}
/*
* @see org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.ExitListener#exit(boolean)
*/
public void exit(boolean accept) {
if (accept)
return;
// remove brackets
try {
final ISourceViewer sourceViewer= getSourceViewer();
IDocument document= sourceViewer.getDocument();
document.replace(fOffset, fLength, null);
} catch (BadLocationException e) {
}
}
}
protected AnnotationType getAnnotationType(String preferenceKey) {
Iterator e= ANNOTATION_MAP.keySet().iterator();
while (e.hasNext()) {
AnnotationType type= (AnnotationType) e.next();
AnnotationInfo info= (AnnotationInfo) ANNOTATION_MAP.get(type);
if (info != null) {
if (preferenceKey.equals(info.fColorPreference) || preferenceKey.equals(info.fEditorPreference) || preferenceKey.equals(info.fOverviewRulerPreference))
return type;
}
}
return null;
}
/*
* @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
*/
protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
try {
AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer();
if (asv != null) {
String p= event.getProperty();
if (CLOSE_BRACKETS.equals(p)) {
fBracketInserter.setCloseBracketsEnabled(getPreferenceStore().getBoolean(p));
return;
}
if (CLOSE_STRINGS.equals(p)) {
fBracketInserter.setCloseStringsEnabled(getPreferenceStore().getBoolean(p));
return;
}
if (SPACES_FOR_TABS.equals(p)) {
if (isTabConversionEnabled())
startTabConversion();
else
stopTabConversion();
return;
}
if (MATCHING_BRACKETS.equals(p)) {
if (isBracketHighlightingEnabled())
startBracketHighlighting();
else
stopBracketHighlighting();
return;
}
if (MATCHING_BRACKETS_COLOR.equals(p)) {
if (fBracketPainter != null)
fBracketPainter.setHighlightColor(getColor(MATCHING_BRACKETS_COLOR));
return;
}
if (CURRENT_LINE.equals(p)) {
if (isLineHighlightingEnabled())
startLineHighlighting();
else
stopLineHighlighting();
return;
}
if (CURRENT_LINE_COLOR.equals(p)) {
if (fLinePainter != null) {
stopLineHighlighting();
startLineHighlighting();
}
return;
}
if (PRINT_MARGIN.equals(p)) {
if (isPrintMarginVisible())
showPrintMargin();
else
hidePrintMargin();
return;
}
if (PRINT_MARGIN_COLOR.equals(p)) {
if (fPrintMarginPainter != null)
fPrintMarginPainter.setMarginRulerColor(getColor(PRINT_MARGIN_COLOR));
return;
}
if (PRINT_MARGIN_COLUMN.equals(p)) {
if (fPrintMarginPainter != null)
fPrintMarginPainter.setMarginRulerColumn(getPreferenceStore().getInt(PRINT_MARGIN_COLUMN));
return;
}
if (OVERVIEW_RULER.equals(p)) {
if (isOverviewRulerVisible())
showOverviewRuler();
else
hideOverviewRuler();
return;
}
AnnotationType type= getAnnotationType(p);
if (type != null) {
AnnotationInfo info= (AnnotationInfo) ANNOTATION_MAP.get(type);
if (info.fColorPreference.equals(p)) {
Color color= getColor(type);
if (fProblemPainter != null) {
fProblemPainter.setColor(type, color);
fProblemPainter.paint(IPainter.CONFIGURATION);
}
setColorInOverviewRuler(type, color);
return;
}
if (info.fEditorPreference.equals(p)) {
if (isAnnotationIndicationEnabled(type))
startAnnotationIndication(type);
else
stopAnnotationIndication(type);
return;
}
if (info.fOverviewRulerPreference.equals(p)) {
if (isAnnotationIndicationInOverviewRulerEnabled(type))
showAnnotationIndicationInOverviewRuler(type, true);
else
showAnnotationIndicationInOverviewRuler(type, false);
return;
}
}
IContentAssistant c= asv.getContentAssistant();
if (c instanceof ContentAssistant)
ContentAssistPreference.changeConfiguration((ContentAssistant) c, getPreferenceStore(), event);
}
} finally {
super.handlePreferenceStoreChanged(event);
}
}
/**
* Handles a property change event describing a change
* of the java core's preferences and updates the preference
* related editor properties.
*
* @param event the property change event
*/
protected void handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer();
if (asv != null) {
String p= event.getProperty();
if (CODE_FORMATTER_TAB_SIZE.equals(p)) {
asv.updateIndentationPrefixes();
if (fTabConverter != null)
fTabConverter.setNumberOfSpacesPerTab(getTabSize());
}
}
}
/*
* @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent)
*/
protected boolean affectsTextPresentation(PropertyChangeEvent event) {
String p= event.getProperty();
boolean affects=MATCHING_BRACKETS_COLOR.equals(p) || CURRENT_LINE_COLOR.equals(p) ||
ERROR_INDICATION_COLOR.equals(p) || WARNING_INDICATION_COLOR.equals(p) || TASK_INDICATION_COLOR.equals(p);
return affects ? affects : super.affectsTextPresentation(event);
}
/*
* @see JavaEditor#createJavaSourceViewer(Composite, IVerticalRuler, int)
*/
protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler ruler, int styles) {
return new AdaptedSourceViewer(parent, ruler, styles);
}
/*
* @see JavaEditor#synchronizeOutlinePageSelection()
*/
public void synchronizeOutlinePageSelection() {
if (isEditingScriptRunning())
return;
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null || fOutlinePage == null)
return;
StyledText styledText= sourceViewer.getTextWidget();
if (styledText == null)
return;
int offset= sourceViewer.getVisibleRegion().getOffset();
int caret= offset + styledText.getCaretOffset();
IJavaElement element= getElementAt(caret, false);
ISourceReference reference= getSourceReference(element, caret);
if (reference != null) {
fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener);
fOutlinePage.select(reference);
fOutlinePage.addSelectionChangedListener(fSelectionChangedListener);
}
}
private ISourceReference getSourceReference(IJavaElement element, int offset) {
if ( !(element instanceof ISourceReference))
return null;
if (element.getElementType() == IJavaElement.IMPORT_DECLARATION) {
IImportDeclaration declaration= (IImportDeclaration) element;
IImportContainer container= (IImportContainer) declaration.getParent();
ISourceRange srcRange= null;
try {
srcRange= container.getSourceRange();
} catch (JavaModelException e) {
}
if (srcRange != null && srcRange.getOffset() == offset)
return container;
}
return (ISourceReference) element;
}
/*
* @see IReconcilingParticipant#reconciled()
*/
public void reconciled() {
if (!JavaEditorPreferencePage.synchronizeOutlineOnCursorMove()) {
Shell shell= getSite().getShell();
if (shell != null && !shell.isDisposed()) {
shell.getDisplay().asyncExec(new Runnable() {
public void run() {
synchronizeOutlinePageSelection();
}
});
}
}
}
protected void updateStateDependentActions() {
super.updateStateDependentActions();
fGenerateActionGroup.editorStateChanged();
}
/**
* Returns the updated java element for the old java element.
*/
private IJavaElement findElement(IJavaElement element) {
if (element == null)
return null;
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
ICompilationUnit unit= manager.getWorkingCopy(getEditorInput());
if (unit != null) {
try {
synchronized (unit) {
unit.reconcile();
}
IJavaElement[] findings= unit.findElements(element);
if (findings != null && findings.length > 0)
return findings[0];
} catch (JavaModelException x) {
JavaPlugin.log(x.getStatus());
// nothing found, be tolerant and go on
}
}
return null;
}
/**
* Returns the offset of the given Java element.
*/
private int getOffset(IJavaElement element) {
if (element instanceof ISourceReference) {
ISourceReference sr= (ISourceReference) element;
try {
ISourceRange srcRange= sr.getSourceRange();
if (srcRange != null)
return srcRange.getOffset();
} catch (JavaModelException e) {
}
}
return -1;
}
/*
* @see AbstractTextEditor#rememberSelection()
*/
protected void rememberSelection() {
ISelectionProvider sp= getSelectionProvider();
fRememberedSelection= (sp == null ? null : (ITextSelection) sp.getSelection());
if (fRememberedSelection != null) {
fRememberedElement= getElementAt(fRememberedSelection.getOffset(), true);
fRememberedElementOffset= getOffset(fRememberedElement);
}
}
/*
* @see AbstractTextEditor#restoreSelection()
*/
protected void restoreSelection() {
try {
if (getSourceViewer() == null || fRememberedSelection == null)
return;
IJavaElement newElement= findElement(fRememberedElement);
int newOffset= getOffset(newElement);
int offset= (newOffset > -1 && fRememberedElementOffset > -1) ? newOffset - fRememberedElementOffset : 0;
selectAndReveal(offset + fRememberedSelection.getOffset(), fRememberedSelection.getLength());
} finally {
fRememberedSelection= null;
fRememberedElement= null;
fRememberedElementOffset= -1;
}
}
/*
* @see AbstractTextEditor#canHandleMove(IEditorInput, IEditorInput)
*/
protected boolean canHandleMove(IEditorInput originalElement, IEditorInput movedElement) {
String oldExtension= ""; //$NON-NLS-1$
if (originalElement instanceof IFileEditorInput) {
IFile file= ((IFileEditorInput) originalElement).getFile();
if (file != null) {
String ext= file.getFileExtension();
if (ext != null)
oldExtension= ext;
}
}
String newExtension= ""; //$NON-NLS-1$
if (movedElement instanceof IFileEditorInput) {
IFile file= ((IFileEditorInput) movedElement).getFile();
if (file != null)
newExtension= file.getFileExtension();
}
return oldExtension.equals(newExtension);
}
}
|
26,699 |
Bug 26699 Create Jar fails with no warning if jar read-only
|
Once *.jardesc has been created, if I invoke "Create JAR" from the context menu and the jar file already exists and is read-only, the progress dialog flashes and nothing more happens. Please add check for this condition and at least an error message should be displayed. Even better, ask something like "Jar file read-only, overwrite?" Y/N and overwrite the file on yes (similar to what the option "warn if jar file exists" does).
|
resolved fixed
|
73ce812
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-20T13:28:51Z | 2002-11-19T21:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarpackager/JarFileExportOperation.java
|
/*
* (c) Copyright IBM Corp. 2000, 2002.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.jarpackager;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.Manifest;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.operation.ModalContext;
import org.eclipse.jface.util.Assert;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModelMarker;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.jarpackager.IJarDescriptionWriter;
import org.eclipse.jdt.ui.jarpackager.IJarExportRunnable;
import org.eclipse.jdt.ui.jarpackager.JarPackageData;
import org.eclipse.jdt.ui.jarpackager.JarWriter;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaStatusConstants;
import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
/**
* Operation for exporting a resource and its children to a new JAR file.
*/
public class JarFileExportOperation implements IJarExportRunnable {
private static class MessageMultiStatus extends MultiStatus {
MessageMultiStatus(String pluginId, int code, String message, Throwable exception) {
super(pluginId, code, message, exception);
}
/*
* allows to change the message
*/
protected void setMessage(String message) {
super.setMessage(message);
}
}
private JarWriter fJarWriter;
private JarPackageData fJarPackage;
private JarPackageData[] fJarPackages;
private Shell fParentShell;
private Map fJavaNameToClassFilesMap;
private IContainer fClassFilesMapContainer;
private Set fExportedClassContainers;
private MessageMultiStatus fStatus;
/**
* Creates an instance of this class.
*
* @param jarPackage the JAR package specification
* @param parent the parent for the dialog,
* or <code>null</code> if no dialog should be presented
*/
public JarFileExportOperation(JarPackageData jarPackage, Shell parent) {
this(new JarPackageData[] {jarPackage}, parent);
}
/**
* Creates an instance of this class.
*
* @param jarPackages an array with JAR package data objects
* @param parent the parent for the dialog,
* or <code>null</code> if no dialog should be presented
*/
public JarFileExportOperation(JarPackageData[] jarPackages, Shell parent) {
this(parent);
fJarPackages= jarPackages;
}
private JarFileExportOperation(Shell parent) {
fParentShell= parent;
fStatus= new MessageMultiStatus(JavaPlugin.getPluginId(), IStatus.OK, "", null); //$NON-NLS-1$
}
protected void addToStatus(CoreException ex) {
IStatus status= ex.getStatus();
String message= ex.getLocalizedMessage();
if (message == null || message.length() < 1) {
message= JarPackagerMessages.getString("JarFileExportOperation.coreErrorDuringExport"); //$NON-NLS-1$
status= new Status(status.getSeverity(), status.getPlugin(), status.getCode(), message, ex);
}
fStatus.add(status);
}
/**
* Adds a new info to the list with the passed information.
* Normally the export operation continues after a warning.
* @param message the message
* @param exception the throwable that caused the warning, or <code>null</code>
*/
protected void addInfo(String message, Throwable error) {
fStatus.add(new Status(IStatus.INFO, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, message, error));
}
/**
* Adds a new warning to the list with the passed information.
* Normally the export operation continues after a warning.
* @param message the message
* @param exception the throwable that caused the warning, or <code>null</code>
*/
protected void addWarning(String message, Throwable error) {
fStatus.add(new Status(IStatus.WARNING, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, message, error));
}
/**
* Adds a new error to the list with the passed information.
* Normally an error terminates the export operation.
* @param message the message
* @param exception the throwable that caused the error, or <code>null</code>
*/
protected void addError(String message, Throwable error) {
fStatus.add(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, message, error));
}
/**
* Answers the number of file resources specified by the JAR package.
*
* @return int
*/
protected int countSelectedElements() {
int count= 0;
int n= fJarPackage.getElements().length;
for (int i= 0; i < n; i++) {
Object element= fJarPackage.getElements()[i];
IResource resource= null;
if (element instanceof IJavaElement) {
IJavaElement je= (IJavaElement)element;
try {
resource= je.getUnderlyingResource();
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.underlyingResourceNotFound", je.getElementName()), ex); //$NON-NLS-1$
return count;
}
}
else
resource= (IResource)element;
if (resource.getType() == IResource.FILE)
count++;
else
count += getTotalChildCount((IContainer)resource);
}
return count;
}
private int getTotalChildCount(IContainer container) {
IResource[] members;
try {
members= container.members();
} catch (CoreException ex) {
return 0;
}
int count= 0;
for (int i= 0; i < members.length; i++) {
if (members[i].getType() == IResource.FILE)
count++;
else
count += getTotalChildCount((IContainer)members[i]);
}
return count;
}
/**
* Exports the passed resource to the JAR file
*
* @param element the resource or JavaElement to export
*/
protected void exportElement(Object element, IProgressMonitor progressMonitor) throws InterruptedException {
int leadSegmentsToRemove= 1;
IPackageFragmentRoot pkgRoot= null;
boolean isInJavaProject= false;
IResource resource= null;
IJavaProject jProject= null;
if (element instanceof IJavaElement) {
isInJavaProject= true;
IJavaElement je= (IJavaElement)element;
try {
resource= je.getUnderlyingResource();
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.underlyingResourceNotFound", je.getElementName()), ex); //$NON-NLS-1$
return;
}
jProject= je.getJavaProject();
pkgRoot= JavaModelUtil.getPackageFragmentRoot(je);
}
else
resource= (IResource)element;
if (!resource.isAccessible()) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.resourceNotFound", resource.getFullPath()), null); //$NON-NLS-1$
return;
}
if (resource.getType() == IResource.FILE) {
if (!resource.isLocal(IResource.DEPTH_ZERO))
try {
resource.setLocal(true , IResource.DEPTH_ZERO, progressMonitor);
} catch (CoreException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.resourceNotLocal", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
if (!isInJavaProject) {
// check if it's a Java resource
try {
isInJavaProject= resource.getProject().hasNature(JavaCore.NATURE_ID);
} catch (CoreException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.projectNatureNotDeterminable", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
if (isInJavaProject) {
jProject= JavaCore.create(resource.getProject());
try {
IPackageFragment pkgFragment= jProject.findPackageFragment(resource.getFullPath().removeLastSegments(1));
if (pkgFragment != null)
pkgRoot= JavaModelUtil.getPackageFragmentRoot(pkgFragment);
else
pkgRoot= findPackageFragmentRoot(jProject, resource.getFullPath().removeLastSegments(1));
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.javaPackageNotDeterminable", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
}
}
if (pkgRoot != null) {
leadSegmentsToRemove= pkgRoot.getPath().segmentCount();
if (mustUseSourceFolderHierarchy() && !pkgRoot.getElementName().equals(IPackageFragmentRoot.DEFAULT_PACKAGEROOT_PATH))
leadSegmentsToRemove--;
}
IPath destinationPath= resource.getFullPath().removeFirstSegments(leadSegmentsToRemove);
boolean isInOutputFolder= false;
if (isInJavaProject) {
try {
isInOutputFolder= jProject.getOutputLocation().isPrefixOf(resource.getFullPath());
} catch (JavaModelException ex) {
isInOutputFolder= false;
}
}
exportClassFiles(progressMonitor, pkgRoot, resource, jProject, destinationPath);
exportResource(progressMonitor, pkgRoot, isInJavaProject, resource, destinationPath, isInOutputFolder);
progressMonitor.worked(1);
ModalContext.checkCanceled(progressMonitor);
} else if (element instanceof IPackageFragment)
exportPackageFragment(progressMonitor, (IPackageFragment)element);
else
exportContainer(progressMonitor, (IContainer)resource);
}
private void exportPackageFragment(IProgressMonitor progressMonitor, IPackageFragment pkgFragment) throws java.lang.InterruptedException {
Object[] children;
try {
children= pkgFragment.getChildren();
for (int i= 0; i < children.length; i++)
exportElement(children[i], progressMonitor);
children= pkgFragment.getNonJavaResources();
for (int i= 0; i < children.length; i++)
exportElement(children[i], progressMonitor);
} catch (CoreException e) {
// this should never happen because an #isAccessible check is done before #members is invoked
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.errorDuringExport", pkgFragment.toString()), e); //$NON-NLS-1$
}
}
private void exportContainer(IProgressMonitor progressMonitor, IContainer container) throws java.lang.InterruptedException {
if (container.getType() == IResource.FOLDER && isOutputFolder((IFolder)container))
return;
IResource[] children= null;
try {
children= container.members();
} catch (CoreException e) {
// this should never happen because an #isAccessible check is done before #members is invoked
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.errorDuringExport", container.getFullPath()), e); //$NON-NLS-1$
}
for (int i= 0; i < children.length; i++)
exportElement(children[i], progressMonitor);
}
private IPackageFragmentRoot findPackageFragmentRoot(IJavaProject jProject, IPath path) throws JavaModelException {
if (jProject == null || path == null || path.segmentCount() <= 0)
return null;
IPackageFragmentRoot pkgRoot= jProject.findPackageFragmentRoot(path);
if (pkgRoot != null)
return pkgRoot;
else
return findPackageFragmentRoot(jProject, path.removeLastSegments(1));
}
private void exportResource(IProgressMonitor progressMonitor, IPackageFragmentRoot pkgRoot, boolean isInJavaProject, IResource resource, IPath destinationPath, boolean isInOutputFolder) {
boolean isNonJavaResource= !isInJavaProject || pkgRoot == null;
boolean isInClassFolder= false;
try {
isInClassFolder= pkgRoot != null && !pkgRoot.isArchive() && pkgRoot.getKind() == IPackageFragmentRoot.K_BINARY;
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.cantGetRootKind", resource.getFullPath()), ex); //$NON-NLS-1$
}
if ((fJarPackage.areClassFilesExported() &&
((isNonJavaResource || (pkgRoot != null && !isJavaFile(resource) && !isClassFile(resource)))
|| isInClassFolder && isClassFile(resource)))
|| (fJarPackage.areJavaFilesExported() && (isNonJavaResource || (pkgRoot != null && !isClassFile(resource))))) {
try {
progressMonitor.subTask(JarPackagerMessages.getFormattedString("JarFileExportOperation.exporting", destinationPath.toString())); //$NON-NLS-1$
fJarWriter.write((IFile) resource, destinationPath);
} catch (CoreException ex) {
addToStatus(ex);
}
}
}
private boolean isOutputFolder(IFolder folder) {
try {
IJavaProject javaProject= JavaCore.create(folder.getProject());
IPath outputFolderPath= javaProject.getOutputLocation();
return folder.getFullPath().equals(outputFolderPath);
} catch (JavaModelException ex) {
return false;
}
}
private void exportClassFiles(IProgressMonitor progressMonitor, IPackageFragmentRoot pkgRoot, IResource resource, IJavaProject jProject, IPath destinationPath) {
if (fJarPackage.areClassFilesExported() && isJavaFile(resource) && pkgRoot != null) {
try {
// find corresponding file(s) on classpath and export
Iterator iter= filesOnClasspath((IFile)resource, destinationPath, jProject, progressMonitor);
IPath baseDestinationPath= destinationPath.removeLastSegments(1);
while (iter.hasNext()) {
IFile file= (IFile)iter.next();
if (!resource.isLocal(IResource.DEPTH_ZERO))
file.setLocal(true , IResource.DEPTH_ZERO, progressMonitor);
IPath classFilePath= baseDestinationPath.append(file.getName());
progressMonitor.subTask(JarPackagerMessages.getFormattedString("JarFileExportOperation.exporting", classFilePath.toString())); //$NON-NLS-1$
fJarWriter.write(file, classFilePath);
}
} catch (CoreException ex) {
addToStatus(ex);
}
}
}
/**
* Exports the resources as specified by the JAR package.
*/
protected void exportSelectedElements(IProgressMonitor progressMonitor) throws InterruptedException {
fExportedClassContainers= new HashSet(10);
int n= fJarPackage.getElements().length;
for (int i= 0; i < n; i++)
exportElement(fJarPackage.getElements()[i], progressMonitor);
}
/**
* Returns an iterator on a list with files that correspond to the
* passed file and that are on the classpath of its project.
*
* @param file the file for which to find the corresponding classpath resources
* @param pathInJar the path that the file has in the JAR (i.e. project and source folder segments removed)
* @param javaProject the javaProject that contains the file
* @return the iterator over the corresponding classpath files for the given file
*/
protected Iterator filesOnClasspath(IFile file, IPath pathInJar, IJavaProject javaProject, IProgressMonitor progressMonitor) throws CoreException {
// Allow JAR Package to provide its own strategy
IFile[] classFiles= fJarPackage.findClassfilesFor(file);
if (classFiles != null)
return Arrays.asList(classFiles).iterator();
if (!isJavaFile(file))
return Collections.EMPTY_LIST.iterator();
IPath outputPath= javaProject.getOutputLocation();
IContainer outputContainer;
if (javaProject.getProject().getFullPath().equals(outputPath))
outputContainer= javaProject.getProject();
else {
outputContainer= createFolderHandle(outputPath);
if (outputContainer == null || !outputContainer.isAccessible()) {
String msg= JarPackagerMessages.getString("JarFileExportOperation.outputContainerNotAccessible"); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, msg, null));
}
}
// Java CU - search files with .class ending
boolean hasErrors= hasCompileErrors(file);
boolean hasWarnings= hasCompileWarnings(file);
boolean canBeExported= canBeExported(hasErrors, hasWarnings);
if (!canBeExported)
return Collections.EMPTY_LIST.iterator();
reportPossibleCompileProblems(file, hasErrors, hasWarnings, canBeExported);
IContainer classContainer= outputContainer;
if (pathInJar.segmentCount() > 1)
classContainer= outputContainer.getFolder(pathInJar.removeLastSegments(1));
if (fExportedClassContainers.contains(classContainer))
return Collections.EMPTY_LIST.iterator();
if (fClassFilesMapContainer == null || !fClassFilesMapContainer.equals(classContainer)) {
fJavaNameToClassFilesMap= buildJavaToClassMap(classContainer);
if (fJavaNameToClassFilesMap == null) {
// Could not fully build map. fallback is to export whole directory
String msg= JarPackagerMessages.getFormattedString("JarFileExportOperation.missingSourceFileAttributeExportedAll", classContainer.getLocation().toFile()); //$NON-NLS-1$
addInfo(msg, null);
fExportedClassContainers.add(classContainer);
return getClassesIn(classContainer);
}
fClassFilesMapContainer= classContainer;
}
ArrayList classFileList= (ArrayList)fJavaNameToClassFilesMap.get(file.getName());
if (classFileList == null || classFileList.isEmpty()) {
String msg= JarPackagerMessages.getFormattedString("JarFileExportOperation.classFileOnClasspathNotAccessible", file.getFullPath()); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, msg, null));
}
return classFileList.iterator();
}
private Iterator getClassesIn(IContainer classContainer) throws CoreException {
IResource[] resources= classContainer.members();
List files= new ArrayList(resources.length);
for (int i= 0; i < resources.length; i++)
if (resources[i].getType() == IResource.FILE && isClassFile(resources[i]))
files.add(resources[i]);
return files.iterator();
}
/**
* Answers whether the given resource is a Java file.
* The resource must be a file whose file name ends with ".java".
*
* @return a <code>true<code> if the given resource is a Java file
*/
boolean isJavaFile(IResource file) {
return file != null
&& file.getType() == IFile.FILE
&& file.getFileExtension() != null
&& file.getFileExtension().equalsIgnoreCase("java"); //$NON-NLS-1$
}
/**
* Answers whether the given resource is a class file.
* The resource must be a file whose file name ends with ".class".
*
* @return a <code>true<code> if the given resource is a class file
*/
boolean isClassFile(IResource file) {
return file != null
&& file.getType() == IFile.FILE
&& file.getFileExtension() != null
&& file.getFileExtension().equalsIgnoreCase("class"); //$NON-NLS-1$
}
/*
* Builds and returns a map that has the class files
* for each java file in a given directory
*/
private Map buildJavaToClassMap(IContainer container) throws CoreException {
if (!isCompilerGeneratingSourceFileAttribute())
return null;
if (container == null || !container.isAccessible())
return new HashMap(0);
/*
* XXX: Bug 6584: Need a way to get class files for a java file (or CU)
*/
org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader cfReader;
IResource[] members= container.members();
Map map= new HashMap(members.length);
for (int i= 0; i < members.length; i++) {
if (isClassFile(members[i])) {
IFile classFile= (IFile)members[i];
try {
cfReader= org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader.read(classFile.getLocation().toFile());
} catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.invalidClassFileFormat", classFile.getLocation().toFile()), ex); //$NON-NLS-1$
continue;
} catch (IOException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.ioErrorDuringClassFileLookup", classFile.getLocation().toFile()), ex); //$NON-NLS-1$
continue;
}
if (cfReader != null) {
if (cfReader.sourceFileName() == null) {
/*
* Can't fully build the map because one or more
* class file does not contain the name of its
* source file.
*/
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.classFileWithoutSourceFileAttribute", classFile.getLocation().toFile()), null); //$NON-NLS-1$
return null;
}
String javaName= new String(cfReader.sourceFileName());
Object classFiles= map.get(javaName);
if (classFiles == null) {
classFiles= new ArrayList(3);
map.put(javaName, classFiles);
}
((ArrayList)classFiles).add(classFile);
}
}
}
return map;
}
/**
* Creates a file resource handle for the file with the given workspace path.
* This method does not create the file resource; this is the responsibility
* of <code>createFile</code>.
*
* @param filePath the path of the file resource to create a handle for
* @return the new file resource handle
* @see #createFile
*/
protected IFile createFileHandle(IPath filePath) {
if (filePath.isValidPath(filePath.toString()) && filePath.segmentCount() >= 2)
return JavaPlugin.getWorkspace().getRoot().getFile(filePath);
else
return null;
}
/**
* Creates a folder resource handle for the folder with the given workspace path.
*
* @param folderPath the path of the folder to create a handle for
* @return the new folder resource handle
*/
protected IFolder createFolderHandle(IPath folderPath) {
if (folderPath.isValidPath(folderPath.toString()) && folderPath.segmentCount() >= 2)
return JavaPlugin.getWorkspace().getRoot().getFolder(folderPath);
else
return null;
}
/**
* Returns the status of this operation.
* The result is a status object containing individual
* status objects.
*
* @return the status of this operation
*/
public IStatus getStatus() {
String message= null;
switch (fStatus.getSeverity()) {
case IStatus.OK:
message= ""; //$NON-NLS-1$
break;
case IStatus.INFO:
message= JarPackagerMessages.getString("JarFileExportOperation.exportFinishedWithInfo"); //$NON-NLS-1$
break;
case IStatus.WARNING:
message= JarPackagerMessages.getString("JarFileExportOperation.exportFinishedWithWarnings"); //$NON-NLS-1$
break;
case IStatus.ERROR:
if (fJarPackages.length > 1)
message= JarPackagerMessages.getString("JarFileExportOperation.creationOfSomeJARsFailed"); //$NON-NLS-1$
else
message= JarPackagerMessages.getString("JarFileExportOperation.jarCreationFailed"); //$NON-NLS-1$
break;
default:
// defensive code in case new severity is defined
message= ""; //$NON-NLS-1$
break;
}
fStatus.setMessage(message);
return fStatus;
}
/**
* Answer a boolean indicating whether the passed child is a descendant
* of one or more members of the passed resources collection
*
* @param resources a List contain potential parents
* @param child the resource to test
* @return a <code>boolean</code> indicating if the child is a descendant
*/
protected boolean isDescendant(List resources, IResource child) {
if (child.getType() == IResource.PROJECT)
return false;
IResource parent= child.getParent();
if (resources.contains(parent))
return true;
return isDescendant(resources, parent);
}
protected boolean canBeExported(boolean hasErrors, boolean hasWarnings) throws CoreException {
return (!hasErrors && !hasWarnings)
|| (hasErrors && fJarPackage.areErrorsExported())
|| (hasWarnings && fJarPackage.exportWarnings());
}
protected void reportPossibleCompileProblems(IFile file, boolean hasErrors, boolean hasWarnings, boolean canBeExported) {
if (hasErrors) {
if (canBeExported)
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.exportedWithCompileErrors", file.getFullPath()), null); //$NON-NLS-1$
else
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.notExportedDueToCompileErrors", file.getFullPath()), null); //$NON-NLS-1$
}
if (hasWarnings) {
if (canBeExported)
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.exportedWithCompileWarnings", file.getFullPath()), null); //$NON-NLS-1$
else
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.notExportedDueToCompileWarnings", file.getFullPath()), null); //$NON-NLS-1$
}
}
/**
* Exports the resources as specified by the JAR package.
*
* @param progressMonitor the progress monitor that displays the progress
* @see #getStatus()
*/
public void run(IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException {
int count= fJarPackages.length;
progressMonitor.beginTask("", count); //$NON-NLS-1$
try {
for (int i= 0; i < count; i++) {
SubProgressMonitor subProgressMonitor= new SubProgressMonitor(progressMonitor, 1);
fJarPackage= fJarPackages[i];
if (fJarPackage != null)
singleRun(subProgressMonitor);
}
} finally {
progressMonitor.done();
}
}
public void singleRun(IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException {
try {
if (!preconditionsOK())
throw new InvocationTargetException(null, JarPackagerMessages.getString("JarFileExportOperation.jarCreationFailedSeeDetails")); //$NON-NLS-1$
int totalWork= countSelectedElements();
if (!isAutoBuilding() && fJarPackage.isBuildingIfNeeded() && fJarPackage.areClassFilesExported()) {
int subMonitorTicks= totalWork/10;
totalWork += subMonitorTicks;
progressMonitor.beginTask("", totalWork); //$NON-NLS-1$
SubProgressMonitor subProgressMonitor= new SubProgressMonitor(progressMonitor, subMonitorTicks, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
buildProjects(subProgressMonitor);
} else
progressMonitor.beginTask("", totalWork); //$NON-NLS-1$
fJarWriter= fJarPackage.createJarWriter(fParentShell);
exportSelectedElements(progressMonitor);
if (getStatus().getSeverity() != IStatus.ERROR) {
progressMonitor.subTask(JarPackagerMessages.getString("JarFileExportOperation.savingFiles")); //$NON-NLS-1$
saveFiles();
}
} catch (CoreException ex) {
addToStatus(ex);
} finally {
try {
if (fJarWriter != null)
fJarWriter.close();
} catch (CoreException ex) {
addToStatus(ex);
}
progressMonitor.done();
}
}
protected boolean preconditionsOK() {
if (!fJarPackage.areClassFilesExported() && !fJarPackage.areJavaFilesExported()) {
addError(JarPackagerMessages.getString("JarFileExportOperation.noExportTypeChosen"), null); //$NON-NLS-1$
return false;
}
if (fJarPackage.getElements() == null || fJarPackage.getElements().length == 0) {
addError(JarPackagerMessages.getString("JarFileExportOperation.noResourcesSelected"), null); //$NON-NLS-1$
return false;
}
if (fJarPackage.getJarLocation() == null) {
addError(JarPackagerMessages.getString("JarFileExportOperation.invalidJarLocation"), null); //$NON-NLS-1$
return false;
}
if (!fJarPackage.isManifestAccessible()) {
addError(JarPackagerMessages.getString("JarFileExportOperation.manifestDoesNotExist"), null); //$NON-NLS-1$
return false;
}
if (!fJarPackage.isMainClassValid(new BusyIndicatorRunnableContext())) {
addError(JarPackagerMessages.getString("JarFileExportOperation.invalidMainClass"), null); //$NON-NLS-1$
return false;
}
if (fParentShell == null)
// no checking if shell is null
return true;
IFile[] unsavedFiles= getUnsavedFiles();
if (unsavedFiles.length > 0)
return saveModifiedResourcesIfUserConfirms(unsavedFiles);
return true;
}
/**
* 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() {
IEditorPart[] dirtyEditors= getDirtyEditors(fParentShell);
Set unsavedFiles= new HashSet(dirtyEditors.length);
if (dirtyEditors.length > 0) {
List selection= JarPackagerUtil.asResources(fJarPackage.getElements());
for (int i= 0; i < dirtyEditors.length; i++) {
if (dirtyEditors[i].getEditorInput() instanceof IFileEditorInput) {
IFile dirtyFile= ((IFileEditorInput)dirtyEditors[i].getEditorInput()).getFile();
if (JarPackagerUtil.contains(selection, dirtyFile)) {
unsavedFiles.add(dirtyFile);
}
}
}
}
return (IFile[])unsavedFiles.toArray(new IFile[unsavedFiles.size()]);
}
/**
* 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= fParentShell.getDisplay();
if (display == null || display.isDisposed())
return false;
// Ask user to confirm saving of all files
final ConfirmSaveModifiedResourcesDialog dlg= new ConfirmSaveModifiedResourcesDialog(fParentShell, 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;
}
/**
* Asks to confirm to save the modified resources
* and save them if OK is pressed.
*
* @return true if user pressed OK and save was successful.
*/
private boolean saveModifiedResourcesIfUserConfirms(IFile[] dirtyFiles) {
if (confirmSaveModifiedResources(dirtyFiles))
return saveModifiedResources(dirtyFiles);
// Report unsaved files
for (int i= 0; i < dirtyFiles.length; i++)
addError(JarPackagerMessages.getFormattedString("JarFileExportOperation.fileUnsaved", dirtyFiles[i].getFullPath()), null); //$NON-NLS-1$
return false;
}
/**
* Save all of the editors in the workbench.
*
* @return true if successful.
*/
private boolean saveModifiedResources(final IFile[] dirtyFiles) {
// Get display for further UI operations
Display display= fParentShell.getDisplay();
if (display == null || display.isDisposed())
return false;
final boolean[] retVal= new boolean[1];
Runnable runnable= new Runnable() {
public void run() {
try {
new ProgressMonitorDialog(fParentShell).run(false, false, createSaveModifiedResourcesRunnable(dirtyFiles));
retVal[0]= true;
} catch (InvocationTargetException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingModifiedResources"), ex); //$NON-NLS-1$
JavaPlugin.log(ex);
retVal[0]= false;
} catch (InterruptedException ex) {
Assert.isTrue(false); // Can't happen. Operation isn't cancelable.
retVal[0]= false;
}
}
};
display.syncExec(runnable);
return retVal[0];
}
private IRunnableWithProgress createSaveModifiedResourcesRunnable(final IFile[] dirtyFiles) {
return new IRunnableWithProgress() {
public void run(final IProgressMonitor pm) {
IEditorPart[] editorsToSave= getDirtyEditors(fParentShell);
pm.beginTask(JarPackagerMessages.getString("JarFileExportOperation.savingModifiedResources"), editorsToSave.length); //$NON-NLS-1$
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();
}
}
};
}
protected void saveFiles() {
// Save the manifest
if (fJarPackage.areClassFilesExported() && fJarPackage.isManifestGenerated() && fJarPackage.isManifestSaved()) {
try {
saveManifest();
} catch (CoreException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingManifest"), ex); //$NON-NLS-1$
} catch (IOException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingManifest"), ex); //$NON-NLS-1$
}
}
// Save the description
if (fJarPackage.isDescriptionSaved()) {
try {
saveDescription();
} catch (CoreException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingDescription"), ex); //$NON-NLS-1$
} catch (IOException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingDescription"), ex); //$NON-NLS-1$
}
}
}
private IEditorPart[] getDirtyEditors(Shell parent) {
Display display= parent.getDisplay();
final Object[] result= new Object[1];
display.syncExec(
new Runnable() {
public void run() {
result[0]= JavaPlugin.getDirtyEditors();
}
}
);
return (IEditorPart[])result[0];
}
protected void saveDescription() throws CoreException, IOException {
// Adjust JAR package attributes
if (fJarPackage.isManifestReused())
fJarPackage.setGenerateManifest(false);
ByteArrayOutputStream objectStreamOutput= new ByteArrayOutputStream();
IJarDescriptionWriter writer= fJarPackage.createJarDescriptionWriter(objectStreamOutput);
ByteArrayInputStream fileInput= null;
try {
writer.write(fJarPackage);
fileInput= new ByteArrayInputStream(objectStreamOutput.toByteArray());
IFile descriptionFile= fJarPackage.getDescriptionFile();
if (descriptionFile.isAccessible()) {
if (fJarPackage.allowOverwrite() || JarPackagerUtil.askForOverwritePermission(fParentShell, descriptionFile.getFullPath().toString()))
descriptionFile.setContents(fileInput, true, true, null);
} else
descriptionFile.create(fileInput, true, null);
} finally {
if (fileInput != null)
fileInput.close();
if (writer != null)
writer.close();
}
}
protected void saveManifest() throws CoreException, IOException {
ByteArrayOutputStream manifestOutput= new ByteArrayOutputStream();
ByteArrayInputStream fileInput= null;
try {
Manifest manifest= fJarPackage.getManifestProvider().create(fJarPackage);
manifest.write(manifestOutput);
fileInput= new ByteArrayInputStream(manifestOutput.toByteArray());
IFile manifestFile= fJarPackage.getManifestFile();
if (manifestFile.isAccessible()) {
if (fJarPackage.allowOverwrite() || JarPackagerUtil.askForOverwritePermission(fParentShell, manifestFile.getFullPath().toString()))
manifestFile.setContents(fileInput, true, true, null);
} else
manifestFile.create(fileInput, true, null);
} finally {
if (manifestOutput != null)
manifestOutput.close();
if (fileInput != null)
fileInput.close();
}
}
private boolean isAutoBuilding() {
return ResourcesPlugin.getWorkspace().getDescription().isAutoBuilding();
}
private boolean isCompilerGeneratingSourceFileAttribute() {
Object value= JavaCore.getOptions().get(JavaCore.COMPILER_SOURCE_FILE_ATTR);
if (value instanceof String)
return "generate".equalsIgnoreCase((String)value); //$NON-NLS-1$
else
return true; // default
}
private void buildProjects(IProgressMonitor progressMonitor) {
Set builtProjects= new HashSet(10);
Object[] elements= fJarPackage.getElements();
for (int i= 0; i < elements.length; i++) {
IProject project= null;
Object element= elements[i];
if (element instanceof IResource)
project= ((IResource)element).getProject();
else if (element instanceof IJavaElement)
project= ((IJavaElement)element).getJavaProject().getProject();
if (project != null && !builtProjects.contains(project)) {
try {
project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, progressMonitor);
} catch (CoreException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.errorDuringProjectBuild", project.getFullPath()); //$NON-NLS-1$
addError(message, ex);
} finally {
// don't try to build same project a second time even if it failed
builtProjects.add(project);
}
}
}
}
/**
* Tells whether the given resource (or its children) have compile errors.
* The method acts on the current build state and does not recompile.
*
* @param resource the resource to check for errors
* @return <code>true</code> if the resource (and its children) are error free
* @throws import org.eclipse.core.runtime.CoreException if there's a marker problem
*/
private boolean hasCompileErrors(IResource resource) throws CoreException {
IMarker[] problemMarkers= resource.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE);
for (int i= 0; i < problemMarkers.length; i++) {
if (problemMarkers[i].getAttribute(IMarker.SEVERITY, -1) == IMarker.SEVERITY_ERROR)
return true;
}
return false;
}
/**
* Tells whether the given resource (or its children) have compile errors.
* The method acts on the current build state and does not recompile.
*
* @param resource the resource to check for errors
* @return <code>true</code> if the resource (and its children) are error free
* @throws import org.eclipse.core.runtime.CoreException if there's a marker problem
*/
private boolean hasCompileWarnings(IResource resource) throws CoreException {
IMarker[] problemMarkers= resource.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE);
for (int i= 0; i < problemMarkers.length; i++) {
if (problemMarkers[i].getAttribute(IMarker.SEVERITY, -1) == IMarker.SEVERITY_WARNING)
return true;
}
return false;
}
private boolean mustUseSourceFolderHierarchy() {
return fJarPackage.useSourceFolderHierarchy() && fJarPackage.areJavaFilesExported() && !fJarPackage.areClassFilesExported();
}
}
|
26,498 |
Bug 26498 No feedback when deleting empty package which is not a leaf [refactoring]
|
Build 20021114 1. Disable filtering of empty packages 2. Select an empty package which is not a leaf (e.g. junit.samples) 2. Delete it ==> no feedback, nothing happens. I see two solutions 1) Dialog informs the user about the fact that this thing can't be removed 2) Dialog asks the user if he want to delete everything below two This wasn't an issue so far but when deleting empty nodes in the Package Explorer with hierarchical layout it is weird to get no feedback.
|
resolved fixed
|
263f794
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-20T16:20:24Z | 2002-11-15T17:06:40Z |
org.eclipse.jdt.ui/core
| |
26,498 |
Bug 26498 No feedback when deleting empty package which is not a leaf [refactoring]
|
Build 20021114 1. Disable filtering of empty packages 2. Select an empty package which is not a leaf (e.g. junit.samples) 2. Delete it ==> no feedback, nothing happens. I see two solutions 1) Dialog informs the user about the fact that this thing can't be removed 2) Dialog asks the user if he want to delete everything below two This wasn't an issue so far but when deleting empty nodes in the Package Explorer with hierarchical layout it is weird to get no feedback.
|
resolved fixed
|
263f794
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-20T16:20:24Z | 2002-11-15T17:06:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/reorg/DeleteRefactoring.java
| |
26,102 |
Bug 26102 inline method: NPE in SourceAnalyzer
|
smoke for 1113 junit Money line: 23 return m.addMoney(this); select 'addMoney' and choose 'inline' method nothing happens and 1 entry in the log: !MESSAGE java.lang.NullPointerException !STACK 0 java.lang.NullPointerException at org.eclipse.jdt.internal.corext.refactoring.code.SourceAnalyzer$ActivationAnalyz er.getLastNode(SourceAnalyzer.java:103) at org.eclipse.jdt.internal.corext.refactoring.code.SourceAnalyzer$ActivationAnalyz er.<init>(SourceAnalyzer.java:70) at org.eclipse.jdt.internal.corext.refactoring.code.SourceAnalyzer.checkActivation (SourceAnalyzer.java:219) at org.eclipse.jdt.internal.corext.refactoring.code.SourceProvider.checkActivation (SourceProvider.java:86) at org.eclipse.jdt.internal.corext.refactoring.code.InlineMethodRefactoring.checkAc tivation(InlineMethodRefactoring.java:151) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:69) at org.eclipse.jdt.ui.actions.InlineMethodAction.run (InlineMethodAction.java:80) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:193) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:169) at org.eclipse.jface.action.Action.runWithEvent(Action.java:769) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:411) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java:365) at org.eclipse.jface.action.ActionContributionItem.access$0 (ActionContributionItem.java:356) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java:48) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1418) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:831) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539)
|
resolved fixed
|
c2ba53b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-20T17:17:38Z | 2002-11-13T15:06:40Z |
org.eclipse.jdt.ui/core
| |
26,102 |
Bug 26102 inline method: NPE in SourceAnalyzer
|
smoke for 1113 junit Money line: 23 return m.addMoney(this); select 'addMoney' and choose 'inline' method nothing happens and 1 entry in the log: !MESSAGE java.lang.NullPointerException !STACK 0 java.lang.NullPointerException at org.eclipse.jdt.internal.corext.refactoring.code.SourceAnalyzer$ActivationAnalyz er.getLastNode(SourceAnalyzer.java:103) at org.eclipse.jdt.internal.corext.refactoring.code.SourceAnalyzer$ActivationAnalyz er.<init>(SourceAnalyzer.java:70) at org.eclipse.jdt.internal.corext.refactoring.code.SourceAnalyzer.checkActivation (SourceAnalyzer.java:219) at org.eclipse.jdt.internal.corext.refactoring.code.SourceProvider.checkActivation (SourceProvider.java:86) at org.eclipse.jdt.internal.corext.refactoring.code.InlineMethodRefactoring.checkAc tivation(InlineMethodRefactoring.java:151) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:69) at org.eclipse.jdt.ui.actions.InlineMethodAction.run (InlineMethodAction.java:80) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:193) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:169) at org.eclipse.jface.action.Action.runWithEvent(Action.java:769) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:411) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java:365) at org.eclipse.jface.action.ActionContributionItem.access$0 (ActionContributionItem.java:356) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java:48) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1418) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:831) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539)
|
resolved fixed
|
c2ba53b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-20T17:17:38Z | 2002-11-13T15:06:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/SourceAnalyzer.java
| |
26,074 |
Bug 26074 getter and setter wizard doesn't work for subclasses
|
With the following code block: public class Foo { protected String someString; } class Bar extends Foo { } If the Generate Getter and Setter wizard is opened inside the Bar class, a message indicating that the "operation not applicable to current text selection". Since a getter/setter has not been created in the superclass Foo, I think that Bar should be able to create the methods. If a field is added to Bar, the wizard is displayed but it still does not allow a getter/setter to be built for the someString field.
|
resolved wontfix
|
863bb44
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-21T11:50:52Z | 2002-11-13T04:00:00Z |
org.eclipse.jdt.ui/core
| |
26,074 |
Bug 26074 getter and setter wizard doesn't work for subclasses
|
With the following code block: public class Foo { protected String someString; } class Bar extends Foo { } If the Generate Getter and Setter wizard is opened inside the Bar class, a message indicating that the "operation not applicable to current text selection". Since a getter/setter has not been created in the superclass Foo, I think that Bar should be able to create the methods. If a field is added to Bar, the wizard is displayed but it still does not allow a getter/setter to be built for the someString field.
|
resolved wontfix
|
863bb44
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-21T11:50:52Z | 2002-11-13T04:00:00Z |
extension/org/eclipse/jdt/internal/corext/codemanipulation/ImportsStructure.java
| |
26,641 |
Bug 26641 No option to disable "Assignment ... has no effect"
|
2.1 M3 I am missing an option to disable the compiler warning upon assigning a variable to itself...
|
resolved fixed
|
09e5d24
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-21T13:03:29Z | 2002-11-19T07:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/CompilerConfigurationBlock.java
|
package org.eclipse.jdt.internal.ui.preferences;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
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.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.dialogs.StatusUtil;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.util.PixelConverter;
import org.eclipse.jdt.internal.ui.util.TabFolderLayout;
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.IListAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField;
/**
*/
public class CompilerConfigurationBlock {
// 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_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_STATIC_ACCESS_RECEIVER= JavaCore.COMPILER_PB_STATIC_ACCESS_RECEIVER;
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_PB_INCOMPLETE_BUILDPATH= JavaCore.CORE_INCOMPLETE_CLASSPATH;
private static final String PREF_PB_CIRCULAR_BUILDPATH= JavaCore.CORE_CIRCULAR_CLASSPATH;
private static final String PREF_COMPILER_PB_DEPRECATION_IN_DEPRECATED_CODE= JavaCore.COMPILER_PB_DEPRECATION_IN_DEPRECATED_CODE;
private static final String PREF_COMPILER_TASK_TAGS= JavaCore.COMPILER_TASK_TAGS;
private static final String PREF_COMPILER_TASK_PRIORITIES= JavaCore.COMPILER_TASK_PRIORITIES;
private static final String PREF_PB_DUPLICATE_RESOURCE= JavaCore.CORE_JAVA_BUILD_DUPLICATE_RESOURCE;
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 ENABLED= JavaCore.ENABLED;
private static final String DISABLED= JavaCore.DISABLED;
private static final String PRIORITY_HIGH= JavaCore.COMPILER_TASK_PRIORITY_HIGH;
private static final String PRIORITY_NORMAL= JavaCore.COMPILER_TASK_PRIORITY_NORMAL;
private static final String PRIORITY_LOW= JavaCore.COMPILER_TASK_PRIORITY_LOW;
private static final String DEFAULT= "default"; //$NON-NLS-1$
private static final String USER= "user"; //$NON-NLS-1$
private static String[] getAllKeys() {
return new String[] {
PREF_LOCAL_VARIABLE_ATTR, PREF_LINE_NUMBER_ATTR, PREF_SOURCE_FILE_ATTR, PREF_CODEGEN_UNUSED_LOCAL,
PREF_CODEGEN_TARGET_PLATFORM, PREF_PB_UNREACHABLE_CODE, PREF_PB_INVALID_IMPORT, PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD,
PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME, PREF_PB_DEPRECATION, PREF_PB_HIDDEN_CATCH_BLOCK, PREF_PB_UNUSED_LOCAL,
PREF_PB_UNUSED_PARAMETER, PREF_PB_SYNTHETIC_ACCESS_EMULATION, PREF_PB_NON_EXTERNALIZED_STRINGS,
PREF_PB_ASSERT_AS_IDENTIFIER, PREF_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_COMPILER_PB_DEPRECATION_IN_DEPRECATED_CODE,
PREF_COMPILER_TASK_TAGS, PREF_COMPILER_TASK_PRIORITIES, PREF_PB_DUPLICATE_RESOURCE
};
}
private static class ControlData {
private String fKey;
private String[] fValues;
public ControlData(String key, String[] values) {
fKey= key;
fValues= values;
}
public String getKey() {
return fKey;
}
public String getValue(boolean selection) {
int index= selection ? 0 : 1;
return fValues[index];
}
public String getValue(int index) {
return fValues[index];
}
public int getSelection(String value) {
for (int i= 0; i < fValues.length; i++) {
if (value.equals(fValues[i])) {
return i;
}
}
throw new IllegalArgumentException();
}
}
public static class TodoTask {
public String name;
public String priority;
}
private static class TodoTaskLabelProvider extends LabelProvider implements ITableLabelProvider {
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object)
*/
public Image getImage(Object element) {
return null; // JavaPluginImages.get(JavaPluginImages.IMG_OBJS_REFACTORING_INFO);
}
/* (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) {
return null;
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, int)
*/
public String getColumnText(Object element, int columnIndex) {
TodoTask task= (TodoTask) element;
if (columnIndex == 0) {
return task.name;
} else {
if (PRIORITY_HIGH.equals(task.priority)) {
return JavaUIMessages.getString("CompilerConfigurationBlock.markers.tasks.high.priority");
} else if (PRIORITY_NORMAL.equals(task.priority)) {
return JavaUIMessages.getString("CompilerConfigurationBlock.markers.tasks.normal.priority");
} else {
return JavaUIMessages.getString("CompilerConfigurationBlock.markers.tasks.low.priority");
}
}
}
}
private Map fWorkingValues;
private ArrayList fCheckBoxes;
private ArrayList fComboBoxes;
private ArrayList fTextBoxes;
private SelectionListener fSelectionListener;
private ModifyListener fTextModifyListener;
private ArrayList fComplianceControls;
private PixelConverter fPixelConverter;
private IStatus fComplianceStatus, fMaxNumberProblemsStatus, fResourceFilterStatus, fTaskTagsStatus;
private IStatusChangeListener fContext;
private Shell fShell;
private IJavaProject fProject; // project or null
private ListDialogField fTodoTasksList;
public CompilerConfigurationBlock(IStatusChangeListener context, IJavaProject project) {
fContext= context;
fProject= project;
fWorkingValues= getOptions(true);
fWorkingValues.put(INTR_DEFAULT_COMPLIANCE, getCurrentCompliance());
fCheckBoxes= new ArrayList();
fComboBoxes= new ArrayList();
fTextBoxes= new ArrayList(2);
fComplianceControls= new ArrayList();
fSelectionListener= new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {}
public void widgetSelected(SelectionEvent e) {
controlChanged(e.widget);
}
};
fTextModifyListener= new ModifyListener() {
public void modifyText(ModifyEvent e) {
textChanged((Text) e.widget);
}
};
IListAdapter adapter= new IListAdapter() {
public void customButtonPressed(DialogField field, int index) {
doTodoButtonPressed(index);
}
public void selectionChanged(DialogField field) {
fTodoTasksList.enableButton(3, fTodoTasksList.getSelectedElements().size() == 1);
}
};
String[] buttons= new String[] {
/* 0 */ JavaUIMessages.getString("CompilerConfigurationBlock.markers.tasks.add.button"),
/* 1 */ JavaUIMessages.getString("CompilerConfigurationBlock.markers.tasks.remove.button"),
null,
/* 3 */ JavaUIMessages.getString("CompilerConfigurationBlock.markers.tasks.edit.button"),
};
fTodoTasksList= new ListDialogField(adapter, buttons, new TodoTaskLabelProvider());
fTodoTasksList.setLabelText(JavaUIMessages.getString("CompilerConfigurationBlock.markers.tasks.label"));
fTodoTasksList.setRemoveButtonIndex(1);
String[] columnsHeaders= new String[] {
JavaUIMessages.getString("CompilerConfigurationBlock.markers.tasks.name.column"),
JavaUIMessages.getString("CompilerConfigurationBlock.markers.tasks.priority.column"),
};
fTodoTasksList.setTableColumns(new ListDialogField.ColumnsDescription(columnsHeaders, false));
unpackTodoTasks();
if (fTodoTasksList.getSize() > 0) {
fTodoTasksList.selectFirstElement();
} else {
fTodoTasksList.enableButton(3, false);
}
fComplianceStatus= new StatusInfo();
fMaxNumberProblemsStatus= new StatusInfo();
fResourceFilterStatus= new StatusInfo();
fTaskTagsStatus= new StatusInfo();
}
private Map getOptions(boolean inheritJavaCoreOptions) {
if (fProject != null) {
return fProject.getOptions(inheritJavaCoreOptions);
} else {
return JavaCore.getOptions();
}
}
public boolean hasProjectSpecificOptions() {
if (fProject != null) {
Map settings= fProject.getOptions(false);
String[] allKeys= getAllKeys();
for (int i= 0; i < allKeys.length; i++) {
if (settings.get(allKeys[i]) != null) {
return true;
}
}
}
return false;
}
private void setOptions(Map map) {
if (fProject != null) {
fProject.setOptions(map);
} else {
JavaCore.setOptions((Hashtable) map);
}
}
/**
* Returns the shell.
* @return Shell
*/
public Shell getShell() {
return fShell;
}
/**
* @see PreferencePage#createContents(Composite)
*/
protected Control createContents(Composite parent) {
fPixelConverter= new PixelConverter(parent);
fShell= parent.getShell();
TabFolder folder= new TabFolder(parent, SWT.NONE);
folder.setLayout(new TabFolderLayout());
folder.setLayoutData(new GridData(GridData.FILL_BOTH));
Composite warningsComposite= createWarningsTabContent(folder);
Composite markersComposite= createMarkersTabContent(folder);
Composite codeGenComposite= createCodeGenTabContent(folder);
Composite complianceComposite= createComplianceTabContent(folder);
Composite othersComposite= createOthersTabContent(folder);
TabItem item= new TabItem(folder, SWT.NONE);
item.setText(JavaUIMessages.getString("CompilerConfigurationBlock.warnings.tabtitle")); //$NON-NLS-1$
item.setControl(warningsComposite);
item= new TabItem(folder, SWT.NONE);
item.setText(JavaUIMessages.getString("CompilerConfigurationBlock.markers.tabtitle")); //$NON-NLS-1$
item.setControl(markersComposite);
item= new TabItem(folder, SWT.NONE);
item.setText(JavaUIMessages.getString("CompilerConfigurationBlock.generation.tabtitle")); //$NON-NLS-1$
item.setControl(codeGenComposite);
item= new TabItem(folder, SWT.NONE);
item.setText(JavaUIMessages.getString("CompilerConfigurationBlock.compliance.tabtitle")); //$NON-NLS-1$
item.setControl(complianceComposite);
item= new TabItem(folder, SWT.NONE);
item.setText(JavaUIMessages.getString("CompilerConfigurationBlock.others.tabtitle")); //$NON-NLS-1$
item.setControl(othersComposite);
validateSettings(null, null);
return folder;
}
private Composite createMarkersTabContent(TabFolder folder) {
String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE };
String[] errorWarningIgnoreLabels= new String[] {
JavaUIMessages.getString("CompilerConfigurationBlock.error"), //$NON-NLS-1$
JavaUIMessages.getString("CompilerConfigurationBlock.warning"), //$NON-NLS-1$
JavaUIMessages.getString("CompilerConfigurationBlock.ignore") //$NON-NLS-1$
};
String[] enabledDisabled= new String[] { ENABLED, DISABLED };
Composite markersComposite= new Composite(folder, SWT.NULL);
markersComposite.setLayout(new GridLayout());
GridLayout layout= new GridLayout();
layout.numColumns= 2;
Group group= new Group(markersComposite, SWT.NONE);
group.setText(JavaUIMessages.getString("CompilerConfigurationBlock.markers.deprecated.label"));
group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
group.setLayout(layout);
String label= JavaUIMessages.getString("CompilerConfigurationBlock.pb_deprecation.label"); //$NON-NLS-1$
addComboBox(group, label, PREF_PB_DEPRECATION, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= JavaUIMessages.getString("CompilerConfigurationBlock.pb_deprecation_in_deprecation.label"); //$NON-NLS-1$
addCheckBox(group, label, PREF_COMPILER_PB_DEPRECATION_IN_DEPRECATED_CODE, enabledDisabled, 0);
layout= new GridLayout();
layout.numColumns= 2;
group= new Group(markersComposite, SWT.NONE);
group.setText(JavaUIMessages.getString("CompilerConfigurationBlock.markers.taskmarkers.label"));
group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
group.setLayout(layout);
fTodoTasksList.doFillIntoGrid(group, 3);
LayoutUtil.setHorizontalSpan(fTodoTasksList.getLabelControl(null), 2);
LayoutUtil.setHorizontalGrabbing(fTodoTasksList.getListControl(null));
layout= new GridLayout();
layout.numColumns= 2;
group= new Group(markersComposite, SWT.NONE);
group.setText(JavaUIMessages.getString("CompilerConfigurationBlock.markers.nls.label"));
group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
group.setLayout(layout);
label= JavaUIMessages.getString("CompilerConfigurationBlock.pb_non_externalized_strings.label"); //$NON-NLS-1$
addComboBox(group, label, PREF_PB_NON_EXTERNALIZED_STRINGS, errorWarningIgnore, errorWarningIgnoreLabels, 0);
return markersComposite;
}
private Composite createOthersTabContent(TabFolder folder) {
String[] abortIgnoreValues= new String[] { ABORT, IGNORE };
String[] errorWarning= new String[] { ERROR, WARNING };
String[] errorWarningLabels= new String[] {
JavaUIMessages.getString("CompilerConfigurationBlock.error"), //$NON-NLS-1$
JavaUIMessages.getString("CompilerConfigurationBlock.warning") //$NON-NLS-1$
};
GridLayout layout= new GridLayout();
layout.numColumns= 2;
Composite othersComposite= new Composite(folder, SWT.NULL);
othersComposite.setLayout(layout);
Label description= new Label(othersComposite, SWT.WRAP);
description.setText(JavaUIMessages.getString("CompilerConfigurationBlock.build_warnings.description")); //$NON-NLS-1$
GridData gd= new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL);
gd.horizontalSpan= 2;
// gd.widthHint= convertWidthInCharsToPixels(50);
description.setLayoutData(gd);
Composite combos= new Composite(othersComposite, SWT.NULL);
gd= new GridData(GridData.FILL | GridData.GRAB_HORIZONTAL);
gd.horizontalSpan= 2;
combos.setLayoutData(gd);
GridLayout cl= new GridLayout();
cl.numColumns=2; cl.marginWidth= 0; cl.marginHeight= 0;
combos.setLayout(cl);
String label= JavaUIMessages.getString("CompilerConfigurationBlock.pb_incomplete_build_path.label"); //$NON-NLS-1$
addComboBox(combos, label, PREF_PB_INCOMPLETE_BUILDPATH, errorWarning, errorWarningLabels, 0);
label= JavaUIMessages.getString("CompilerConfigurationBlock.pb_build_path_cycles.label"); //$NON-NLS-1$
addComboBox(combos, label, PREF_PB_CIRCULAR_BUILDPATH, errorWarning, errorWarningLabels, 0);
label= JavaUIMessages.getString("CompilerConfigurationBlock.pb_duplicate_resources.label"); //$NON-NLS-1$
addComboBox(combos, label, PREF_PB_DUPLICATE_RESOURCE, errorWarning, errorWarningLabels, 0);
label= JavaUIMessages.getString("CompilerConfigurationBlock.build_invalid_classpath.label"); //$NON-NLS-1$
addCheckBox(othersComposite, label, PREF_BUILD_INVALID_CLASSPATH, abortIgnoreValues, 0);
description= new Label(othersComposite, SWT.WRAP);
description.setText(JavaUIMessages.getString("CompilerConfigurationBlock.resource_filter.description")); //$NON-NLS-1$
gd= new GridData(GridData.FILL);
gd.horizontalSpan= 2;
gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(60);
description.setLayoutData(gd);
label= JavaUIMessages.getString("CompilerConfigurationBlock.resource_filter.label"); //$NON-NLS-1$
Text text= addTextField(othersComposite, label, PREF_RESOURCE_FILTER);
gd= (GridData) text.getLayoutData();
gd.grabExcessHorizontalSpace= true;
gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(10);
return othersComposite;
}
private Composite createWarningsTabContent(Composite folder) {
String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE };
String[] errorWarningIgnoreLabels= new String[] {
JavaUIMessages.getString("CompilerConfigurationBlock.error"), //$NON-NLS-1$
JavaUIMessages.getString("CompilerConfigurationBlock.warning"), //$NON-NLS-1$
JavaUIMessages.getString("CompilerConfigurationBlock.ignore") //$NON-NLS-1$
};
GridLayout layout= new GridLayout();
layout.numColumns= 2;
layout.verticalSpacing= 2;
Composite warningsComposite= new Composite(folder, SWT.NULL);
warningsComposite.setLayout(layout);
Label description= new Label(warningsComposite, SWT.WRAP);
description.setText(JavaUIMessages.getString("CompilerConfigurationBlock.warnings.description")); //$NON-NLS-1$
GridData gd= new GridData();
gd.horizontalSpan= 2;
gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(50);
description.setLayoutData(gd);
String label= JavaUIMessages.getString("CompilerConfigurationBlock.pb_unreachable_code.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_UNREACHABLE_CODE, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= JavaUIMessages.getString("CompilerConfigurationBlock.pb_invalid_import.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_INVALID_IMPORT, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= JavaUIMessages.getString("CompilerConfigurationBlock.pb_unused_local.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_UNUSED_LOCAL, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= JavaUIMessages.getString("CompilerConfigurationBlock.pb_overriding_pkg_dflt.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= JavaUIMessages.getString("CompilerConfigurationBlock.pb_method_naming.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= JavaUIMessages.getString("CompilerConfigurationBlock.pb_hidden_catchblock.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_HIDDEN_CATCH_BLOCK, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= JavaUIMessages.getString("CompilerConfigurationBlock.pb_unused_imports.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_UNUSED_IMPORT, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= JavaUIMessages.getString("CompilerConfigurationBlock.pb_unused_parameter.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_UNUSED_PARAMETER, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= JavaUIMessages.getString("CompilerConfigurationBlock.pb_static_access_receiver.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_STATIC_ACCESS_RECEIVER, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= JavaUIMessages.getString("CompilerConfigurationBlock.pb_synth_access_emul.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_SYNTHETIC_ACCESS_EMULATION, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= JavaUIMessages.getString("CompilerConfigurationBlock.pb_max_per_unit.label"); //$NON-NLS-1$
Text text= addTextField(warningsComposite, label, PREF_PB_MAX_PER_UNIT);
text.setTextLimit(6);
return warningsComposite;
}
private Composite createCodeGenTabContent(Composite folder) {
String[] generateValues= new String[] { GENERATE, DO_NOT_GENERATE };
GridLayout layout= new GridLayout();
layout.numColumns= 2;
Composite codeGenComposite= new Composite(folder, SWT.NULL);
codeGenComposite.setLayout(layout);
String label= JavaUIMessages.getString("CompilerConfigurationBlock.variable_attr.label"); //$NON-NLS-1$
addCheckBox(codeGenComposite, label, PREF_LOCAL_VARIABLE_ATTR, generateValues, 0);
label= JavaUIMessages.getString("CompilerConfigurationBlock.line_number_attr.label"); //$NON-NLS-1$
addCheckBox(codeGenComposite, label, PREF_LINE_NUMBER_ATTR, generateValues, 0);
label= JavaUIMessages.getString("CompilerConfigurationBlock.source_file_attr.label"); //$NON-NLS-1$
addCheckBox(codeGenComposite, label, PREF_SOURCE_FILE_ATTR, generateValues, 0);
label= JavaUIMessages.getString("CompilerConfigurationBlock.codegen_unused_local.label"); //$NON-NLS-1$
addCheckBox(codeGenComposite, label, PREF_CODEGEN_UNUSED_LOCAL, new String[] { PRESERVE, OPTIMIZE_OUT }, 0);
return codeGenComposite;
}
private Composite createComplianceTabContent(Composite folder) {
GridLayout layout= new GridLayout();
layout.numColumns= 2;
Composite complianceComposite= new Composite(folder, SWT.NULL);
complianceComposite.setLayout(layout);
String[] values34= new String[] { VERSION_1_3, VERSION_1_4 };
String[] values34Labels= new String[] {
JavaUIMessages.getString("CompilerConfigurationBlock.version13"), //$NON-NLS-1$
JavaUIMessages.getString("CompilerConfigurationBlock.version14") //$NON-NLS-1$
};
String label= JavaUIMessages.getString("CompilerConfigurationBlock.compiler_compliance.label"); //$NON-NLS-1$
addComboBox(complianceComposite, label, PREF_COMPLIANCE, values34, values34Labels, 0);
label= JavaUIMessages.getString("CompilerConfigurationBlock.default_settings.label"); //$NON-NLS-1$
addCheckBox(complianceComposite, label, INTR_DEFAULT_COMPLIANCE, new String[] { DEFAULT, USER }, 0);
int indent= fPixelConverter.convertWidthInCharsToPixels(2);
Control[] otherChildren= complianceComposite.getChildren();
String[] values14= new String[] { VERSION_1_1, VERSION_1_2, VERSION_1_3, VERSION_1_4 };
String[] values14Labels= new String[] {
JavaUIMessages.getString("CompilerConfigurationBlock.version11"), //$NON-NLS-1$
JavaUIMessages.getString("CompilerConfigurationBlock.version12"), //$NON-NLS-1$
JavaUIMessages.getString("CompilerConfigurationBlock.version13"), //$NON-NLS-1$
JavaUIMessages.getString("CompilerConfigurationBlock.version14") //$NON-NLS-1$
};
label= JavaUIMessages.getString("CompilerConfigurationBlock.codegen_targetplatform.label"); //$NON-NLS-1$
addComboBox(complianceComposite, label, PREF_CODEGEN_TARGET_PLATFORM, values14, values14Labels, indent);
label= JavaUIMessages.getString("CompilerConfigurationBlock.source_compatibility.label"); //$NON-NLS-1$
addComboBox(complianceComposite, label, PREF_SOURCE_COMPATIBILITY, values34, values34Labels, indent);
String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE };
String[] errorWarningIgnoreLabels= new String[] {
JavaUIMessages.getString("CompilerConfigurationBlock.error"), //$NON-NLS-1$
JavaUIMessages.getString("CompilerConfigurationBlock.warning"), //$NON-NLS-1$
JavaUIMessages.getString("CompilerConfigurationBlock.ignore") //$NON-NLS-1$
};
label= JavaUIMessages.getString("CompilerConfigurationBlock.pb_assert_as_identifier.label"); //$NON-NLS-1$
addComboBox(complianceComposite, label, PREF_PB_ASSERT_AS_IDENTIFIER, errorWarningIgnore, errorWarningIgnoreLabels, indent);
Control[] allChildren= complianceComposite.getChildren();
fComplianceControls.addAll(Arrays.asList(allChildren));
fComplianceControls.removeAll(Arrays.asList(otherChildren));
return complianceComposite;
}
private void addCheckBox(Composite parent, String label, String key, String[] values, int indent) {
ControlData data= new ControlData(key, values);
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= 2;
gd.horizontalIndent= indent;
Button checkBox= new Button(parent, SWT.CHECK);
checkBox.setText(label);
checkBox.setData(data);
checkBox.setLayoutData(gd);
checkBox.addSelectionListener(fSelectionListener);
String currValue= (String)fWorkingValues.get(key);
checkBox.setSelection(data.getSelection(currValue) == 0);
fCheckBoxes.add(checkBox);
}
private void addComboBox(Composite parent, String label, String key, String[] values, String[] valueLabels, int indent) {
ControlData data= new ControlData(key, values);
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
gd.horizontalIndent= indent;
Label labelControl= new Label(parent, SWT.LEFT | SWT.WRAP);
labelControl.setText(label);
labelControl.setLayoutData(gd);
Combo comboBox= new Combo(parent, SWT.READ_ONLY);
comboBox.setItems(valueLabels);
comboBox.setData(data);
comboBox.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
comboBox.addSelectionListener(fSelectionListener);
String currValue= (String)fWorkingValues.get(key);
comboBox.select(data.getSelection(currValue));
fComboBoxes.add(comboBox);
}
private Text addTextField(Composite parent, String label, String key) {
Label labelControl= new Label(parent, SWT.NONE);
labelControl.setText(label);
labelControl.setLayoutData(new GridData());
Text textBox= new Text(parent, SWT.BORDER | SWT.SINGLE);
textBox.setData(key);
textBox.setLayoutData(new GridData());
String currValue= (String) fWorkingValues.get(key);
textBox.setText(currValue);
textBox.addModifyListener(fTextModifyListener);
textBox.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
fTextBoxes.add(textBox);
return textBox;
}
private void controlChanged(Widget widget) {
ControlData data= (ControlData) widget.getData();
String newValue= null;
if (widget instanceof Button) {
newValue= data.getValue(((Button)widget).getSelection());
} else if (widget instanceof Combo) {
newValue= data.getValue(((Combo)widget).getSelectionIndex());
} else {
return;
}
fWorkingValues.put(data.getKey(), newValue);
validateSettings(data.getKey(), newValue);
}
private void textChanged(Text textControl) {
String key= (String) textControl.getData();
String number= textControl.getText();
fWorkingValues.put(key, number);
validateSettings(key, number);
}
private boolean checkValue(String key, String value) {
return value.equals(fWorkingValues.get(key));
}
/* (non-javadoc)
* Update fields and validate.
* @param changedKey Key that changed, or null, if all changed.
*/
private void validateSettings(String changedKey, String newValue) {
if (changedKey != null) {
if (INTR_DEFAULT_COMPLIANCE.equals(changedKey)) {
updateComplianceEnableState();
if (DEFAULT.equals(newValue)) {
updateComplianceDefaultSettings();
}
} 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_COMPILER_TASK_TAGS.equals(changedKey)) {
fTaskTagsStatus= validateTaskTags();
} else {
return;
}
} else {
updateComplianceEnableState();
fComplianceStatus= validateCompliance();
fMaxNumberProblemsStatus= validateMaxNumberProblems();
fResourceFilterStatus= validateResourceFilters();
fTaskTagsStatus= validateTaskTags();
}
IStatus status= StatusUtil.getMostSevere(new IStatus[] { fComplianceStatus, fMaxNumberProblemsStatus, fResourceFilterStatus, fTaskTagsStatus });
fContext.statusChanged(status);
}
private IStatus validateCompliance() {
StatusInfo status= new StatusInfo();
if (checkValue(PREF_COMPLIANCE, VERSION_1_3)) {
if (checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_4)) {
status.setError(JavaUIMessages.getString("CompilerConfigurationBlock.cpl13src14.error")); //$NON-NLS-1$
return status;
} else if (checkValue(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_4)) {
status.setError(JavaUIMessages.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(JavaUIMessages.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(JavaUIMessages.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(JavaUIMessages.getString("CompilerConfigurationBlock.empty_input")); //$NON-NLS-1$
} else {
try {
int value= Integer.parseInt(number);
if (value <= 0) {
status.setError(JavaUIMessages.getFormattedString("CompilerConfigurationBlock.invalid_input", number)); //$NON-NLS-1$
}
} catch (NumberFormatException e) {
status.setError(JavaUIMessages.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);
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= JavaUIMessages.getFormattedString("CompilerConfigurationBlock.filter.invalidsegment.error", status.getMessage()); //$NON-NLS-1$
return new StatusInfo(IStatus.ERROR, message);
}
}
return new StatusInfo();
}
private IStatus validateTaskTags() {
return new StatusInfo();
}
private String[] getTokens(String text) {
StringTokenizer tok= new StringTokenizer(text, ","); //$NON-NLS-1$
int nTokens= tok.countTokens();
String[] res= new String[nTokens];
for (int i= 0; i < res.length; i++) {
res[i]= tok.nextToken();
}
return res;
}
/*
* 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, ERROR);
fWorkingValues.put(PREF_SOURCE_COMPATIBILITY, VERSION_1_4);
fWorkingValues.put(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_4);
}
updateControls();
}
/*
* Evaluate if the current compliance setting correspond to a default setting
*/
private String getCurrentCompliance() {
Object complianceLevel= fWorkingValues.get(PREF_COMPLIANCE);
if ((VERSION_1_3.equals(complianceLevel)
&& checkValue(PREF_PB_ASSERT_AS_IDENTIFIER, IGNORE)
&& checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_3)
&& checkValue(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_1))
|| (VERSION_1_4.equals(complianceLevel)
&& checkValue(PREF_PB_ASSERT_AS_IDENTIFIER, ERROR)
&& checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_4)
&& checkValue(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_4))) {
return DEFAULT;
}
return USER;
}
public boolean performOk(boolean enabled) {
packTodoTasks();
String[] allKeys= getAllKeys();
Map actualOptions= getOptions(false);
// preserve other options
boolean hasChanges= false;
for (int i= 0; i < allKeys.length; i++) {
String key= allKeys[i];
String oldVal= (String) actualOptions.get(key);
String val= null;
if (enabled) {
val= (String) fWorkingValues.get(key);
if (!val.equals(oldVal)) {
hasChanges= true;
actualOptions.put(key, val);
}
} else {
if (oldVal != null) {
actualOptions.remove(key);
hasChanges= true;
}
}
}
if (hasChanges) {
String title= JavaUIMessages.getString("CompilerConfigurationBlock.needsbuild.title"); //$NON-NLS-1$
String message;
if (fProject == null) {
message= JavaUIMessages.getString("CompilerConfigurationBlock.needsfullbuild.message"); //$NON-NLS-1$
} else {
message= JavaUIMessages.getString("CompilerConfigurationBlock.needsprojectbuild.message"); //$NON-NLS-1$
}
MessageDialog dialog= new MessageDialog(getShell(), title, null, message, MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL }, 2);
int res= dialog.open();
if (res != 0 && res != 1) {
return false;
}
setOptions(actualOptions);
if (res == 0) {
doFullBuild();
}
}
return true;
}
private static boolean openQuestion(Shell parent, String title, String message) {
MessageDialog dialog= new MessageDialog(parent, title, null, message, MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL }, 2);
return dialog.open() == 0;
}
private void doFullBuild() {
ProgressMonitorDialog dialog= new ProgressMonitorDialog(getShell());
try {
dialog.run(true, true, new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException {
try {
if (fProject != null) {
fProject.getProject().build(IncrementalProjectBuilder.FULL_BUILD, monitor);
} else {
JavaPlugin.getWorkspace().build(IncrementalProjectBuilder.FULL_BUILD, monitor);
}
} catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
});
} catch (InterruptedException e) {
// cancelled by user
} catch (InvocationTargetException e) {
String title= JavaUIMessages.getString("CompilerConfigurationBlock.builderror.title"); //$NON-NLS-1$
String message= JavaUIMessages.getString("CompilerConfigurationBlock.builderror.message"); //$NON-NLS-1$
ExceptionHandler.handle(e, getShell(), title, message);
}
}
public void performDefaults() {
fWorkingValues= JavaCore.getDefaultOptions();
fWorkingValues.put(INTR_DEFAULT_COMPLIANCE, getCurrentCompliance());
fWorkingValues.put(PREF_COMPILER_TASK_TAGS, "TODO");
fWorkingValues.put(PREF_COMPILER_TASK_PRIORITIES, PRIORITY_NORMAL);
updateControls();
validateSettings(null, null);
}
private void updateControls() {
// update the UI
for (int i= fCheckBoxes.size() - 1; i >= 0; i--) {
Button curr= (Button) fCheckBoxes.get(i);
ControlData data= (ControlData) curr.getData();
String currValue= (String) fWorkingValues.get(data.getKey());
curr.setSelection(data.getSelection(currValue) == 0);
}
for (int i= fComboBoxes.size() - 1; i >= 0; i--) {
Combo curr= (Combo) fComboBoxes.get(i);
ControlData data= (ControlData) curr.getData();
String currValue= (String) fWorkingValues.get(data.getKey());
curr.select(data.getSelection(currValue));
}
for (int i= fTextBoxes.size() - 1; i >= 0; i--) {
Text curr= (Text) fTextBoxes.get(i);
String key= (String) curr.getData();
String currValue= (String) fWorkingValues.get(key);
curr.setText(currValue);
}
unpackTodoTasks();
}
private void unpackTodoTasks() {
String currTags= (String) fWorkingValues.get(PREF_COMPILER_TASK_TAGS);
String currPrios= (String) fWorkingValues.get(PREF_COMPILER_TASK_PRIORITIES);
String[] tags= getTokens(currTags);
String[] prios= getTokens(currPrios);
ArrayList elements= new ArrayList(tags.length);
for (int i= 0; i < tags.length; i++) {
TodoTask task= new TodoTask();
task.name= tags[i].trim();
task.priority= (i < prios.length) ? prios[i] : PRIORITY_NORMAL;
elements.add(task);
}
fTodoTasksList.setElements(elements);
}
private void packTodoTasks() {
StringBuffer tags= new StringBuffer();
StringBuffer prios= new StringBuffer();
List list= fTodoTasksList.getElements();
for (int i= 0; i < list.size(); i++) {
if (i > 0) {
tags.append(',');
prios.append(',');
}
TodoTask elem= (TodoTask) list.get(i);
tags.append(elem.name);
prios.append(elem.priority);
}
fWorkingValues.put(PREF_COMPILER_TASK_TAGS, tags.toString());
fWorkingValues.put(PREF_COMPILER_TASK_PRIORITIES, prios.toString());
}
private void doTodoButtonPressed(int index) {
TodoTask edited= null;
if (index != 0) {
edited= (TodoTask) fTodoTasksList.getSelectedElements().get(0);
}
CompilerTodoTaskInputDialog dialog= new CompilerTodoTaskInputDialog(getShell(), edited, fTodoTasksList.getElements());
if (dialog.open() == CompilerTodoTaskInputDialog.OK) {
if (edited != null) {
fTodoTasksList.replaceElement(edited, dialog.getResult());
} else {
fTodoTasksList.addElement(dialog.getResult());
}
}
}
}
|
26,452 |
Bug 26452 Wrong automatically generated import statements
|
For the following class: public final class OuterClass { void outerMethod() { new Object() { class Subroutine { } private void innerMethod() { Subroutine sub = null; } }; } } When one presses ctrl+shift+o the following statement is added: import OuterClass..Subroutine;
|
verified fixed
|
d8f652c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-21T16:53:59Z | 2002-11-15T11:33:20Z |
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/ImportOrganizeTest.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.ui.tests.core;
import java.io.File;
import java.util.zip.ZipFile;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.testplugin.JavaProjectHelper;
import org.eclipse.jdt.testplugin.JavaTestPlugin;
import org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation;
import org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation.IChooseImportQuery;
import org.eclipse.jdt.internal.corext.util.TypeInfo;
public class ImportOrganizeTest extends TestCase {
private static final Class THIS= ImportOrganizeTest.class;
private IJavaProject fJProject1;
public ImportOrganizeTest(String name) {
super(name);
}
public static Test suite() {
if (true) {
return new TestSuite(THIS);
} else {
TestSuite suite= new TestSuite();
suite.addTest(new ImportOrganizeTest("testImportFromDefaultWithStar"));
return suite;
}
}
protected void setUp() throws Exception {
fJProject1= JavaProjectHelper.createJavaProject("TestProject1", "bin");
assertTrue("rt not found", JavaProjectHelper.addRTJar(fJProject1) != null);
}
protected void tearDown() throws Exception {
JavaProjectHelper.delete(fJProject1);
}
private IChooseImportQuery createQuery(final String name, final String[] choices, final int[] nEntries) {
return new IChooseImportQuery() {
public TypeInfo[] chooseImports(TypeInfo[][] openChoices, ISourceRange[] ranges) {
assertTrue(name + "-query-nchoices1", choices.length == openChoices.length);
assertTrue(name + "-query-nchoices2", nEntries.length == openChoices.length);
if (nEntries != null) {
for (int i= 0; i < nEntries.length; i++) {
assertTrue(name + "-query-cnt" + i, openChoices[i].length == nEntries[i]);
}
}
TypeInfo[] res= new TypeInfo[openChoices.length];
for (int i= 0; i < openChoices.length; i++) {
TypeInfo[] selection= openChoices[i];
assertNotNull(name + "-query-setset" + i, selection);
assertTrue(name + "-query-setlen" + i, selection.length > 0);
TypeInfo found= null;
for (int k= 0; k < selection.length; k++) {
if (selection[k].getFullyQualifiedName().equals(choices[i])) {
found= selection[k];
}
}
assertNotNull(name + "-query-notfound" + i, found);
res[i]= found;
}
return res;
}
};
}
private void assertImports(ICompilationUnit cu, String[] imports) throws Exception {
IImportDeclaration[] desc= cu.getImports();
assertTrue(cu.getElementName() + "-count", desc.length == imports.length);
for (int i= 0; i < imports.length; i++) {
assertEquals(cu.getElementName() + "-cmpentries" + i, desc[i].getElementName(), imports[i]);
}
}
public void test1() throws Exception {
File junitSrcArchive= JavaTestPlugin.getDefault().getFileInPlugin(JavaProjectHelper.JUNIT_SRC);
assertTrue("junit src not found", junitSrcArchive != null && junitSrcArchive.exists());
ZipFile zipfile= new ZipFile(junitSrcArchive);
JavaProjectHelper.addSourceContainerWithImport(fJProject1, "src", zipfile);
ICompilationUnit cu= (ICompilationUnit) fJProject1.findElement(new Path("junit/runner/BaseTestRunner.java"));
assertNotNull("BaseTestRunner.java", cu);
IPackageFragmentRoot root= (IPackageFragmentRoot)cu.getParent().getParent();
IPackageFragment pack= root.createPackageFragment("mytest", true, null);
ICompilationUnit colidingCU= pack.getCompilationUnit("TestListener.java");
colidingCU.createType("public abstract class TestListener {\n}\n", null, true, null);
String[] order= new String[0];
IChooseImportQuery query= createQuery("BaseTestRunner", new String[] { "junit.framework.TestListener" }, new int[] { 2 });
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
assertImports(cu, new String[] {
"java.io.BufferedReader",
"java.io.File",
"java.io.FileInputStream",
"java.io.IOException",
"java.io.InputStream",
"java.io.PrintWriter",
"java.io.StringReader",
"java.io.StringWriter",
"java.lang.reflect.InvocationTargetException",
"java.lang.reflect.Method",
"java.text.NumberFormat",
"java.util.Properties",
"junit.framework.Test",
"junit.framework.TestListener",
"junit.framework.TestSuite"
});
}
public void test2() throws Exception {
File junitSrcArchive= JavaTestPlugin.getDefault().getFileInPlugin(JavaProjectHelper.JUNIT_SRC);
assertTrue("junit src not found", junitSrcArchive != null && junitSrcArchive.exists());
ZipFile zipfile= new ZipFile(junitSrcArchive);
JavaProjectHelper.addSourceContainerWithImport(fJProject1, "src", zipfile);
ICompilationUnit cu= (ICompilationUnit) fJProject1.findElement(new Path("junit/runner/LoadingTestCollector.java"));
assertNotNull("LoadingTestCollector.java", cu);
String[] order= new String[0];
IChooseImportQuery query= createQuery("LoadingTestCollector", new String[] { }, new int[] { });
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
assertImports(cu, new String[] {
"java.lang.reflect.Constructor",
"java.lang.reflect.Method",
"java.lang.reflect.Modifier",
"junit.framework.Test"
});
}
public void test3() throws Exception {
File junitSrcArchive= JavaTestPlugin.getDefault().getFileInPlugin(JavaProjectHelper.JUNIT_SRC);
assertTrue("junit src not found", junitSrcArchive != null && junitSrcArchive.exists());
ZipFile zipfile= new ZipFile(junitSrcArchive);
JavaProjectHelper.addSourceContainerWithImport(fJProject1, "src", zipfile);
ICompilationUnit cu= (ICompilationUnit) fJProject1.findElement(new Path("junit/runner/TestCaseClassLoader.java"));
assertNotNull("TestCaseClassLoader.java", cu);
String[] order= new String[0];
IChooseImportQuery query= createQuery("TestCaseClassLoader", new String[] { }, new int[] { });
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 3, false, true, true, query);
op.run(null);
assertImports(cu, new String[] {
"java.io.*",
"java.net.URL",
"java.util.*",
"java.util.zip.ZipEntry",
"java.util.zip.ZipFile",
});
}
public void test4() throws Exception {
File junitSrcArchive= JavaTestPlugin.getDefault().getFileInPlugin(JavaProjectHelper.JUNIT_SRC);
assertTrue("junit src not found", junitSrcArchive != null && junitSrcArchive.exists());
ZipFile zipfile= new ZipFile(junitSrcArchive);
JavaProjectHelper.addSourceContainerWithImport(fJProject1, "src", zipfile);
ICompilationUnit cu= (ICompilationUnit) fJProject1.findElement(new Path("junit/textui/TestRunner.java"));
assertNotNull("TestRunner.java", cu);
String[] order= new String[0];
IChooseImportQuery query= createQuery("TestRunner", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
assertImports(cu, new String[] {
"java.io.PrintStream",
"java.util.Enumeration",
"junit.framework.AssertionFailedError",
"junit.framework.Test",
"junit.framework.TestFailure",
"junit.framework.TestResult",
"junit.framework.TestSuite",
"junit.runner.BaseTestRunner",
"junit.runner.StandardTestSuiteLoader",
"junit.runner.TestSuiteLoader",
"junit.runner.Version"
});
}
public void testVariousTypeReferences() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack= sourceFolder.createPackageFragment("test", false, null);
for (int ch= 'A'; ch < 'M'; ch++) {
String name= String.valueOf((char) ch);
ICompilationUnit cu= pack.getCompilationUnit(name + ".java");
String content= "public class " + name + " {}";
cu.createType(content, null, false, null);
}
for (int ch= 'A'; ch < 'M'; ch++) {
String name= "I" + String.valueOf((char) ch);
ICompilationUnit cu= pack.getCompilationUnit(name + ".java");
String content= "public interface " + name + " {}";
cu.createType(content, null, false, null);
}
StringBuffer buf= new StringBuffer();
buf.append("public class ImportTest extends A implements IA, IB {\n");
buf.append(" private B fB;\n");
buf.append(" private Object fObj= new C();\n");
buf.append(" public IB foo(IC c, ID d) throws IOException {\n");
buf.append(" Object local= (D) fObj;\n");
buf.append(" if (local instanceof E) {};\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append("}\n");
pack= sourceFolder.createPackageFragment("other", false, null);
ICompilationUnit cu= pack.getCompilationUnit("ImportTest.java");
cu.createType(buf.toString(), null, false, null);
String[] order= new String[0];
IChooseImportQuery query= createQuery("ImportTest", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
assertImports(cu, new String[] {
"java.io.IOException",
"test.A",
"test.B",
"test.C",
"test.D",
"test.E",
"test.IA",
"test.IB",
"test.IC",
"test.ID",
});
}
public void testInnerClassVisibility() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack1= sourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class C {\n");
buf.append(" protected static class C1 {\n");
buf.append(" public static class C2 {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("C.java", buf.toString(), false, null);
IPackageFragment pack2= sourceFolder.createPackageFragment("test2", false, null);
buf= new StringBuffer();
buf.append("package test2;\n");
buf.append("import test2.A.A1;\n");
buf.append("import test2.A.A1.A2;\n");
buf.append("import test2.A.A1.A2.A3;\n");
buf.append("import test2.A.B1;\n");
buf.append("import test2.A.B1.B2;\n");
buf.append("import test1.C;\n");
buf.append("import test1.C.C1.C2;\n");
buf.append("public class A {\n");
buf.append(" public static class A1 {\n");
buf.append(" public static class A2 {\n");
buf.append(" public static class A3 {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" public static class B1 {\n");
buf.append(" public static class B2 {\n");
buf.append(" }\n");
buf.append(" public static class B3 {\n");
buf.append(" public static class B4 extends C {\n");
buf.append(" B4 b4;\n");
buf.append(" B3 b3;\n");
buf.append(" B2 b2;\n");
buf.append(" B1 b1;\n");
buf.append(" A1 a1;\n");
buf.append(" A2 a2;\n");
buf.append(" A3 a3;\n");
buf.append(" C1 c1;\n");
buf.append(" C2 c2;\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" }\n");
ICompilationUnit cu2= pack2.createCompilationUnit("A.java", buf.toString(), false, null);
String[] order= new String[0];
IChooseImportQuery query= createQuery("A", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu2, order, 99, false, true, true, query);
op.run(null);
assertImports(cu2, new String[] {
"test1.C",
"test1.C.C1.C2",
"test2.A.A1.A2",
"test2.A.A1.A2.A3"
});
}
private static final int printRange= 6;
public static void assertEqualString(String str1, String str2) {
int len1= Math.min(str1.length(), str2.length());
int diffPos= -1;
for (int i= 0; i < len1; i++) {
if (str1.charAt(i) != str2.charAt(i)) {
diffPos= i;
break;
}
}
if (diffPos == -1 && str1.length() != str2.length()) {
diffPos= len1;
}
if (diffPos != -1) {
int diffAhead= Math.max(0, diffPos - printRange);
int diffAfter= Math.min(str1.length(), diffPos + printRange);
String diffStr= str1.substring(diffAhead, diffPos) + '^' + str1.substring(diffPos, diffAfter);
assertTrue("Content not as expected: is\n" + str1 + "\nDiffers at pos " + diffPos + ": " + diffStr + "\nexpected:\n" + str2, false);
}
}
public void testClearImports() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack1= sourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class C {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[0];
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class C {\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testNewImports() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack1= sourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class C extends Vector {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[0];
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
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 C extends Vector {\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testReplaceImports() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack1= sourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("import java.util.Set;\n");
buf.append("\n");
buf.append("public class C extends Vector {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[0];
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
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 C extends Vector {\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testClearImportsNoPackage() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack1= sourceFolder.getPackageFragment("");
StringBuffer buf= new StringBuffer();
buf.append("import java.util.Vector;\n");
buf.append("public class C {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[0];
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("public class C {\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testNewImportsNoPackage() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack1= sourceFolder.getPackageFragment("");
StringBuffer buf= new StringBuffer();
buf.append("public class C extends Vector {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[0];
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("import java.util.Vector;\n");
buf.append("\n");
buf.append("public class C extends Vector {\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testReplaceImportsNoPackage() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack1= sourceFolder.getPackageFragment("");
StringBuffer buf= new StringBuffer();
buf.append("import java.util.Set;\n");
buf.append("\n");
buf.append("public class C extends Vector {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[0];
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("import java.util.Vector;\n");
buf.append("\n");
buf.append("public class C extends Vector {\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testCommentAfterImport() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package pack1;\r\n");
buf.append("\r\n");
buf.append("import x;\r\n");
buf.append("import java.util.Vector; // comment\r\n");
buf.append("\r\n");
buf.append("public class C {\r\n");
buf.append(" Vector v;\r\n");
buf.append("}\r\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[0];
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("package pack1;\r\n");
buf.append("\r\n");
buf.append("import java.util.Vector;\r\n");
buf.append("\r\n");
buf.append("public class C {\r\n");
buf.append(" Vector v;\r\n");
buf.append("}\r\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testImportToStar() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack2= sourceFolder.createPackageFragment("pack", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class List {\n");
buf.append("}\n");
pack2.createCompilationUnit("List.java", buf.toString(), false, null);
IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import java.util.Set;\n");
buf.append("import java.util.Vector;\n");
buf.append("import java.util.Map;\n");
buf.append("\n");
buf.append("import pack.List;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" Vector v;\n");
buf.append(" Set v2;\n");
buf.append(" Map v3;\n");
buf.append(" List v4;\n");
buf.append(" String v5;\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[] { "java", "pack" };
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 2, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import java.util.*;\n");
buf.append("\n");
buf.append("import pack.List;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" Vector v;\n");
buf.append(" Set v2;\n");
buf.append(" Map v3;\n");
buf.append(" List v4;\n");
buf.append(" String v5;\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testImportToStarWithExplicit() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack2= sourceFolder.createPackageFragment("pack", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class List {\n");
buf.append("}\n");
pack2.createCompilationUnit("List.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class List2 {\n");
buf.append("}\n");
pack2.createCompilationUnit("List2.java", buf.toString(), false, null);
IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import java.util.Set;\n");
buf.append("import java.util.Vector;\n");
buf.append("import java.util.Map;\n");
buf.append("\n");
buf.append("import pack.List;\n");
buf.append("import pack.List2;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" Vector v;\n");
buf.append(" Set v2;\n");
buf.append(" Map v3;\n");
buf.append(" List v4;\n");
buf.append(" List2 v5;\n");
buf.append(" String v6;\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[] { "java", "pack" };
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 2, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import java.util.*;\n");
buf.append("\n");
buf.append("import pack.*;\n");
buf.append("import pack.List;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" Vector v;\n");
buf.append(" Set v2;\n");
buf.append(" Map v3;\n");
buf.append(" List v4;\n");
buf.append(" List2 v5;\n");
buf.append(" String v6;\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testImportFromDefault() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack2= sourceFolder.createPackageFragment("", false, null);
StringBuffer buf= new StringBuffer();
buf.append("public class List1 {\n");
buf.append("}\n");
pack2.createCompilationUnit("List.java", buf.toString(), false, null);
IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import java.util.Set;\n");
buf.append("import java.util.Vector;\n");
buf.append("import java.util.Map;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" Vector v;\n");
buf.append(" Set v2;\n");
buf.append(" Map v3;\n");
buf.append(" List1 v4;\n");
buf.append(" String v5;\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[] { "java", "pack" };
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 2, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import List1;\n");
buf.append("import java.util.*;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" Vector v;\n");
buf.append(" Set v2;\n");
buf.append(" Map v3;\n");
buf.append(" List1 v4;\n");
buf.append(" String v5;\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testImportFromDefaultWithStar() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack2= sourceFolder.createPackageFragment("", false, null);
StringBuffer buf= new StringBuffer();
buf.append("public class List1 {\n");
buf.append("}\n");
pack2.createCompilationUnit("List.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("public class List2 {\n");
buf.append("}\n");
pack2.createCompilationUnit("List2.java", buf.toString(), false, null);
IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import java.util.Set;\n");
buf.append("import java.util.Vector;\n");
buf.append("import java.util.Map;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" Vector v;\n");
buf.append(" Set v2;\n");
buf.append(" Map v3;\n");
buf.append(" List1 v4;\n");
buf.append(" List2 v5;\n");
buf.append(" String v6;\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[] { "java", "pack" };
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 2, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import List1;\n");
buf.append("import List2;\n");
buf.append("import java.util.*;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" Vector v;\n");
buf.append(" Set v2;\n");
buf.append(" Map v3;\n");
buf.append(" List1 v4;\n");
buf.append(" List2 v5;\n");
buf.append(" String v6;\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
}
|
26,452 |
Bug 26452 Wrong automatically generated import statements
|
For the following class: public final class OuterClass { void outerMethod() { new Object() { class Subroutine { } private void innerMethod() { Subroutine sub = null; } }; } } When one presses ctrl+shift+o the following statement is added: import OuterClass..Subroutine;
|
verified fixed
|
d8f652c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-21T16:53:59Z | 2002-11-15T11:33:20Z |
org.eclipse.jdt.ui/core
| |
26,452 |
Bug 26452 Wrong automatically generated import statements
|
For the following class: public final class OuterClass { void outerMethod() { new Object() { class Subroutine { } private void innerMethod() { Subroutine sub = null; } }; } } When one presses ctrl+shift+o the following statement is added: import OuterClass..Subroutine;
|
verified fixed
|
d8f652c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-21T16:53:59Z | 2002-11-15T11:33:20Z |
extension/org/eclipse/jdt/internal/corext/codemanipulation/OrganizeImportsOperation.java
| |
26,865 |
Bug 26865 Import problem in InlineConstantRefactoring
| null |
resolved fixed
|
5726c25
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-21T18:07:33Z | 2002-11-21T14:46:40Z |
org.eclipse.jdt.ui/core
| |
26,865 |
Bug 26865 Import problem in InlineConstantRefactoring
| null |
resolved fixed
|
5726c25
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-21T18:07:33Z | 2002-11-21T14:46:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/InlineConstantRefactoring.java
| |
26,261 |
Bug 26261 Confusion after setting hover prefs due to disabled hover - remove hover toggle
|
20021113 i set the 'shift' hover to source - nothing happens on hovering with shift down
|
resolved fixed
|
eb40e76
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-22T09:52:19Z | 2002-11-14T10:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/ClassFileEditorActionContributor.java
|
/**********************************************************************
Copyright (c) 2000, 2002 IBM Corp. and others.
All rights reserved. This program and the accompanying materials
are made available under the terms of the Common Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/cpl-v10.html
Contributors:
IBM Corporation - Initial implementation
**********************************************************************/
package org.eclipse.jdt.internal.ui.javaeditor;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.texteditor.BasicTextEditorActionContributor;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.ui.texteditor.RetargetTextEditorAction;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds;
public class ClassFileEditorActionContributor extends BasicTextEditorActionContributor {
protected RetargetTextEditorAction fShowJavaDoc;
protected TogglePresentationAction fTogglePresentationAction;
protected ToggleTextHoverAction fToggleTextHover;
public ClassFileEditorActionContributor() {
super();
fShowJavaDoc= new RetargetTextEditorAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc."); //$NON-NLS-1$
fShowJavaDoc.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_JAVADOC);
fTogglePresentationAction= new TogglePresentationAction();
fToggleTextHover= new ToggleTextHoverAction();
}
/*
* @see org.eclipse.ui.part.EditorActionBarContributor#contributeToMenu(org.eclipse.jface.action.IMenuManager)
*/
public void contributeToMenu(IMenuManager menu) {
super.contributeToMenu(menu);
IMenuManager editMenu= menu.findMenuUsingPath(IWorkbenchActionConstants.M_EDIT);
if (editMenu != null) {
editMenu.add(new Separator(IContextMenuConstants.GROUP_OPEN));
editMenu.add(new Separator(IContextMenuConstants.GROUP_GENERATE));
editMenu.add(new Separator(IContextMenuConstants.GROUP_ADDITIONS));
editMenu.appendToGroup(IContextMenuConstants.GROUP_GENERATE, fShowJavaDoc);
}
}
/*
* @see EditorActionBarContributor#contributeToToolBar(IToolBarManager)
*/
public void contributeToToolBar(IToolBarManager tbm) {
tbm.add(new Separator());
tbm.add(fTogglePresentationAction);
tbm.add(fToggleTextHover);
}
/*
* @see EditorActionBarContributor#setActiveEditor(IEditorPart)
*/
public void setActiveEditor(IEditorPart part) {
super.setActiveEditor(part);
ITextEditor textEditor= null;
if (part instanceof ITextEditor)
textEditor= (ITextEditor) part;
ClassFileEditor classFileEditor= null;
if (part instanceof ClassFileEditor)
classFileEditor= (ClassFileEditor)part;
fShowJavaDoc.setAction(getAction(textEditor, "ShowJavaDoc")); //$NON-NLS-1$
fTogglePresentationAction.setEditor(textEditor);
fToggleTextHover.setEditor(textEditor);
if (classFileEditor != null) {
IActionBars bars= getActionBars();
classFileEditor.fActionGroups.fillActionBars(bars);
}
}
/*
* @see IEditorActionBarContributor#dispose()
*/
public void dispose() {
setActiveEditor(null);
super.dispose();
}
}
|
26,261 |
Bug 26261 Confusion after setting hover prefs due to disabled hover - remove hover toggle
|
20021113 i set the 'shift' hover to source - nothing happens on hovering with shift down
|
resolved fixed
|
eb40e76
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-22T09:52:19Z | 2002-11-14T10:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/CompilationUnitEditorActionContributor.java
|
/**********************************************************************
Copyright (c) 2000, 2002 IBM Corp. and others.
All rights reserved. This program and the accompanying materials
are made available under the terms of the Common Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/cpl-v10.html
Contributors:
IBM Corporation - Initial implementation
**********************************************************************/
package org.eclipse.jdt.internal.ui.javaeditor;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.actions.RetargetAction;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.RetargetTextEditorAction;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds;
import org.eclipse.jdt.ui.actions.JdtActionConstants;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.GoToNextPreviousMemberAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectionAction;
public class CompilationUnitEditorActionContributor extends BasicEditorActionContributor {
/**
* Extends retarget action to make sure that state required for a toolbar actions is
* also copied over from the actual action handler.
*/
private static class RetargetToolbarAction extends RetargetAction {
private String fDefaultLabel;
public RetargetToolbarAction(ResourceBundle bundle, String prefix, String actionId, boolean checkStyle) {
super(actionId, getLabel(bundle, prefix));
fDefaultLabel= getText();
if (checkStyle)
setChecked(true);
}
private static String getLabel(ResourceBundle bundle, String prefix) {
final String labelKey= "label"; //$NON-NLS-1$
try {
return bundle.getString(prefix + labelKey);
} catch (MissingResourceException e) {
return labelKey;
}
}
/*
* @see RetargetAction#propogateChange(PropertyChangeEvent)
*/
protected void propogateChange(PropertyChangeEvent event) {
if (ENABLED.equals(event.getProperty())) {
Boolean bool= (Boolean) event.getNewValue();
setEnabled(bool.booleanValue());
} else if (TEXT.equals(event.getProperty()))
setText((String) event.getNewValue());
else if (TOOL_TIP_TEXT.equals(event.getProperty()))
setToolTipText((String) event.getNewValue());
else if (CHECKED.equals(event.getProperty())) {
Boolean bool= (Boolean) event.getNewValue();
setChecked(bool.booleanValue());
}
}
/*
* @see RetargetAction#setActionHandler(IAction)
*/
protected void setActionHandler(IAction newHandler) {
// default behavior
super.setActionHandler(newHandler);
// update all the remaining issues
if (newHandler != null) {
setText(newHandler.getText());
setToolTipText(newHandler.getToolTipText());
setDescription(newHandler.getDescription());
setImageDescriptor(newHandler.getImageDescriptor());
setHoverImageDescriptor(newHandler.getHoverImageDescriptor());
setDisabledImageDescriptor(newHandler.getDisabledImageDescriptor());
setMenuCreator(newHandler.getMenuCreator());
if (newHandler.getStyle() == IAction.AS_CHECK_BOX)
setChecked(newHandler.isChecked());
} else {
setText(fDefaultLabel);
setToolTipText(fDefaultLabel);
setDescription(fDefaultLabel);
setChecked(false);
}
}
};
private IWorkbenchPage fPage;
private List fRetargetToolbarActions= new ArrayList();
private RetargetTextEditorAction fStructureSelectEnclosingAction;
private RetargetTextEditorAction fStructureSelectNextAction;
private RetargetTextEditorAction fStructureSelectPreviousAction;
private RetargetTextEditorAction fStructureSelectHistoryAction;
private RetargetTextEditorAction fGotoNextMemberAction;
private RetargetTextEditorAction fGotoPreviousMemberAction;
private RetargetTextEditorAction fGotoMatchingBracket;
private RetargetTextEditorAction fShowOutline;
private RetargetTextEditorAction fOpenStructure;
protected TogglePresentationAction fTogglePresentation;
protected ToggleTextHoverAction fToggleTextHover;
protected GotoErrorAction fPreviousError;
protected GotoErrorAction fNextError;
public CompilationUnitEditorActionContributor() {
super();
ResourceBundle b= JavaEditorMessages.getResourceBundle();
// retarget actions usually fetched form the active part or editor
RetargetAction a= new RetargetToolbarAction(b, "TogglePresentation.", IJavaEditorActionConstants.TOGGLE_PRESENTATION, true); //$NON-NLS-1$
a.setActionDefinitionId(IJavaEditorActionDefinitionIds.TOGGLE_PRESENTATION);
JavaPluginImages.setToolImageDescriptors(a, "segment_edit.gif"); //$NON-NLS-1$
fRetargetToolbarActions.add(a);
markAsPartListener(a);
a= new RetargetToolbarAction(b, "ToggleTextHover.", IJavaEditorActionConstants.TOGGLE_TEXT_HOVER, true); //$NON-NLS-1$
a.setActionDefinitionId(IJavaEditorActionDefinitionIds.TOGGLE_TEXT_HOVER);
JavaPluginImages.setToolImageDescriptors(a, "jdoc_hover_edit.gif"); //$NON-NLS-1$
fRetargetToolbarActions.add(a);
markAsPartListener(a);
// http://dev.eclipse.org/bugs/show_bug.cgi?id=18968
a= new RetargetToolbarAction(b, "NextError.", IJavaEditorActionConstants.NEXT_ERROR, false); //$NON-NLS-1$
a.setActionDefinitionId("org.eclipse.ui.navigate.next");
a.setImageDescriptor(JavaPluginImages.DESC_TOOL_GOTO_NEXT_ERROR);
fRetargetToolbarActions.add(a);
markAsPartListener(a);
// http://dev.eclipse.org/bugs/show_bug.cgi?id=18968
a= new RetargetToolbarAction(b, "PreviousError.", IJavaEditorActionConstants.PREVIOUS_ERROR, false); //$NON-NLS-1$
a.setActionDefinitionId("org.eclipse.ui.navigate.previous");
a.setImageDescriptor(JavaPluginImages.DESC_TOOL_GOTO_PREV_ERROR);
fRetargetToolbarActions.add(a);
markAsPartListener(a);
fStructureSelectEnclosingAction= new RetargetTextEditorAction(b, "StructureSelectEnclosing."); //$NON-NLS-1$
fStructureSelectEnclosingAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_ENCLOSING);
fStructureSelectNextAction= new RetargetTextEditorAction(b, "StructureSelectNext."); //$NON-NLS-1$
fStructureSelectNextAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_NEXT);
fStructureSelectPreviousAction= new RetargetTextEditorAction(b, "StructureSelectPrevious."); //$NON-NLS-1$
fStructureSelectPreviousAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_PREVIOUS);
fStructureSelectHistoryAction= new RetargetTextEditorAction(b, "StructureSelectHistory."); //$NON-NLS-1$
fStructureSelectHistoryAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_LAST);
fGotoNextMemberAction= new RetargetTextEditorAction(b, "GotoNextMember."); //$NON-NLS-1$
fGotoNextMemberAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_NEXT_MEMBER);
fGotoPreviousMemberAction= new RetargetTextEditorAction(b, "GotoPreviousMember."); //$NON-NLS-1$
fGotoPreviousMemberAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_PREVIOUS_MEMBER);
fGotoMatchingBracket= new RetargetTextEditorAction(b, "GotoMatchingBracket."); //$NON-NLS-1$
fGotoMatchingBracket.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_MATCHING_BRACKET);
fShowOutline= new RetargetTextEditorAction(JavaEditorMessages.getResourceBundle(), "ShowOutline."); //$NON-NLS-1$
fShowOutline.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_OUTLINE);
fOpenStructure= new RetargetTextEditorAction(JavaEditorMessages.getResourceBundle(), "OpenStructure."); //$NON-NLS-1$
fOpenStructure.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE);
// actions that are "contributed" to editors, they are consider belonging to the active editor
fTogglePresentation= new TogglePresentationAction();
fToggleTextHover= new ToggleTextHoverAction();
fPreviousError= new GotoErrorAction("PreviousError.", false); //$NON-NLS-1$
fPreviousError.setActionDefinitionId("org.eclipse.ui.navigate.previous");
fPreviousError.setImageDescriptor(JavaPluginImages.DESC_TOOL_GOTO_PREV_ERROR);
fNextError= new GotoErrorAction("NextError.", true); //$NON-NLS-1$
fNextError.setActionDefinitionId("org.eclipse.ui.navigate.next");
fNextError.setImageDescriptor(JavaPluginImages.DESC_TOOL_GOTO_NEXT_ERROR);
}
public void init(IActionBars bars) {
super.init(bars);
// register actions that have a dynamic editor.
bars.setGlobalActionHandler(ITextEditorActionConstants.NEXT, fNextError);
bars.setGlobalActionHandler(ITextEditorActionConstants.PREVIOUS, fPreviousError);
bars.setGlobalActionHandler(IJavaEditorActionConstants.TOGGLE_PRESENTATION, fTogglePresentation);
bars.setGlobalActionHandler(IJavaEditorActionConstants.TOGGLE_TEXT_HOVER, fToggleTextHover);
// http://dev.eclipse.org/bugs/show_bug.cgi?id=18968
bars.setGlobalActionHandler(IJavaEditorActionConstants.NEXT_ERROR, fNextError);
bars.setGlobalActionHandler(IJavaEditorActionConstants.PREVIOUS_ERROR, fPreviousError);
}
/*
* @see EditorActionBarContributor#contributeToMenu(IMenuManager)
*/
public void contributeToMenu(IMenuManager menu) {
super.contributeToMenu(menu);
IMenuManager editMenu= menu.findMenuUsingPath(IWorkbenchActionConstants.M_EDIT);
if (editMenu != null) {
MenuManager structureSelection= new MenuManager(JavaEditorMessages.getString("ExpandSelectionMenu.label")); //$NON-NLS-1$
structureSelection.add(fStructureSelectEnclosingAction);
structureSelection.add(fStructureSelectNextAction);
structureSelection.add(fStructureSelectPreviousAction);
structureSelection.add(fStructureSelectHistoryAction);
editMenu.appendToGroup(IContextMenuConstants.GROUP_OPEN, structureSelection);
editMenu.appendToGroup(IContextMenuConstants.GROUP_OPEN, fGotoPreviousMemberAction);
editMenu.appendToGroup(IContextMenuConstants.GROUP_OPEN, fGotoNextMemberAction);
editMenu.appendToGroup(IContextMenuConstants.GROUP_OPEN, fGotoMatchingBracket);
editMenu.appendToGroup(IContextMenuConstants.GROUP_GENERATE, fShowOutline);
}
IMenuManager navigateMenu= menu.findMenuUsingPath(IWorkbenchActionConstants.M_NAVIGATE);
if (navigateMenu != null) {
navigateMenu.appendToGroup("open.ext", fOpenStructure); //$NON-NLS-1$
}
}
/*
* @see EditorActionBarContributor#contributeToToolBar(IToolBarManager)
*/
public void contributeToToolBar(IToolBarManager tbm) {
tbm.add(new Separator());
Iterator e= fRetargetToolbarActions.iterator();
while (e.hasNext())
tbm.add((IAction) e.next());
}
/*
* @see IEditorActionBarContributor#setActiveEditor(IEditorPart)
*/
public void setActiveEditor(IEditorPart part) {
super.setActiveEditor(part);
ITextEditor textEditor= null;
if (part instanceof ITextEditor)
textEditor= (ITextEditor) part;
fTogglePresentation.setEditor(textEditor);
fToggleTextHover.setEditor(textEditor);
fPreviousError.setEditor(textEditor);
fNextError.setEditor(textEditor);
fStructureSelectEnclosingAction.setAction(getAction(textEditor, StructureSelectionAction.ENCLOSING));
fStructureSelectNextAction.setAction(getAction(textEditor, StructureSelectionAction.NEXT));
fStructureSelectPreviousAction.setAction(getAction(textEditor, StructureSelectionAction.PREVIOUS));
fStructureSelectHistoryAction.setAction(getAction(textEditor, StructureSelectionAction.HISTORY));
fGotoNextMemberAction.setAction(getAction(textEditor, GoToNextPreviousMemberAction.NEXT_MEMBER));
fGotoPreviousMemberAction.setAction(getAction(textEditor, GoToNextPreviousMemberAction.PREVIOUS_MEMBER));
fGotoMatchingBracket.setAction(getAction(textEditor, GotoMatchingBracketAction.GOTO_MATCHING_BRACKET));
fShowOutline.setAction(getAction(textEditor, "ShowOutline")); //$NON-NLS-1$
fOpenStructure.setAction(getAction(textEditor, "OpenStructure")); //$NON-NLS-1$
IActionBars bars= getActionBars();
// Source menu.
bars.setGlobalActionHandler(JdtActionConstants.COMMENT, getAction(textEditor, "Comment")); //$NON-NLS-1$
bars.setGlobalActionHandler(JdtActionConstants.UNCOMMENT, getAction(textEditor, "Uncomment")); //$NON-NLS-1$
bars.setGlobalActionHandler(JdtActionConstants.FORMAT, getAction(textEditor, "Format")); //$NON-NLS-1$
// Navigate menu
if (part instanceof CompilationUnitEditor) {
CompilationUnitEditor cuEditor= (CompilationUnitEditor)part;
ActionGroup group= cuEditor.getActionGroup();
if (group != null)
group.fillActionBars(bars);
}
}
}
|
26,261 |
Bug 26261 Confusion after setting hover prefs due to disabled hover - remove hover toggle
|
20021113 i set the 'shift' hover to source - nothing happens on hovering with shift down
|
resolved fixed
|
eb40e76
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-22T09:52:19Z | 2002-11-14T10:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/IJavaEditorActionConstants.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.javaeditor;
/**
* Defines action IDs for private JavaEditor actions.
*/
public interface IJavaEditorActionConstants {
/**
* ID of the action to toggle the style of the presentation.
*/
public static final String TOGGLE_PRESENTATION= "togglePresentation"; //$NON-NLS-1$
/**
* ID of the action to toggle the visibility of the text hover.
*/
public static final String TOGGLE_TEXT_HOVER= "toggleTextHover"; //$NON-NLS-1$
// http://dev.eclipse.org/bugs/show_bug.cgi?id=18968
/**
* ID of the toolbar action to go to the previous error.
*/
public static final String PREVIOUS_ERROR= "gotoPreviousError"; //$NON-NLS-1$
// http://dev.eclipse.org/bugs/show_bug.cgi?id=18968
/**
* ID of the toolbar action to go to the next error.
*/
public static final String NEXT_ERROR= "gotoNextError"; //$NON-NLS-1$
}
|
26,261 |
Bug 26261 Confusion after setting hover prefs due to disabled hover - remove hover toggle
|
20021113 i set the 'shift' hover to source - nothing happens on hovering with shift down
|
resolved fixed
|
eb40e76
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-22T09:52:19Z | 2002-11-14T10:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaEditor.java
|
/**********************************************************************
Copyright (c) 2000, 2002 IBM Corp. and others.
All rights reserved. This program and the accompanying materials
are made available under the terms of the Common Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/cpl-v10.html
Contributors:
IBM Corporation - Initial implementation
**********************************************************************/
package org.eclipse.jdt.internal.ui.javaeditor;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BidiSegmentEvent;
import org.eclipse.swt.custom.BidiSegmentListener;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DefaultInformationControl;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.jface.text.IInformationControl;
import org.eclipse.jface.text.IInformationControlCreator;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextHover;
import org.eclipse.jface.text.ITextInputListener;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.ITextViewerExtension2;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.text.information.IInformationProvider;
import org.eclipse.jface.text.information.InformationPresenter;
import org.eclipse.jface.text.source.AnnotationRulerColumn;
import org.eclipse.jface.text.source.CompositeRuler;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.IVerticalRuler;
import org.eclipse.jface.text.source.IVerticalRulerColumn;
import org.eclipse.jface.text.source.LineNumberRulerColumn;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IPartService;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.editors.text.DefaultEncodingSupport;
import org.eclipse.ui.editors.text.IEncodingSupport;
import org.eclipse.ui.part.EditorActionBarContributor;
import org.eclipse.ui.texteditor.AddTaskAction;
import org.eclipse.ui.texteditor.DefaultRangeIndicator;
import org.eclipse.ui.texteditor.IAbstractTextEditorHelpContextIds;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
import org.eclipse.ui.texteditor.ResourceAction;
import org.eclipse.ui.texteditor.StatusTextEditor;
import org.eclipse.ui.texteditor.TextEditorAction;
import org.eclipse.ui.texteditor.TextOperationAction;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICodeAssist;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IPackageDeclaration;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds;
import org.eclipse.jdt.ui.actions.JavaSearchActionGroup;
import org.eclipse.jdt.ui.actions.OpenEditorActionGroup;
import org.eclipse.jdt.ui.actions.OpenViewActionGroup;
import org.eclipse.jdt.ui.actions.ShowActionGroup;
import org.eclipse.jdt.ui.text.IColorManager;
import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.preferences.JavaEditorPreferencePage;
import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter;
import org.eclipse.jdt.internal.ui.text.JavaPartitionScanner;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider;
/**
* Java specific text editor.
*/
public abstract class JavaEditor extends StatusTextEditor implements IViewPartInputProvider {
/**
* "Smart" runnable for updating the outline page's selection.
*/
class OutlinePageSelectionUpdater implements Runnable {
/** Has the runnable already been posted? */
private boolean fPosted= false;
public OutlinePageSelectionUpdater() {
}
/*
* @see Runnable#run()
*/
public void run() {
synchronizeOutlinePageSelection();
fPosted= false;
}
/**
* Posts this runnable into the event queue.
*/
public void post() {
if (fPosted)
return;
Shell shell= getSite().getShell();
if (shell != null & !shell.isDisposed()) {
fPosted= true;
shell.getDisplay().asyncExec(this);
}
}
};
class SelectionChangedListener implements ISelectionChangedListener {
public void selectionChanged(SelectionChangedEvent event) {
doSelectionChanged(event);
}
};
/**
* Link mode.
*/
class MouseClickListener implements KeyListener, MouseListener, MouseMoveListener,
FocusListener, PaintListener, IPropertyChangeListener, IDocumentListener, ITextInputListener {
/** The session is active. */
private boolean fActive;
/** The currently active style range. */
private IRegion fActiveRegion;
/** The hand cursor. */
private Cursor fCursor;
/** The default cursor. */
private Cursor fDefaultCursor;
/** The link color. */
private Color fColor;
public void deactivate() {
if (!fActive)
return;
repairRepresentation();
fActive= false;
}
public void install() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
StyledText text= sourceViewer.getTextWidget();
if (text == null || text.isDisposed())
return;
updateColor(sourceViewer);
sourceViewer.addTextInputListener(this);
IDocument document= sourceViewer.getDocument();
if (document != null)
document.addDocumentListener(this);
text.addKeyListener(this);
text.addMouseListener(this);
text.addMouseMoveListener(this);
text.addFocusListener(this);
text.addPaintListener(this);
IPreferenceStore preferenceStore= getPreferenceStore();
preferenceStore.addPropertyChangeListener(this);
}
public void uninstall() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
StyledText text= sourceViewer.getTextWidget();
if (text == null || text.isDisposed())
return;
sourceViewer.removeTextInputListener(this);
IDocument document= sourceViewer.getDocument();
if (document != null)
document.removeDocumentListener(this);
text.removeKeyListener(this);
text.removeMouseListener(this);
text.removeMouseMoveListener(this);
text.removeFocusListener(this);
text.removePaintListener(this);
IPreferenceStore preferenceStore= getPreferenceStore();
preferenceStore.removePropertyChangeListener(this);
if (fColor != null) {
fColor.dispose();
fColor= null;
}
if (fCursor != null) {
fCursor.dispose();
fCursor= null;
}
}
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(JavaEditor.LINK_COLOR)) {
ISourceViewer viewer= getSourceViewer();
if (viewer != null)
updateColor(viewer);
}
}
private void updateColor(ISourceViewer viewer) {
if (fColor != null)
fColor.dispose();
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
Display display= text.getDisplay();
fColor= createColor(getPreferenceStore(), JavaEditor.LINK_COLOR, display);
}
/**
* Creates a color from the information stored in the given preference store.
* Returns <code>null</code> if there is no such information available.
*/
private Color createColor(IPreferenceStore store, String key, Display display) {
RGB rgb= null;
if (store.contains(key)) {
if (store.isDefault(key))
rgb= PreferenceConverter.getDefaultColor(store, key);
else
rgb= PreferenceConverter.getColor(store, key);
if (rgb != null)
return new Color(display, rgb);
}
return null;
}
private void repairRepresentation() {
if (fActiveRegion == null)
return;
ISourceViewer viewer= getSourceViewer();
if (viewer != null) {
resetCursor(viewer);
int offset= fActiveRegion.getOffset();
int length= fActiveRegion.getLength();
// remove style
if (viewer instanceof ITextViewerExtension2)
((ITextViewerExtension2) viewer).invalidateTextPresentation(offset, length);
else
viewer.invalidateTextPresentation();
// remove underline
offset -= viewer.getVisibleRegion().getOffset();
StyledText text= viewer.getTextWidget();
text.redrawRange(offset, length, true);
}
fActiveRegion= null;
}
private IJavaElement getInput(JavaEditor editor) {
if (editor == null)
return null;
IEditorInput input= editor.getEditorInput();
if (input instanceof IClassFileEditorInput)
return ((IClassFileEditorInput)input).getClassFile();
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
return manager.getWorkingCopy(input);
}
// will eventually be replaced by a method provided by jdt.core
private IRegion selectWord(IDocument document, int anchor) {
try {
int offset= anchor;
char c;
while (offset >= 0) {
c= document.getChar(offset);
if (!Character.isJavaIdentifierPart(c))
break;
--offset;
}
int start= offset;
offset= anchor;
int length= document.getLength();
while (offset < length) {
c= document.getChar(offset);
if (!Character.isJavaIdentifierPart(c))
break;
++offset;
}
int end= offset;
if (start == end)
return new Region(start, 0);
else
return new Region(start + 1, end - start - 1);
} catch (BadLocationException x) {
return null;
}
}
IRegion getCurrentTextRegion(ISourceViewer viewer) {
int offset= getCurrentTextOffset(viewer);
if (offset == -1)
return null;
IJavaElement input= SelectionConverter.getInput(JavaEditor.this);
if (input == null)
return null;
try {
IJavaElement[] elements= ((ICodeAssist) input).codeSelect(offset, 0);
if (elements == null || elements.length == 0)
return null;
return selectWord(viewer.getDocument(), offset);
} catch (JavaModelException e) {
return null;
}
}
private int getCurrentTextOffset(ISourceViewer viewer) {
try {
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return -1;
Display display= text.getDisplay();
Point absolutePosition= display.getCursorLocation();
Point relativePosition= text.toControl(absolutePosition);
return text.getOffsetAtLocation(relativePosition) + viewer.getVisibleRegion().getOffset();
} catch (IllegalArgumentException e) {
return -1;
}
}
private void highlightRegion(ISourceViewer viewer, IRegion region) {
if (region.equals(fActiveRegion))
return;
repairRepresentation();
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
// highlight region
int offset= region.getOffset() - viewer.getVisibleRegion().getOffset();
int length= region.getLength();
StyleRange oldStyleRange= text.getStyleRangeAtOffset(offset);
Color foregroundColor= fColor;
Color backgroundColor= oldStyleRange == null ? text.getBackground() : oldStyleRange.background;
StyleRange styleRange= new StyleRange(offset, length, foregroundColor, backgroundColor);
text.setStyleRange(styleRange);
// underline
text.redrawRange(offset, length, true);
fActiveRegion= region;
}
private void activateCursor(ISourceViewer viewer) {
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
Display display= text.getDisplay();
if (fCursor == null)
fCursor= new Cursor(display, SWT.CURSOR_HAND);
text.setCursor(fCursor);
}
private void resetCursor(ISourceViewer viewer) {
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
Display display= text.getDisplay();
if (fDefaultCursor == null)
fDefaultCursor= new Cursor(display, SWT.CURSOR_IBEAM);
text.setCursor(fDefaultCursor);
if (fCursor != null) {
fCursor.dispose();
fCursor= null;
}
}
/*
* @see org.eclipse.swt.events.KeyListener#keyPressed(org.eclipse.swt.events.KeyEvent)
*/
public void keyPressed(KeyEvent event) {
if (fActive) {
deactivate();
return;
}
if (event.keyCode != SWT.CTRL) {
deactivate();
return;
}
fActive= true;
ISourceViewer viewer= getSourceViewer();
if (viewer == null)
return;
IRegion region= getCurrentTextRegion(viewer);
if (region == null)
return;
// removed for #25871
// highlightRegion(viewer, region);
// activateCursor(viewer);
}
/*
* @see org.eclipse.swt.events.KeyListener#keyReleased(org.eclipse.swt.events.KeyEvent)
*/
public void keyReleased(KeyEvent event) {
if (!fActive)
return;
deactivate();
}
/*
* @see org.eclipse.swt.events.MouseListener#mouseDoubleClick(org.eclipse.swt.events.MouseEvent)
*/
public void mouseDoubleClick(MouseEvent e) {}
/*
* @see org.eclipse.swt.events.MouseListener#mouseDown(org.eclipse.swt.events.MouseEvent)
*/
public void mouseDown(MouseEvent event) {
if (!fActive)
return;
if (event.stateMask != SWT.CTRL) {
deactivate();
return;
}
if (event.button != 1) {
deactivate();
return;
}
}
/*
* @see org.eclipse.swt.events.MouseListener#mouseUp(org.eclipse.swt.events.MouseEvent)
*/
public void mouseUp(MouseEvent e) {
if (!fActive)
return;
if (e.button != 1) {
deactivate();
return;
}
deactivate();
IAction action= getAction("OpenEditor"); //$NON-NLS-1$
if (action == null)
return;
action.run();
}
/*
* @see org.eclipse.swt.events.MouseMoveListener#mouseMove(org.eclipse.swt.events.MouseEvent)
*/
public void mouseMove(MouseEvent event) {
if (event.widget instanceof Control && !((Control) event.widget).isFocusControl()) {
deactivate();
return;
}
if (!fActive) {
if (event.stateMask != SWT.CTRL)
return;
// Ctrl was already pressed
fActive= true;
}
ISourceViewer viewer= getSourceViewer();
if (viewer == null) {
deactivate();
return;
}
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed()) {
deactivate();
return;
}
if ((event.stateMask & SWT.BUTTON1) != 0 && text.getSelectionCount() != 0) {
deactivate();
return;
}
IRegion region= getCurrentTextRegion(viewer);
if (region == null || 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) {
}
/*
* @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent)
*/
public void documentChanged(DocumentEvent event) {
deactivate();
}
/*
* @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
*/
public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) {
if (oldInput == null)
return;
deactivate();
oldInput.removeDocumentListener(this);
}
/*
* @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
*/
public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
if (newInput == null)
return;
newInput.addDocumentListener(this);
}
/*
* @see PaintListener#paintControl(PaintEvent)
*/
public void paintControl(PaintEvent event) {
if (fActiveRegion == null)
return;
ISourceViewer viewer= getSourceViewer();
if (viewer == null)
return;
IRegion region= viewer.getVisibleRegion();
if (!includes(region, fActiveRegion))
return;
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
int offset= fActiveRegion.getOffset() - region.getOffset();
int length= fActiveRegion.getLength();
// support for bidi
Point minLocation= getMinimumLocation(text, offset, length);
Point maxLocation= getMaximumLocation(text, offset, length);
int x1= minLocation.x;
int x2= minLocation.x + maxLocation.x - minLocation.x - 1;
int y= minLocation.y + text.getLineHeight() - 1;
GC gc= event.gc;
if (fColor != null && !fColor.isDisposed())
gc.setForeground(fColor);
gc.drawLine(x1, y, x2, y);
}
private boolean includes(IRegion region, IRegion position) {
return
position.getOffset() >= region.getOffset() &&
position.getOffset() + position.getLength() <= region.getOffset() + region.getLength();
}
private Point getMinimumLocation(StyledText text, int offset, int length) {
Point minLocation= new Point(Integer.MAX_VALUE, Integer.MAX_VALUE);
for (int i= 0; i <= length; i++) {
Point location= text.getLocationAtOffset(offset + i);
if (location.x < minLocation.x)
minLocation.x= location.x;
if (location.y < minLocation.y)
minLocation.y= location.y;
}
return minLocation;
}
private Point getMaximumLocation(StyledText text, int offset, int length) {
Point maxLocation= new Point(Integer.MIN_VALUE, Integer.MIN_VALUE);
for (int i= 0; i <= length; i++) {
Point location= text.getLocationAtOffset(offset + i);
if (location.x > maxLocation.x)
maxLocation.x= location.x;
if (location.y > maxLocation.y)
maxLocation.y= location.y;
}
return maxLocation;
}
}
/**
* This action dispatches into two behaviours: If there is no current text
* hover, the javadoc is displayed using information presenter. If there is
* a current text hover, it is converted into a information presenter in
* order to make it sticky.
*/
class InformationDispatchAction extends TextEditorAction {
/** The wrapped text operation action. */
private final TextOperationAction fTextOperationAction;
/**
* Creates a dispatch action.
*/
public InformationDispatchAction(ResourceBundle resourceBundle, String prefix, final TextOperationAction textOperationAction) {
super(resourceBundle, prefix, JavaEditor.this);
if (textOperationAction == null)
throw new IllegalArgumentException();
fTextOperationAction= textOperationAction;
}
/*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null) {
fTextOperationAction.run();
return;
}
if (! (sourceViewer instanceof ITextViewerExtension2)) {
fTextOperationAction.run();
return;
}
ITextViewerExtension2 textViewerExtension2= (ITextViewerExtension2) sourceViewer;
// does a text hover exist?
ITextHover textHover= textViewerExtension2.getCurrentTextHover();
if (textHover == null) {
fTextOperationAction.run();
return;
}
Point hoverEventLocation= textViewerExtension2.getHoverEventLocation();
int offset= computeOffsetAtLocation(sourceViewer, hoverEventLocation.x, hoverEventLocation.y);
if (offset == -1) {
fTextOperationAction.run();
return;
}
try {
// get the text hover content
IDocument document= sourceViewer.getDocument();
String contentType= document.getContentType(offset);
final IRegion hoverRegion= textHover.getHoverRegion(sourceViewer, offset);
if (hoverRegion == null)
return;
final String hoverInfo= textHover.getHoverInfo(sourceViewer, hoverRegion);
// with information provider
IInformationProvider informationProvider= new IInformationProvider() {
/*
* @see org.eclipse.jface.text.information.IInformationProvider#getSubject(org.eclipse.jface.text.ITextViewer, int)
*/
public IRegion getSubject(ITextViewer textViewer, int offset) {
return hoverRegion;
}
/*
* @see org.eclipse.jface.text.information.IInformationProvider#getInformation(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion)
*/
public String getInformation(ITextViewer textViewer, IRegion subject) {
return hoverInfo;
}
};
fInformationPresenter.setOffset(offset);
fInformationPresenter.setInformationProvider(informationProvider, contentType);
fInformationPresenter.showInformation();
} catch (BadLocationException e) {
}
}
// modified version from TextViewer
private int computeOffsetAtLocation(ITextViewer textViewer, int x, int y) {
StyledText styledText= textViewer.getTextWidget();
IDocument document= textViewer.getDocument();
IRegion visibleRegion= textViewer.getVisibleRegion();
if (document == null)
return -1;
try {
return styledText.getOffsetAtLocation(new Point(x, y)) + visibleRegion.getOffset();
} catch (IllegalArgumentException e) {
return -1;
}
}
}
/** Preference key for showing the line number ruler */
private final static String LINE_NUMBER_RULER= PreferenceConstants.EDITOR_LINE_NUMBER_RULER;
/** Preference key for the foreground color of the line numbers */
private final static String LINE_NUMBER_COLOR= PreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR;
/** Preference key for the link color */
private final static String LINK_COLOR= PreferenceConstants.EDITOR_LINK_COLOR;
// /** Preference key for the default hover */
// private static final String DEFAULT_HOVER= PreferenceConstants.EDITOR_DEFAULT_HOVER;
// /** Preference key for hover while no modifier is pressed */
// private static final String NONE_HOVER= PreferenceConstants.EDITOR_NONE_HOVER;
// /** Preference key for hover while Ctrl modifier is pressed */
// private static final String CTRL_HOVER= PreferenceConstants.EDITOR_CTRL_HOVER;
// /** Preference key for hover while Shift modifier is pressed */
// private static final String SHIFT_HOVER= PreferenceConstants.EDITOR_SHIFT_HOVER;
// /** Preference key for hover while Ctrl+Alt modifiers are pressed */
// private static final String CTRL_ALT_HOVER= PreferenceConstants.EDITOR_CTRL_ALT_HOVER;
// /** Preference key for hover while Ctrl+Alt+Shift modifiers are pressed */
// private static final String CTRL_ALT_SHIFT_HOVER= PreferenceConstants.EDITOR_CTRL_ALT_SHIFT_HOVER;
// /** Preference key for hover while Ctrl+Shift modifiers are pressed */
// private static final String CTRL_SHIFT_HOVER= PreferenceConstants.EDITOR_CTRL_SHIFT_HOVER;
// /** Preference key for hover while Alt+Shift modifiers are pressed */
// private static final String ALT_SHIFT_HOVER= PreferenceConstants.EDITOR_ALT_SHIFT_HOVER;
// /** Id indicating no hover is configured */
// private static final String NO_HOVER_CONFIGURED_ID= PreferenceConstants.EDITOR_NO_HOVER_CONFIGURED_ID;
// /** Hover id indicating the default hover */
// private static final String DEFAULT_HOVER_CONFIGURED_ID= PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID;
/** The outline page */
protected JavaOutlinePage fOutlinePage;
/** Outliner context menu Id */
protected String fOutlinerContextMenuId;
/** The selection changed listener */
protected ISelectionChangedListener fSelectionChangedListener= new SelectionChangedListener();
/** The outline page selection updater */
private OutlinePageSelectionUpdater fUpdater;
/** Indicates whether this editor should react on outline page selection changes */
private int fIgnoreOutlinePageSelection;
/** The line number ruler column */
private LineNumberRulerColumn fLineNumberRulerColumn;
/** This editor's encoding support */
private DefaultEncodingSupport fEncodingSupport;
/** The mouse listener */
private MouseClickListener fMouseListener;
/** The information presenter. */
private InformationPresenter fInformationPresenter;
protected CompositeActionGroup fActionGroups;
private CompositeActionGroup fContextMenuGroup;
/**
* Returns the most narrow java element including the given offset
*
* @param offset the offset inside of the requested element
*/
abstract protected IJavaElement getElementAt(int offset);
/**
* Returns the java element of this editor's input corresponding to the given IJavaElement
*/
abstract protected IJavaElement getCorrespondingElement(IJavaElement element);
/**
* Sets the input of the editor's outline page.
*/
abstract protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input);
/**
* Default constructor.
*/
public JavaEditor() {
super();
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
setSourceViewerConfiguration(new JavaSourceViewerConfiguration(textTools, this));
setRangeIndicator(new DefaultRangeIndicator());
setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
if (JavaEditorPreferencePage.synchronizeOutlineOnCursorMove())
fUpdater= new OutlinePageSelectionUpdater();
}
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected final ISourceViewer createSourceViewer(Composite parent, IVerticalRuler ruler, int styles) {
ISourceViewer viewer= createJavaSourceViewer(parent, ruler, styles);
StyledText text= viewer.getTextWidget();
text.addBidiSegmentListener(new BidiSegmentListener() {
public void lineGetSegments(BidiSegmentEvent event) {
event.segments= getBidiLineSegments(event.lineOffset, event.lineText);
}
});
JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR);
return viewer;
}
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler ruler, int styles) {
return super.createSourceViewer(parent, ruler, styles);
}
/*
* @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent)
*/
protected boolean affectsTextPresentation(PropertyChangeEvent event) {
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
return textTools.affectsBehavior(event);
}
/**
* Sets the outliner's context menu ID.
*/
protected void setOutlinerContextMenuId(String menuId) {
fOutlinerContextMenuId= menuId;
}
/**
* Returns the standard action group of this editor.
*/
protected ActionGroup getActionGroup() {
return fActionGroups;
}
/*
* @see AbstractTextEditor#editorContextMenuAboutToShow
*/
public void editorContextMenuAboutToShow(IMenuManager menu) {
super.editorContextMenuAboutToShow(menu);
menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, new Separator(IContextMenuConstants.GROUP_OPEN));
menu.insertAfter(IContextMenuConstants.GROUP_OPEN, new GroupMarker(IContextMenuConstants.GROUP_SHOW));
ActionContext context= new ActionContext(getSelectionProvider().getSelection());
fContextMenuGroup.setContext(context);
fContextMenuGroup.fillContextMenu(menu);
fContextMenuGroup.setContext(null);
}
/**
* Creates the outline page used with this editor.
*/
protected JavaOutlinePage createOutlinePage() {
JavaOutlinePage page= new JavaOutlinePage(fOutlinerContextMenuId, this);
page.addSelectionChangedListener(fSelectionChangedListener);
setOutlinePageInput(page, getEditorInput());
return page;
}
/**
* Informs the editor that its outliner has been closed.
*/
public void outlinePageClosed() {
if (fOutlinePage != null) {
fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener);
fOutlinePage= null;
resetHighlightRange();
}
}
/**
* Synchronizes the outliner selection with the actual cursor
* position in the editor.
*/
public void synchronizeOutlinePageSelection() {
if (isEditingScriptRunning())
return;
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null || fOutlinePage == null)
return;
StyledText styledText= sourceViewer.getTextWidget();
if (styledText == null)
return;
int offset= sourceViewer.getVisibleRegion().getOffset();
int caret= offset + styledText.getCaretOffset();
IJavaElement element= getElementAt(caret);
if (element instanceof ISourceReference) {
fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener);
fOutlinePage.select((ISourceReference) element);
fOutlinePage.addSelectionChangedListener(fSelectionChangedListener);
}
}
/*
* Get the desktop's StatusLineManager
*/
protected IStatusLineManager getStatusLineManager() {
IEditorActionBarContributor contributor= getEditorSite().getActionBarContributor();
if (contributor instanceof EditorActionBarContributor) {
return ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager();
}
return null;
}
/*
* @see AbstractTextEditor#getAdapter(Class)
*/
public Object getAdapter(Class required) {
if (IContentOutlinePage.class.equals(required)) {
if (fOutlinePage == null)
fOutlinePage= createOutlinePage();
return fOutlinePage;
}
if (IEncodingSupport.class.equals(required))
return fEncodingSupport;
return super.getAdapter(required);
}
protected void setSelection(ISourceReference reference, boolean moveCursor) {
ISelection selection= getSelectionProvider().getSelection();
if (selection instanceof TextSelection) {
TextSelection textSelection= (TextSelection) selection;
if (textSelection.getOffset() != 0 || textSelection.getLength() != 0)
markInNavigationHistory();
}
if (reference != null) {
StyledText textWidget= null;
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null)
textWidget= sourceViewer.getTextWidget();
if (textWidget == null)
return;
try {
ISourceRange range= reference.getSourceRange();
if (range == null)
return;
int offset= range.getOffset();
int length= range.getLength();
if (offset < 0 || length < 0)
return;
textWidget.setRedraw(false);
setHighlightRange(offset, length, moveCursor);
if (!moveCursor)
return;
offset= -1;
length= -1;
if (reference instanceof IMember) {
range= ((IMember) reference).getNameRange();
if (range != null) {
offset= range.getOffset();
length= range.getLength();
}
} else if (reference instanceof IImportDeclaration) {
String name= ((IImportDeclaration) reference).getElementName();
if (name != null && name.length() > 0) {
String content= reference.getSource();
offset= range.getOffset() + content.indexOf(name);
length= name.length();
}
} else if (reference instanceof IPackageDeclaration) {
String name= ((IPackageDeclaration) reference).getElementName();
if (name != null && name.length() > 0) {
String content= reference.getSource();
offset= range.getOffset() + content.indexOf(name);
length= name.length();
}
}
if (offset > -1 && length > 0) {
sourceViewer.revealRange(offset, length);
sourceViewer.setSelectedRange(offset, length);
}
} catch (JavaModelException x) {
} catch (IllegalArgumentException x) {
} finally {
if (textWidget != null)
textWidget.setRedraw(true);
}
} else if (moveCursor) {
resetHighlightRange();
}
markInNavigationHistory();
}
public void setSelection(IJavaElement element) {
if (element == null || element instanceof ICompilationUnit || element instanceof IClassFile) {
/*
* If the element is an ICompilationUnit this unit is either the input
* of this editor or not being displayed. In both cases, nothing should
* happened. (http://dev.eclipse.org/bugs/show_bug.cgi?id=5128)
*/
return;
}
IJavaElement corresponding= getCorrespondingElement(element);
if (corresponding instanceof ISourceReference) {
ISourceReference reference= (ISourceReference) corresponding;
// set hightlight range
setSelection(reference, true);
// set outliner selection
if (fOutlinePage != null) {
fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener);
fOutlinePage.select(reference);
fOutlinePage.addSelectionChangedListener(fSelectionChangedListener);
}
}
}
public synchronized void editingScriptStarted() {
++ fIgnoreOutlinePageSelection;
}
public synchronized void editingScriptEnded() {
-- fIgnoreOutlinePageSelection;
}
public synchronized boolean isEditingScriptRunning() {
return (fIgnoreOutlinePageSelection > 0);
}
protected void doSelectionChanged(SelectionChangedEvent event) {
ISourceReference reference= null;
ISelection selection= event.getSelection();
Iterator iter= ((IStructuredSelection) selection).iterator();
while (iter.hasNext()) {
Object o= iter.next();
if (o instanceof ISourceReference) {
reference= (ISourceReference) o;
break;
}
}
if (!isActivePart() && JavaPlugin.getActivePage() != null)
JavaPlugin.getActivePage().bringToTop(this);
try {
editingScriptStarted();
setSelection(reference, !isActivePart());
} finally {
editingScriptEnded();
}
}
/*
* @see AbstractTextEditor#adjustHighlightRange(int, int)
*/
protected void adjustHighlightRange(int offset, int length) {
try {
IJavaElement element= getElementAt(offset);
while (element instanceof ISourceReference) {
ISourceRange range= ((ISourceReference) element).getSourceRange();
if (offset < range.getOffset() + range.getLength() && range.getOffset() < offset + length) {
setHighlightRange(range.getOffset(), range.getLength(), true);
if (fOutlinePage != null) {
fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener);
fOutlinePage.select((ISourceReference) element);
fOutlinePage.addSelectionChangedListener(fSelectionChangedListener);
}
return;
}
element= element.getParent();
}
} catch (JavaModelException x) {
JavaPlugin.log(x.getStatus());
}
resetHighlightRange();
}
protected boolean isActivePart() {
IWorkbenchWindow window= getSite().getWorkbenchWindow();
IPartService service= window.getPartService();
IWorkbenchPart part= service.getActivePart();
return part != null && part.equals(this);
}
/*
* @see StatusTextEditor#getStatusHeader(IStatus)
*/
protected String getStatusHeader(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusHeader(status);
if (message != null)
return message;
}
return super.getStatusHeader(status);
}
/*
* @see StatusTextEditor#getStatusBanner(IStatus)
*/
protected String getStatusBanner(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusBanner(status);
if (message != null)
return message;
}
return super.getStatusBanner(status);
}
/*
* @see StatusTextEditor#getStatusMessage(IStatus)
*/
protected String getStatusMessage(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusMessage(status);
if (message != null)
return message;
}
return super.getStatusMessage(status);
}
/*
* @see AbstractTextEditor#doSetInput
*/
protected void doSetInput(IEditorInput input) throws CoreException {
super.doSetInput(input);
if (fEncodingSupport != null)
fEncodingSupport.reset();
setOutlinePageInput(fOutlinePage, input);
}
/*
* @see IWorkbenchPart#dispose()
*/
public void dispose() {
if (fMouseListener != null) {
fMouseListener.uninstall();
fMouseListener= null;
}
if (fEncodingSupport != null) {
fEncodingSupport.dispose();
fEncodingSupport= null;
}
super.dispose();
}
protected void createActions() {
super.createActions();
ResourceAction action= new AddTaskAction(JavaEditorMessages.getResourceBundle(), "AddTask.", this); //$NON-NLS-1$
action.setHelpContextId(IAbstractTextEditorHelpContextIds.ADD_TASK_ACTION);
action.setActionDefinitionId(ITextEditorActionDefinitionIds.ADD_TASK);
setAction(ITextEditorActionConstants.ADD_TASK, action);
ActionGroup oeg, ovg, sg, jsg;
fActionGroups= new CompositeActionGroup(new ActionGroup[] {
oeg= new OpenEditorActionGroup(this),
ovg= new OpenViewActionGroup(this),
sg= new ShowActionGroup(this),
jsg= new JavaSearchActionGroup(this)
});
fContextMenuGroup= new CompositeActionGroup(new ActionGroup[] {oeg, ovg, sg, jsg});
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", this, ISourceViewer.INFORMATION, true); //$NON-NLS-1$
action= new InformationDispatchAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", (TextOperationAction) action); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_JAVADOC);
setAction("ShowJavaDoc", action); //$NON-NLS-1$
fEncodingSupport= new DefaultEncodingSupport();
fEncodingSupport.initialize(this);
if (fMouseListener == null) {
fMouseListener= new MouseClickListener();
fMouseListener.install();
}
}
private boolean isTextSelectionEmpty() {
ISelection selection= getSelectionProvider().getSelection();
if (!(selection instanceof ITextSelection))
return true;
return ((ITextSelection)selection).getLength() == 0;
}
public void updatedTitleImage(Image image) {
setTitleImage(image);
}
/*
* @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
*/
protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
try {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
String property= event.getProperty();
if (PreferenceConstants.EDITOR_TAB_WIDTH.equals(property)) {
Object value= event.getNewValue();
if (value instanceof Integer) {
sourceViewer.getTextWidget().setTabs(((Integer) value).intValue());
} else if (value instanceof String) {
sourceViewer.getTextWidget().setTabs(Integer.parseInt((String) value));
}
return;
}
if (LINE_NUMBER_RULER.equals(property)) {
if (isLineNumberRulerVisible())
showLineNumberRuler();
else
hideLineNumberRuler();
return;
}
if (fLineNumberRulerColumn != null &&
(LINE_NUMBER_COLOR.equals(property) ||
PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT.equals(property) ||
PREFERENCE_COLOR_BACKGROUND.equals(property))) {
initializeLineNumberRulerColumn(fLineNumberRulerColumn);
}
if (PreferenceConstants.EDITOR_SHOW_HOVER.equals(property)) {
updateHoverBehavior();
}
if (isJavaEditorHoverProperty(property)) {
updateHoverBehavior();
}
} finally {
super.handlePreferenceStoreChanged(event);
}
}
private boolean isJavaEditorHoverProperty(String property) {
return PreferenceConstants.EDITOR_DEFAULT_HOVER.equals(property)
|| PreferenceConstants.EDITOR_NONE_HOVER.equals(property)
|| PreferenceConstants.EDITOR_CTRL_HOVER.equals(property)
|| PreferenceConstants.EDITOR_SHIFT_HOVER.equals(property)
|| PreferenceConstants.EDITOR_CTRL_ALT_HOVER.equals(property)
|| PreferenceConstants.EDITOR_CTRL_SHIFT_HOVER.equals(property)
|| PreferenceConstants.EDITOR_CTRL_ALT_SHIFT_HOVER.equals(property)
|| PreferenceConstants.EDITOR_ALT_SHIFT_HOVER.equals(property);
}
/**
* Shows the line number ruler column.
*/
private void showLineNumberRuler() {
IVerticalRuler v= getVerticalRuler();
if (v instanceof CompositeRuler) {
CompositeRuler c= (CompositeRuler) v;
c.addDecorator(1, createLineNumberRulerColumn());
}
}
/**
* Hides the line number ruler column.
*/
private void hideLineNumberRuler() {
IVerticalRuler v= getVerticalRuler();
if (v instanceof CompositeRuler) {
CompositeRuler c= (CompositeRuler) v;
c.removeDecorator(1);
}
}
/**
* Return whether the line number ruler column should be
* visible according to the preference store settings.
* @return <code>true</code> if the line numbers should be visible
*/
private boolean isLineNumberRulerVisible() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(LINE_NUMBER_RULER);
}
/**
* Returns a segmentation of the line of the given document appropriate for bidi rendering.
* The default implementation returns only the string literals of a java code line as segments.
*
* @param document the document
* @param lineOffset the offset of the line
* @return the line's bidi segmentation
* @throws BadLocationException in case lineOffset is not valid in document
*/
public static int[] getBidiLineSegments(IDocument document, int lineOffset) throws BadLocationException {
IRegion line= document.getLineInformationOfOffset(lineOffset);
ITypedRegion[] linePartitioning= document.computePartitioning(lineOffset, line.getLength());
List segmentation= new ArrayList();
for (int i= 0; i < linePartitioning.length; i++) {
if (JavaPartitionScanner.JAVA_STRING.equals(linePartitioning[i].getType()))
segmentation.add(linePartitioning[i]);
}
if (segmentation.size() == 0)
return null;
int size= segmentation.size();
int[] segments= new int[size * 2 + 1];
int j= 0;
for (int i= 0; i < size; i++) {
ITypedRegion segment= (ITypedRegion) segmentation.get(i);
if (i == 0)
segments[j++]= 0;
int offset= segment.getOffset() - lineOffset;
if (offset > segments[j - 1])
segments[j++]= offset;
if (offset + segment.getLength() >= line.getLength())
break;
segments[j++]= offset + segment.getLength();
}
if (j < segments.length) {
int[] result= new int[j];
System.arraycopy(segments, 0, result, 0, j);
segments= result;
}
return segments;
}
/**
* Returns a segmentation of the given line appropriate for bidi rendering. The default
* implementation returns only the string literals of a java code line as segments.
*
* @param lineOffset the offset of the line
* @param line the content of the line
* @return the line's bidi segmentation
*/
protected int[] getBidiLineSegments(int lineOffset, String line) {
IDocumentProvider provider= getDocumentProvider();
if (provider != null && line != null && line.length() > 0) {
IDocument document= provider.getDocument(getEditorInput());
if (document != null)
try {
return getBidiLineSegments(document, lineOffset);
} catch (BadLocationException x) {
// ignore
}
}
return null;
}
/*
* @see AbstractTextEditor#handleCursorPositionChanged()
*/
protected void handleCursorPositionChanged() {
super.handleCursorPositionChanged();
if (!isEditingScriptRunning() && fUpdater != null)
fUpdater.post();
}
/**
* Initializes the given line number ruler column from the preference store.
* @param rulerColumn the ruler column to be initialized
*/
protected void initializeLineNumberRulerColumn(LineNumberRulerColumn rulerColumn) {
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
IColorManager manager= textTools.getColorManager();
IPreferenceStore store= getPreferenceStore();
if (store != null) {
RGB rgb= null;
// foreground color
if (store.contains(LINE_NUMBER_COLOR)) {
if (store.isDefault(LINE_NUMBER_COLOR))
rgb= PreferenceConverter.getDefaultColor(store, LINE_NUMBER_COLOR);
else
rgb= PreferenceConverter.getColor(store, LINE_NUMBER_COLOR);
}
rulerColumn.setForeground(manager.getColor(rgb));
rgb= null;
// background color
if (!store.getBoolean(PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)) {
if (store.contains(PREFERENCE_COLOR_BACKGROUND)) {
if (store.isDefault(PREFERENCE_COLOR_BACKGROUND))
rgb= PreferenceConverter.getDefaultColor(store, PREFERENCE_COLOR_BACKGROUND);
else
rgb= PreferenceConverter.getColor(store, PREFERENCE_COLOR_BACKGROUND);
}
}
rulerColumn.setBackground(manager.getColor(rgb));
}
}
/**
* Creates a new line number ruler column that is appropriately initialized.
*/
protected IVerticalRulerColumn createLineNumberRulerColumn() {
fLineNumberRulerColumn= new LineNumberRulerColumn();
initializeLineNumberRulerColumn(fLineNumberRulerColumn);
return fLineNumberRulerColumn;
}
/*
* @see AbstractTextEditor#createVerticalRuler()
*/
protected IVerticalRuler createVerticalRuler() {
CompositeRuler ruler= new CompositeRuler();
ruler.addDecorator(0, new AnnotationRulerColumn(VERTICAL_RULER_WIDTH));
if (isLineNumberRulerVisible())
ruler.addDecorator(1, createLineNumberRulerColumn());
return ruler;
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#updatePropertyDependentActions()
*/
protected void updatePropertyDependentActions() {
super.updatePropertyDependentActions();
if (fEncodingSupport != null)
fEncodingSupport.reset();
}
/*
* Update the hovering behavior depending on the preferences.
*/
private void updateHoverBehavior() {
SourceViewerConfiguration configuration= getSourceViewerConfiguration();
String[] types= configuration.getConfiguredContentTypes(getSourceViewer());
for (int i= 0; i < types.length; i++) {
String t= types[i];
int[] stateMasks= configuration.getConfiguredTextHoverStateMasks(getSourceViewer(), t);
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer instanceof ITextViewerExtension2) {
if (stateMasks != null) {
for (int j= 0; j < stateMasks.length; j++) {
int stateMask= stateMasks[j];
ITextHover textHover= configuration.getTextHover(sourceViewer, t, stateMask);
((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, stateMask);
}
} else {
ITextHover textHover= configuration.getTextHover(sourceViewer, t);
((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK);
}
} else
sourceViewer.setTextHover(configuration.getTextHover(sourceViewer, t), t);
}
}
/*
* @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
*/
public Object getViewPartInput() {
return getEditorInput().getAdapter(IJavaElement.class);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetSelection(ISelection)
*/
protected void doSetSelection(ISelection selection) {
super.doSetSelection(selection);
synchronizeOutlinePageSelection();
}
/*
* @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.
* widgets.Composite)
*/
public void createPartControl(Composite parent) {
super.createPartControl(parent);
ISourceViewer sourceViewer= getSourceViewer();
SourceViewerConfiguration sourceViewerConfiguration= getSourceViewerConfiguration();
IInformationControlCreator informationControlCreator= new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell parent) {
boolean cutDown= false;
int style= cutDown ? SWT.NONE : (SWT.V_SCROLL | SWT.H_SCROLL);
return new DefaultInformationControl(parent, SWT.RESIZE, style, new HTMLTextPresenter(cutDown));
}
};
fInformationPresenter= new InformationPresenter(informationControlCreator);
fInformationPresenter.setSizeConstraints(60, 10, true, true);
fInformationPresenter.install(sourceViewer);
}
}
|
26,261 |
Bug 26261 Confusion after setting hover prefs due to disabled hover - remove hover toggle
|
20021113 i set the 'shift' hover to source - nothing happens on hovering with shift down
|
resolved fixed
|
eb40e76
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-22T09:52:19Z | 2002-11-14T10:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaOutlinePage.java
|
package org.eclipse.jdt.internal.ui.javaeditor;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Item;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.ListenerList;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.DecoratingLabelProvider;
import org.eclipse.jface.viewers.IBaseLabelProvider;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProviderChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.internal.model.WorkbenchAdapter;
import org.eclipse.ui.model.IWorkbenchAdapter;
import org.eclipse.ui.part.IPageSite;
import org.eclipse.ui.part.Page;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.IUpdate;
import org.eclipse.ui.texteditor.TextEditorAction;
import org.eclipse.ui.texteditor.TextOperationAction;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.jdt.core.ElementChangedEvent;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IElementChangedListener;
import org.eclipse.jdt.core.IInitializer;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaElementDelta;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IParent;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.ProblemsLabelDecorator.ProblemsLabelChangedEvent;
import org.eclipse.jdt.ui.actions.CCPActionGroup;
import org.eclipse.jdt.ui.actions.GenerateActionGroup;
import org.eclipse.jdt.ui.actions.JavaSearchActionGroup;
import org.eclipse.jdt.ui.actions.JdtActionConstants;
import org.eclipse.jdt.ui.actions.MemberFilterActionGroup;
import org.eclipse.jdt.ui.actions.OpenViewActionGroup;
import org.eclipse.jdt.ui.actions.RefactorActionGroup;
import org.eclipse.jdt.ui.actions.ShowActionGroup;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter;
import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer;
import org.eclipse.jdt.internal.ui.dnd.TransferDragSourceListener;
import org.eclipse.jdt.internal.ui.dnd.TransferDropTargetListener;
import org.eclipse.jdt.internal.ui.packageview.SelectionTransferDragAdapter;
import org.eclipse.jdt.internal.ui.packageview.SelectionTransferDropAdapter;
import org.eclipse.jdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater;
/**
* The content outline page of the Java editor. The viewer implements a proprietary
* update mechanism based on Java model deltas. It does not react on domain changes.
* It is specified to show the content of ICompilationUnits and IClassFiles.
* Pulishes its context menu under <code>JavaPlugin.getDefault().getPluginId() + ".outline"</code>.
*/
class JavaOutlinePage extends Page implements IContentOutlinePage {
static Object[] NO_CHILDREN= new Object[0];
/**
* The element change listener of the java outline viewer.
* @see IElementChangedListener
*/
class ElementChangedListener implements IElementChangedListener {
public void elementChanged(final ElementChangedEvent e) {
if (getControl() == null)
return;
Display d= getControl().getDisplay();
if (d != null) {
d.asyncExec(new Runnable() {
public void run() {
ICompilationUnit cu= (ICompilationUnit) fInput;
IJavaElement base= cu;
if (fTopLevelTypeOnly) {
base= getMainType(cu);
if (base == null) {
if (fOutlineViewer != null)
fOutlineViewer.refresh();
return;
}
}
IJavaElementDelta delta= findElement(base, e.getDelta());
if (delta != null && fOutlineViewer != null) {
fOutlineViewer.reconcile(delta);
}
}
});
}
}
protected IJavaElementDelta findElement(IJavaElement unit, IJavaElementDelta delta) {
if (delta == null || unit == null)
return null;
IJavaElement element= delta.getElement();
if (unit.equals(element))
return delta;
if (element.getElementType() > IJavaElement.CLASS_FILE)
return null;
IJavaElementDelta[] children= delta.getAffectedChildren();
if (children == null || children.length == 0)
return null;
for (int i= 0; i < children.length; i++) {
IJavaElementDelta d= findElement(unit, children[i]);
if (d != null)
return d;
}
return null;
}
};
static class NoClassElement extends WorkbenchAdapter implements IAdaptable {
/*
* @see java.lang.Object#toString()
*/
public String toString() {
return JavaEditorMessages.getString("JavaOutlinePage.error.NoTopLevelType"); //$NON-NLS-1$
}
/*
* @see org.eclipse.core.runtime.IAdaptable#getAdapter(Class)
*/
public Object getAdapter(Class clas) {
if (clas == IWorkbenchAdapter.class)
return this;
return null;
}
}
/**
* Content provider for the children of an ICompilationUnit or
* an IClassFile
* @see ITreeContentProvider
*/
class ChildrenProvider implements ITreeContentProvider {
private Object[] NO_CLASS= new Object[] {new NoClassElement()};
private ElementChangedListener fListener;
protected boolean matches(IJavaElement element) {
if (element.getElementType() == IJavaElement.METHOD) {
String name= element.getElementName();
return (name != null && name.indexOf('<') >= 0);
}
return false;
}
protected IJavaElement[] filter(IJavaElement[] children) {
boolean initializers= false;
for (int i= 0; i < children.length; i++) {
if (matches(children[i])) {
initializers= true;
break;
}
}
if (!initializers)
return children;
Vector v= new Vector();
for (int i= 0; i < children.length; i++) {
if (matches(children[i]))
continue;
v.addElement(children[i]);
}
IJavaElement[] result= new IJavaElement[v.size()];
v.copyInto(result);
return result;
}
public Object[] getChildren(Object parent) {
if (parent instanceof IParent) {
IParent c= (IParent) parent;
try {
return filter(c.getChildren());
} catch (JavaModelException x) {
JavaPlugin.log(x);
}
}
return NO_CHILDREN;
}
public Object[] getElements(Object parent) {
if (fTopLevelTypeOnly) {
if (parent instanceof ICompilationUnit) {
try {
IType type= getMainType((ICompilationUnit) parent);
return type != null ? type.getChildren() : NO_CLASS;
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
} else if (parent instanceof IClassFile) {
try {
IType type= getMainType((IClassFile) parent);
return type != null ? type.getChildren() : NO_CLASS;
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
}
return getChildren(parent);
}
public Object getParent(Object child) {
if (child instanceof IJavaElement) {
IJavaElement e= (IJavaElement) child;
return e.getParent();
}
return null;
}
public boolean hasChildren(Object parent) {
if (parent instanceof IParent) {
IParent c= (IParent) parent;
try {
IJavaElement[] children= filter(c.getChildren());
return (children != null && children.length > 0);
} catch (JavaModelException x) {
JavaPlugin.log(x);
}
}
return false;
}
public boolean isDeleted(Object o) {
return false;
}
public void dispose() {
if (fListener != null) {
JavaCore.removeElementChangedListener(fListener);
fListener= null;
}
}
/*
* @see IContentProvider#inputChanged(Viewer, Object, Object)
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
boolean isCU= (newInput instanceof ICompilationUnit);
if (isCU && fListener == null) {
fListener= new ElementChangedListener();
JavaCore.addElementChangedListener(fListener);
} else if (!isCU && fListener != null) {
JavaCore.removeElementChangedListener(fListener);
fListener= null;
}
}
};
class JavaOutlineViewer extends TreeViewer {
/**
* Indicates an item which has been reused. At the point of
* its reuse it has been expanded. This field is used to
* communicate between <code>internalExpandToLevel</code> and
* <code>reuseTreeItem</code>.
*/
private Item fReusedExpandedItem;
public JavaOutlineViewer(Tree tree) {
super(tree);
setAutoExpandLevel(ALL_LEVELS);
}
/**
* Investigates the given element change event and if affected incrementally
* updates the outline.
*/
public void reconcile(IJavaElementDelta delta) {
if (getSorter() == null) {
if (fTopLevelTypeOnly
&& delta.getElement() instanceof IType
&& (delta.getKind() & IJavaElementDelta.ADDED) != 0)
{
refresh();
} else {
Widget w= findItem(fInput);
if (w != null && !w.isDisposed())
update(w, delta);
}
} else {
// just for now
refresh();
}
}
/*
* @see TreeViewer#internalExpandToLevel
*/
protected void internalExpandToLevel(Widget node, int level) {
if (node instanceof Item) {
Item i= (Item) node;
if (i.getData() instanceof IJavaElement) {
IJavaElement je= (IJavaElement) i.getData();
if (je.getElementType() == IJavaElement.IMPORT_CONTAINER || isInnerType(je)) {
if (i != fReusedExpandedItem) {
setExpanded(i, false);
return;
}
}
}
}
super.internalExpandToLevel(node, level);
}
protected void reuseTreeItem(Item item, Object element) {
// remove children
Item[] c= getChildren(item);
if (c != null && c.length > 0) {
if (getExpanded(item))
fReusedExpandedItem= item;
for (int k= 0; k < c.length; k++) {
if (c[k].getData() != null)
disassociate(c[k]);
c[k].dispose();
}
}
updateItem(item, element);
updatePlus(item, element);
internalExpandToLevel(item, ALL_LEVELS);
fReusedExpandedItem= null;
}
protected boolean mustUpdateParent(IJavaElementDelta delta, IJavaElement element) {
if (element instanceof IMethod) {
if ((delta.getKind() & IJavaElementDelta.ADDED) != 0) {
try {
return ((IMethod)element).isMainMethod();
} catch (JavaModelException e) {
JavaPlugin.log(e.getStatus());
}
}
return "main".equals(element.getElementName()); //$NON-NLS-1$
}
return false;
}
protected ISourceRange getSourceRange(IJavaElement element) throws JavaModelException {
if (element instanceof IMember && !(element instanceof IInitializer))
return ((IMember) element).getNameRange();
if (element instanceof ISourceReference)
return ((ISourceReference) element).getSourceRange();
return null;
}
protected boolean overlaps(ISourceRange range, int start, int end) {
return start <= (range.getOffset() + range.getLength() - 1) && range.getOffset() <= end;
}
protected boolean filtered(IJavaElement parent, IJavaElement child) {
Object[] result= new Object[] { child };
ViewerFilter[] filters= getFilters();
for (int i= 0; i < filters.length; i++) {
result= filters[i].filter(this, parent, result);
if (result.length == 0)
return true;
}
return false;
}
protected void update(Widget w, IJavaElementDelta delta) {
Item item;
IJavaElement parent= delta.getElement();
IJavaElementDelta[] affected= delta.getAffectedChildren();
Item[] children= getChildren(w);
boolean doUpdateParent= false;
Vector deletions= new Vector();
Vector additions= new Vector();
for (int i= 0; i < affected.length; i++) {
IJavaElementDelta affectedDelta= affected[i];
IJavaElement affectedElement= affectedDelta.getElement();
int status= affected[i].getKind();
// find tree item with affected element
int j;
for (j= 0; j < children.length; j++)
if (affectedElement.equals(children[j].getData()))
break;
if (j == children.length) {
// addition
if ((status & IJavaElementDelta.CHANGED) != 0 &&
(affectedDelta.getFlags() & IJavaElementDelta.F_MODIFIERS) != 0 &&
!filtered(parent, affectedElement))
{
additions.addElement(affectedDelta);
}
continue;
}
item= children[j];
// removed
if ((status & IJavaElementDelta.REMOVED) != 0) {
deletions.addElement(item);
doUpdateParent= doUpdateParent || mustUpdateParent(affectedDelta, affectedElement);
// changed
} else if ((status & IJavaElementDelta.CHANGED) != 0) {
int change= affectedDelta.getFlags();
doUpdateParent= doUpdateParent || mustUpdateParent(affectedDelta, affectedElement);
if ((change & IJavaElementDelta.F_MODIFIERS) != 0) {
if (filtered(parent, affectedElement))
deletions.addElement(item);
else
updateItem(item, affectedElement);
}
if ((change & IJavaElementDelta.F_CONTENT) != 0)
updateItem(item, affectedElement);
if ((change & IJavaElementDelta.F_CHILDREN) != 0)
update(item, affectedDelta);
}
}
// find all elements to add
IJavaElementDelta[] add= delta.getAddedChildren();
if (additions.size() > 0) {
IJavaElementDelta[] tmp= new IJavaElementDelta[add.length + additions.size()];
System.arraycopy(add, 0, tmp, 0, add.length);
for (int i= 0; i < additions.size(); i++)
tmp[i + add.length]= (IJavaElementDelta) additions.elementAt(i);
add= tmp;
}
// add at the right position
go2: for (int i= 0; i < add.length; i++) {
try {
IJavaElement e= add[i].getElement();
if (filtered(parent, e))
continue go2;
doUpdateParent= doUpdateParent || mustUpdateParent(add[i], e);
ISourceRange rng= getSourceRange(e);
int start= rng.getOffset();
int end= start + rng.getLength() - 1;
Item last= null;
item= null;
children= getChildren(w);
for (int j= 0; j < children.length; j++) {
item= children[j];
IJavaElement r= (IJavaElement) item.getData();
if (r == null) {
// parent node collapsed and not be opened before -> do nothing
continue go2;
}
try {
rng= getSourceRange(r);
if (overlaps(rng, start, end)) {
// be tolerant if the delta is not correct, or if
// the tree has been updated other than by a delta
reuseTreeItem(item, e);
continue go2;
} else if (rng.getOffset() > start) {
if (last != null && deletions.contains(last)) {
// reuse item
deletions.removeElement(last);
reuseTreeItem(last, (Object) e);
} else {
// nothing to reuse
createTreeItem(w, (Object) e, j);
}
continue go2;
}
} catch (JavaModelException x) {
// stumbled over deleted element
}
last= item;
}
// add at the end of the list
if (last != null && deletions.contains(last)) {
// reuse item
deletions.removeElement(last);
reuseTreeItem(last, e);
} else {
// nothing to reuse
createTreeItem(w, e, -1);
}
} catch (JavaModelException x) {
// the element to be added is not present -> don't add it
}
}
// remove items which haven't been reused
Enumeration e= deletions.elements();
while (e.hasMoreElements()) {
item= (Item) e.nextElement();
disassociate(item);
item.dispose();
}
if (doUpdateParent)
updateItem(w, delta.getElement());
}
/*
* @see ContentViewer#handleLabelProviderChanged(LabelProviderChangedEvent)
*/
protected void handleLabelProviderChanged(LabelProviderChangedEvent event) {
Object input= getInput();
if (event instanceof ProblemsLabelChangedEvent) {
ProblemsLabelChangedEvent e= (ProblemsLabelChangedEvent) event;
if (e.isMarkerChange() && input instanceof ICompilationUnit) {
return; // marker changes can be ignored
}
}
// look if the underlying resource changed
Object[] changed= event.getElements();
if (changed != null) {
IResource resource= getUnderlyingResource();
if (resource != null) {
for (int i= 0; i < changed.length; i++) {
if (changed[i].equals(resource)) {
// change event to a full refresh
event= new LabelProviderChangedEvent((IBaseLabelProvider) event.getSource());
break;
}
}
}
}
super.handleLabelProviderChanged(event);
}
private IResource getUnderlyingResource() {
Object input= getInput();
if (input instanceof ICompilationUnit) {
ICompilationUnit cu= (ICompilationUnit) input;
if (cu.isWorkingCopy()) {
return cu.getOriginalElement().getResource();
} else {
return cu.getResource();
}
} else if (input instanceof IClassFile) {
return ((IClassFile) input).getResource();
}
return null;
}
};
class LexicalSortingAction extends Action {
private JavaElementSorter fSorter= new JavaElementSorter();
public LexicalSortingAction() {
super();
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.LEXICAL_SORTING_OUTLINE_ACTION);
setText(JavaEditorMessages.getString("JavaOutlinePage.Sort.label")); //$NON-NLS-1$
JavaPluginImages.setLocalImageDescriptors(this, "alphab_sort_co.gif"); //$NON-NLS-1$
setToolTipText(JavaEditorMessages.getString("JavaOutlinePage.Sort.tooltip")); //$NON-NLS-1$
setDescription(JavaEditorMessages.getString("JavaOutlinePage.Sort.description")); //$NON-NLS-1$
boolean checked= JavaPlugin.getDefault().getPreferenceStore().getBoolean("LexicalSortingAction.isChecked"); //$NON-NLS-1$
valueChanged(checked, false);
}
public void run() {
valueChanged(isChecked(), true);
}
private void valueChanged(final boolean on, boolean store) {
setChecked(on);
BusyIndicator.showWhile(fOutlineViewer.getControl().getDisplay(), new Runnable() {
public void run() {
fOutlineViewer.setSorter(on ? fSorter : null); }
});
if (store)
JavaPlugin.getDefault().getPreferenceStore().setValue("LexicalSortingAction.isChecked", on); //$NON-NLS-1$
}
};
class ClassOnlyAction extends Action {
public ClassOnlyAction() {
super();
setText(JavaEditorMessages.getString("JavaOutlinePage.GoIntoTopLevelType.label")); //$NON-NLS-1$
setToolTipText(JavaEditorMessages.getString("JavaOutlinePage.GoIntoTopLevelType.tooltip")); //$NON-NLS-1$
setDescription(JavaEditorMessages.getString("JavaOutlinePage.GoIntoTopLevelType.description")); //$NON-NLS-1$
JavaPluginImages.setLocalImageDescriptors(this, "class_obj.gif"); //$NON-NLS-1$
IPreferenceStore preferenceStore= JavaPlugin.getDefault().getPreferenceStore();
boolean showclass= preferenceStore.getBoolean("GoIntoTopLevelTypeAction.isChecked"); //$NON-NLS-1$
setTopLevelTypeOnly(showclass);
}
/*
* @see org.eclipse.jface.action.Action#run()
*/
public void run() {
setTopLevelTypeOnly(!fTopLevelTypeOnly);
}
private void setTopLevelTypeOnly(boolean show) {
fTopLevelTypeOnly= show;
setChecked(show);
fOutlineViewer.refresh();
IPreferenceStore preferenceStore= JavaPlugin.getDefault().getPreferenceStore();
preferenceStore.setValue("GoIntoTopLevelTypeAction.isChecked", show); //$NON-NLS-1$
}
};
/** A flag to show contents of top level type only */
private boolean fTopLevelTypeOnly;
private IJavaElement fInput;
private String fContextMenuID;
private Menu fMenu;
private JavaOutlineViewer fOutlineViewer;
private JavaEditor fEditor;
private MemberFilterActionGroup fMemberFilterActionGroup;
private ListenerList fSelectionChangedListeners= new ListenerList();
private Hashtable fActions= new Hashtable();
private TogglePresentationAction fTogglePresentation;
private ToggleTextHoverAction fToggleTextHover;
private GotoErrorAction fPreviousError;
private GotoErrorAction fNextError;
private TextEditorAction fShowJavadoc;
private TextOperationAction fUndo;
private TextOperationAction fRedo;
private CompositeActionGroup fActionGroups;
private CCPActionGroup fCCPActionGroup;
private IPropertyChangeListener fPropertyChangeListener;
public JavaOutlinePage(String contextMenuID, JavaEditor editor) {
super();
Assert.isNotNull(editor);
fContextMenuID= contextMenuID;
fEditor= editor;
fTogglePresentation= new TogglePresentationAction();
fToggleTextHover= new ToggleTextHoverAction();
fPreviousError= new GotoErrorAction("PreviousError.", false); //$NON-NLS-1$
fPreviousError.setImageDescriptor(JavaPluginImages.DESC_TOOL_GOTO_PREV_ERROR);
fNextError= new GotoErrorAction("NextError.", true); //$NON-NLS-1$
fNextError.setImageDescriptor(JavaPluginImages.DESC_TOOL_GOTO_NEXT_ERROR);
fShowJavadoc= (TextEditorAction) fEditor.getAction("ShowJavaDoc"); //$NON-NLS-1$
fUndo= (TextOperationAction) fEditor.getAction(ITextEditorActionConstants.UNDO);
fRedo= (TextOperationAction) fEditor.getAction(ITextEditorActionConstants.REDO);
fTogglePresentation.setEditor(editor);
fToggleTextHover.setEditor(editor);
fPreviousError.setEditor(editor);
fNextError.setEditor(editor);
fPropertyChangeListener= new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
doPropertyChange(event);
}
};
JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(fPropertyChangeListener);
}
/**
* Returns the primary type of a compilation unit (has the same
* name as the compilation unit).
*
* @param compilationUnit the compilation unit
* @return returns the primary type of the compilation unit, or
* <code>null</code> if is does not have one
*/
protected IType getMainType(ICompilationUnit compilationUnit) {
String name= compilationUnit.getElementName();
int index= name.indexOf('.');
if (index != -1)
name= name.substring(0, index);
IType type= compilationUnit.getType(name);
return type.exists() ? type : null;
}
/**
* Returns the primary type of a class file.
*
* @param classFile the class file
* @return returns the primary type of the class file, or <code>null</code>
* if is does not have one
*/
protected IType getMainType(IClassFile classFile) {
try {
IType type= classFile.getType();
return type.exists() ? type : null;
} catch (JavaModelException e) {
return null;
}
}
/* (non-Javadoc)
* Method declared on Page
*/
public void init(IPageSite pageSite) {
super.init(pageSite);
}
private void doPropertyChange(PropertyChangeEvent event) {
if (fOutlineViewer != null) {
if (PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER.equals(event.getProperty())) {
fOutlineViewer.refresh();
}
}
}
/*
* @see ISelectionProvider#addSelectionChangedListener(ISelectionChangedListener)
*/
public void addSelectionChangedListener(ISelectionChangedListener listener) {
if (fOutlineViewer != null)
fOutlineViewer.addSelectionChangedListener(listener);
else
fSelectionChangedListeners.add(listener);
}
/*
* @see ISelectionProvider#removeSelectionChangedListener(ISelectionChangedListener)
*/
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
if (fOutlineViewer != null)
fOutlineViewer.removeSelectionChangedListener(listener);
else
fSelectionChangedListeners.remove(listener);
}
/*
* @see ISelectionProvider#setSelection(ISelection)
*/
public void setSelection(ISelection selection) {
if (fOutlineViewer != null)
fOutlineViewer.setSelection(selection);
}
/*
* @see ISelectionProvider#getSelection()
*/
public ISelection getSelection() {
if (fOutlineViewer == null)
return StructuredSelection.EMPTY;
return fOutlineViewer.getSelection();
}
private void registerToolbarActions() {
IToolBarManager toolBarManager= getSite().getActionBars().getToolBarManager();
if (toolBarManager != null) {
toolBarManager.add(new ClassOnlyAction());
toolBarManager.add(new LexicalSortingAction());
fMemberFilterActionGroup= new MemberFilterActionGroup(fOutlineViewer, "JavaOutlineViewer"); //$NON-NLS-1$
fMemberFilterActionGroup.contributeToToolBar(toolBarManager);
}
}
/*
* @see IPage#createControl
*/
public void createControl(Composite parent) {
Tree tree= new Tree(parent, SWT.MULTI);
ILabelProvider lprovider= new AppearanceAwareLabelProvider(
AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS | JavaElementLabels.F_APP_TYPE_SIGNATURE,
AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS,
AppearanceAwareLabelProvider.getDecorators(true, new OverrideIndicatorLabelDecorator(null))
);
fOutlineViewer= new JavaOutlineViewer(tree);
fOutlineViewer.setContentProvider(new ChildrenProvider());
fOutlineViewer.setLabelProvider(new DecoratingLabelProvider(lprovider, PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator()));
Object[] listeners= fSelectionChangedListeners.getListeners();
for (int i= 0; i < listeners.length; i++) {
fSelectionChangedListeners.remove(listeners[i]);
fOutlineViewer.addSelectionChangedListener((ISelectionChangedListener) listeners[i]);
}
MenuManager manager= new MenuManager(fContextMenuID, fContextMenuID);
manager.setRemoveAllWhenShown(true);
manager.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager manager) {
contextMenuAboutToShow(manager);
}
});
fMenu= manager.createContextMenu(tree);
tree.setMenu(fMenu);
IPageSite site= getSite();
site.registerContextMenu(JavaPlugin.getPluginId() + ".outline", manager, fOutlineViewer); //$NON-NLS-1$
site.setSelectionProvider(fOutlineViewer);
// we must create the groups after we have set the selection provider to the site
fActionGroups= new CompositeActionGroup(new ActionGroup[] {
new OpenViewActionGroup(this),
new ShowActionGroup(this),
fCCPActionGroup= new CCPActionGroup(this),
new RefactorActionGroup(this),
new GenerateActionGroup(this),
new JavaSearchActionGroup(this)});
// register global actions
IActionBars bars= site.getActionBars();
bars.setGlobalActionHandler(ITextEditorActionConstants.UNDO, fUndo);
bars.setGlobalActionHandler(ITextEditorActionConstants.REDO, fRedo);
bars.setGlobalActionHandler(ITextEditorActionConstants.PREVIOUS, fPreviousError);
bars.setGlobalActionHandler(ITextEditorActionConstants.NEXT, fNextError);
bars.setGlobalActionHandler(JdtActionConstants.SHOW_JAVA_DOC, fShowJavadoc);
bars.setGlobalActionHandler(IJavaEditorActionConstants.TOGGLE_PRESENTATION, fTogglePresentation);
bars.setGlobalActionHandler(IJavaEditorActionConstants.TOGGLE_TEXT_HOVER, fToggleTextHover);
// http://dev.eclipse.org/bugs/show_bug.cgi?id=18968
bars.setGlobalActionHandler(IJavaEditorActionConstants.PREVIOUS_ERROR, fPreviousError);
bars.setGlobalActionHandler(IJavaEditorActionConstants.NEXT_ERROR, fNextError);
fActionGroups.fillActionBars(bars);
IStatusLineManager statusLineManager= site.getActionBars().getStatusLineManager();
if (statusLineManager != null) {
StatusBarUpdater updater= new StatusBarUpdater(statusLineManager);
fOutlineViewer.addSelectionChangedListener(updater);
}
registerToolbarActions();
fOutlineViewer.setInput(fInput);
fOutlineViewer.getControl().addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
handleKeyReleased(e);
}
});
initDragAndDrop();
}
public void dispose() {
if (fEditor == null)
return;
if (fMemberFilterActionGroup != null) {
fMemberFilterActionGroup.dispose();
fMemberFilterActionGroup= null;
}
fEditor.outlinePageClosed();
fEditor= null;
fSelectionChangedListeners.clear();
fSelectionChangedListeners= null;
if (fPropertyChangeListener != null) {
JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener);
fPropertyChangeListener= null;
}
if (fMenu != null && !fMenu.isDisposed()) {
fMenu.dispose();
fMenu= null;
}
if (fActionGroups != null)
fActionGroups.dispose();
fTogglePresentation.setEditor(null);
fToggleTextHover.setEditor(null);
fPreviousError.setEditor(null);
fNextError.setEditor(null);
fOutlineViewer= null;
super.dispose();
}
public Control getControl() {
if (fOutlineViewer != null)
return fOutlineViewer.getControl();
return null;
}
public void setInput(IJavaElement inputElement) {
fInput= inputElement;
if (fOutlineViewer != null)
fOutlineViewer.setInput(fInput);
}
public void select(ISourceReference reference) {
if (fOutlineViewer != null) {
ISelection s= fOutlineViewer.getSelection();
if (s instanceof IStructuredSelection) {
IStructuredSelection ss= (IStructuredSelection) s;
List elements= ss.toList();
if (!elements.contains(reference)) {
s= (reference == null ? StructuredSelection.EMPTY : new StructuredSelection(reference));
fOutlineViewer.setSelection(s, true);
}
}
}
}
public void setAction(String actionID, IAction action) {
Assert.isNotNull(actionID);
if (action == null)
fActions.remove(actionID);
else
fActions.put(actionID, action);
}
public IAction getAction(String actionID) {
Assert.isNotNull(actionID);
return (IAction) fActions.get(actionID);
}
/**
* Convenience method to add the action installed under the given actionID to the
* specified group of the menu.
*/
protected void addAction(IMenuManager menu, String group, String actionID) {
IAction action= getAction(actionID);
if (action != null) {
if (action instanceof IUpdate)
((IUpdate) action).update();
if (action.isEnabled()) {
IMenuManager subMenu= menu.findMenuUsingPath(group);
if (subMenu != null)
subMenu.add(action);
else
menu.appendToGroup(group, action);
}
}
}
protected void contextMenuAboutToShow(IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
IStructuredSelection selection= (IStructuredSelection)getSelection();
fActionGroups.setContext(new ActionContext(selection));
fActionGroups.fillContextMenu(menu);
}
/*
* @see Page#setFocus()
*/
public void setFocus() {
if (fOutlineViewer != null)
fOutlineViewer.getControl().setFocus();
}
/**
* Checkes whether a given Java element is an inner type.
*/
private boolean isInnerType(IJavaElement element) {
if (element.getElementType() == IJavaElement.TYPE) {
IJavaElement parent= element.getParent();
int type= parent.getElementType();
return (type != IJavaElement.COMPILATION_UNIT && type != IJavaElement.CLASS_FILE);
}
return false;
}
/**
* Handles key events in viewer.
*/
private void handleKeyReleased(KeyEvent event) {
if (event.stateMask != 0)
return;
IAction action= null;
if (event.character == SWT.DEL) {
action= fCCPActionGroup.getDeleteAction();
}
if (action != null && action.isEnabled())
action.run();
}
private void initDragAndDrop() {
int ops= DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK;
Transfer[] transfers= new Transfer[] {
LocalSelectionTransfer.getInstance()
};
// Drop Adapter
TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] {
new SelectionTransferDropAdapter(fOutlineViewer)
};
fOutlineViewer.addDropSupport(ops | DND.DROP_DEFAULT, transfers, new DelegatingDropAdapter(dropListeners));
// Drag Adapter
Control control= fOutlineViewer.getControl();
TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
new SelectionTransferDragAdapter(fOutlineViewer)
};
DragSource source= new DragSource(control, ops);
// Note, that the transfer agents are set by the delegating drag adapter itself.
source.addDragListener(new DelegatingDragAdapter(dragListeners));
}}
|
26,261 |
Bug 26261 Confusion after setting hover prefs due to disabled hover - remove hover toggle
|
20021113 i set the 'shift' hover to source - nothing happens on hovering with shift down
|
resolved fixed
|
eb40e76
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-22T09:52:19Z | 2002-11-14T10:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/hover/JavaEditorTextHoverProxy.java
|
/**********************************************************************
Copyright (c) 2000, 2002 IBM Corp. and others.
All rights reserved. This program and the accompanying materials
are made available under the terms of the Common Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/cpl-v10.html
Contributors:
IBM Corporation - Initial implementation
**********************************************************************/
package org.eclipse.jdt.internal.ui.text.java.hover;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.text.java.hover.IJavaEditorTextHover;
import org.eclipse.jdt.internal.ui.JavaPlugin;
/**
* Proxy for JavaEditorTextHovers.
*
* @since 2.1
*/
public class JavaEditorTextHoverProxy extends AbstractJavaEditorTextHover {
// XXX: Can be removed if we decide we don't want enabling and disabling of hovers
class ListenerRemover implements IPartListener {
void dispose() {
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
store.removePropertyChangeListener(fEnableStateUpdater);
fEnableStateUpdater= null;
stopListening();
setEditor(null);
}
private void stopListening() {
getEditor().getSite().getWorkbenchWindow().getPartService().removePartListener(this);
}
public void partClosed(IWorkbenchPart part) {
if (part == getEditor())
dispose();
}
public void partOpened(IWorkbenchPart part) {
}
public void partDeactivated(IWorkbenchPart part) {
}
public void partActivated(IWorkbenchPart part) {
}
public void partBroughtToTop(IWorkbenchPart part) {
}
};
// XXX: Can be removed if we decide we don't want enabling and disabling of hovers
class EnableStateUpdater implements IPropertyChangeListener {
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (PreferenceConstants.EDITOR_SHOW_HOVER.equals(event.getProperty())) {
Object newValue= event.getNewValue();
if (newValue instanceof Boolean)
fEnabled= ((Boolean) newValue).booleanValue();
}
}
};
private JavaEditorTextHoverDescriptor fHoverDescriptor;
private IJavaEditorTextHover fHover;
private boolean fEnabled;
private IPropertyChangeListener fEnableStateUpdater;
private ListenerRemover fListenerRemover;
public JavaEditorTextHoverProxy(JavaEditorTextHoverDescriptor descriptor, IEditorPart editor) {
fEnabled= JavaPlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SHOW_HOVER);
fHoverDescriptor= descriptor;
setEditor(editor);
}
/*
* @see IJavaEditorTextHover#setEditor(IEditorPart)
*/
public void setEditor(IEditorPart editor) {
if (getEditor() != null && fListenerRemover != null)
fListenerRemover.stopListening();
super.setEditor(editor);
if (fHover != null)
fHover.setEditor(getEditor());
// XXX: Can be removed if we decide we don't want enabling and disabling of hovers
// if (fEditor != null) {
// fListenerRemover= new ListenerRemover();
// IWorkbenchWindow window= fEditor.getSite().getWorkbenchWindow();
// window.getPartService().addPartListener(fListenerRemover);
//
// if (fEnableStateUpdater == null) {
// fEnableStateUpdater= new EnableStateUpdater();
// IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
// store.addPropertyChangeListener(fEnableStateUpdater);
// }
// }
}
public boolean isEnabled() {
return true;
}
/*
* @see ITextHover#getHoverRegion(ITextViewer, int)
*/
public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
if (!isEnabled() || fHoverDescriptor == null)
return null;
if (isCreated() || createHover())
return fHover.getHoverRegion(textViewer, offset);
else
return null;
}
/*
* @see ITextHover#getHoverInfo(ITextViewer, IRegion)
*/
public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
if (!isEnabled() || fHoverDescriptor == null)
return null;
if (isCreated() || createHover())
return fHover.getHoverInfo(textViewer, hoverRegion);
else
return null;
}
public void dispose() {
fListenerRemover.dispose();
}
private boolean isCreated() {
return fHover != null;
}
private boolean createHover() {
fHover= fHoverDescriptor.createTextHover();
if (fHover != null)
fHover.setEditor(getEditor());
return isCreated();
}
}
|
26,261 |
Bug 26261 Confusion after setting hover prefs due to disabled hover - remove hover toggle
|
20021113 i set the 'shift' hover to source - nothing happens on hovering with shift down
|
resolved fixed
|
eb40e76
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-22T09:52:19Z | 2002-11-14T10:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/PreferenceConstants.java
|
/*******************************************************************************
* Copyright (c) 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.ui;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Display;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.ui.texteditor.AbstractTextEditor;
import org.eclipse.ui.texteditor.WorkbenchChainedTextFontFieldEditor;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.ui.text.IJavaColorConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.preferences.NewJavaProjectPreferencePage;
/**
* Preference constants used in the JDT-UI preference store. Clients should only read the
* JDT-UI preference store using these values. Clients are not allowed to modify the
* preference store programmatically.
*
* @since 2.0
*/
public class PreferenceConstants {
private PreferenceConstants() {
}
/**
* A named preference that controls return type rendering of methods in the UI.
* <p>
* Value is of type <code>Boolean</code>: if <code>true</code> return types
* are rendered
* </p>
*/
public static final String APPEARANCE_METHOD_RETURNTYPE= "org.eclipse.jdt.ui.methodreturntype";//$NON-NLS-1$
/**
* A named preference that controls if override indicators are rendered in the UI.
* <p>
* Value is of type <code>Boolean</code>: if <code>true</code> override
* indicators are rendered
* </p>
*/
public static final String APPEARANCE_OVERRIDE_INDICATOR= "org.eclipse.jdt.ui.overrideindicator";//$NON-NLS-1$
/**
* A named preference that defines the pattern used for package name compression.
* <p>
* Value is of type <code>String</code>. For example foe the given package name 'org.eclipse.jdt' pattern
* '.' will compress it to '..jdt', '1~' to 'o~.e~.jdt'.
* </p>
*/
public static final String APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW= "PackagesView.pkgNamePatternForPackagesView";//$NON-NLS-1$
/**
* A named preference that controls if package name compression is turned on or off.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*
* @see #APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW
*/
public static final String APPEARANCE_COMPRESS_PACKAGE_NAMES= "org.eclipse.jdt.ui.compresspackagenames";//$NON-NLS-1$
/**
* A named preference that controls if empty inner packages are folded in
* the hierarchical mode of the package explorer.
* <p>
* Value is of type <code>Boolean</code>: if <code>true</code> empty
* inner packages are folded.
* </p>
* @since 2.1
*/
public static final String APPEARANCE_FOLD_PACKAGES_IN_PACKAGE_EXPLORER= "org.eclipse.jdt.ui.flatPackagesInPackageExplorer";//$NON-NLS-1$
/**
* A named preference that 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>
*/
public static final String CODEGEN_USE_GETTERSETTER_PREFIX= "org.eclipse.jdt.ui.gettersetter.prefix.enable";//$NON-NLS-1$
/**
* A named preference that holds a list of prefixes to be removed from a local variable to compute setter
* and gettter names.
* <p>
* Value is of type <code>String</code>: comma separated list of prefixed
* </p>
*
* @see #CODEGEN_USE_GETTERSETTER_PREFIX
*/
public static final String CODEGEN_GETTERSETTER_PREFIX= "org.eclipse.jdt.ui.gettersetter.prefix.list";//$NON-NLS-1$
/**
* A named preference that controls if suffix removal during setter/getter generation is turned on or off.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public static final String CODEGEN_USE_GETTERSETTER_SUFFIX= "org.eclipse.jdt.ui.gettersetter.suffix.enable";//$NON-NLS-1$
/**
* A named preference that holds a list of suffixes to be removed from a local variable to compute setter
* and getter names.
* <p>
* Value is of type <code>String</code>: comma separated list of suffixes
* </p>
*
* @see #CODEGEN_USE_GETTERSETTER_SUFFIX
*/
public static final String CODEGEN_GETTERSETTER_SUFFIX= "org.eclipse.jdt.ui.gettersetter.suffix.list"; //$NON-NLS-1$
/**
* A name preference that controls if a JavaDoc stub gets added to newly created types and methods.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public static final String CODEGEN__JAVADOC_STUBS= "org.eclipse.jdt.ui.javadoc"; //$NON-NLS-1$
/**
* A named preference that controls if a non-javadoc comment gets added to methods generated via the
* "Override Methods" operation.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public static final String CODEGEN__NON_JAVADOC_COMMENTS= "org.eclipse.jdt.ui.seecomments"; //$NON-NLS-1$
/**
* A named preference that controls if a file comment gets added to newly created files.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public static final String CODEGEN__FILE_COMMENTS= "org.eclipse.jdt.ui.filecomments"; //$NON-NLS-1$
/**
* A named preference that holds a list of comma separated package names. The list specifies the import order used by
* the "Organize Imports" opeation.
* <p>
* Value is of type <code>String</code>: 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 browsing view's selection is
* linked to the active editor.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public static final String LINK_BROWSING_VIEW_TO_EDITOR= "org.eclipse.jdt.ui.browsing.linktoeditor"; //$NON-NLS-1$
/**
* A named preference that controls whether new projects are generated using source and output folder.
* <p>
* Value is of type <code>Boolean</code>. if <code>true</code> new projects are created with a source and
* output folder. If <code>false</code> source and output folder equals to the project.
* </p>
*/
public static final String SRCBIN_FOLDERS_IN_NEWPROJ= "org.eclipse.jdt.ui.wizards.srcBinFoldersInNewProjects"; //$NON-NLS-1$
/**
* A named preference that specifies the source folder name used when creating a new Java project. Value is inactive
* if <code>SRCBIN_FOLDERS_IN_NEWPROJ</code> is set to <code>false</code>.
* <p>
* Value is of type <code>String</code>.
* </p>
*
* @see #SRCBIN_FOLDERS_IN_NEWPROJ
*/
public static final String SRCBIN_SRCNAME= "org.eclipse.jdt.ui.wizards.srcBinFoldersSrcName"; //$NON-NLS-1$
/**
* A named preference that specifies the output folder name used when creating a new Java project. Value is inactive
* if <code>SRCBIN_FOLDERS_IN_NEWPROJ</code> is set to <code>false</code>.
* <p>
* Value is of type <code>String</code>.
* </p>
*
* @see #SRCBIN_FOLDERS_IN_NEWPROJ
*/
public static final String SRCBIN_BINNAME= "org.eclipse.jdt.ui.wizards.srcBinFoldersBinName"; //$NON-NLS-1$
/**
* A named preference that holds a list of possible JRE libraries used by the New Java Project wizard. An library
* consists of a description and an arbitrary number of <code>IClasspathEntry</code>s, that will represent the
* JRE on the new project's classpath.
* <p>
* Value is of type <code>String</code>: a semicolon separated list of encoded JRE libraries.
* <code>NEWPROJECT_JRELIBRARY_INDEX</code> defines the currently used library. Clients
* should use the method <code>encodeJRELibrary</code> to encode a JRE library into a string
* and the methods <code>decodeJRELibraryDescription(String)</code> and <code>
* decodeJRELibraryClasspathEntries(String)</code> to decode the description and the array
* of classpath entries from an encoded string.
* </p>
*
* @see #NEWPROJECT_JRELIBRARY_INDEX
* @see #encodeJRELibrary(String, IClasspathEntry[])
* @see #decodeJRELibraryDescription(String)
* @see #decodeJRELibraryClasspathEntries(String)
*/
public static final String NEWPROJECT_JRELIBRARY_LIST= "org.eclipse.jdt.ui.wizards.jre.list"; //$NON-NLS-1$
/**
* A named preferences that specifies the current active JRE library.
* <p>
* Value is of type <code>Int</code>: an index into the list of possible JRE libraries.
* </p>
*
* @see #NEWPROJECT_JRELIBRARY_LIST
*/
public static final String NEWPROJECT_JRELIBRARY_INDEX= "org.eclipse.jdt.ui.wizards.jre.index"; //$NON-NLS-1$
/**
* A named preference that controls if a new type hierarchy gets opened in a
* new type hierarchy perspective or inside the type hierarchy view part.
* <p>
* Value is of type <code>String</code>: possible values are <code>
* OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE</code> or <code>
* OPEN_TYPE_HIERARCHY_IN_VIEW_PART</code>.
* </p>
*
* @see #OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE
* @see #OPEN_TYPE_HIERARCHY_IN_VIEW_PART
*/
public static final String OPEN_TYPE_HIERARCHY= "org.eclipse.jdt.ui.openTypeHierarchy"; //$NON-NLS-1$
/**
* A string value used by the named preference <code>OPEN_TYPE_HIERARCHY</code>.
*
* @see #OPEN_TYPE_HIERARCHY
*/
public static final String OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE= "perspective"; //$NON-NLS-1$
/**
* A string value used by the named preference <code>OPEN_TYPE_HIERARCHY</code>.
*
* @see #OPEN_TYPE_HIERARCHY
*/
public static final String OPEN_TYPE_HIERARCHY_IN_VIEW_PART= "viewPart"; //$NON-NLS-1$
/**
* A named preference that controls the behaviour when double clicking on a container in the packages view.
* <p>
* Value is of type <code>String</code>: possible values are <code>
* DOUBLE_CLICK_GOES_INTO</code> or <code>
* DOUBLE_CLICK_EXPANDS</code>.
* </p>
*
* @see #DOUBLE_CLICK_EXPANDS
* @see #DOUBLE_CLICK_GOES_INTO
*/
public static final String DOUBLE_CLICK= "packageview.doubleclick"; //$NON-NLS-1$
/**
* A string value used by the named preference <code>DOUBLE_CLICK</code>.
*
* @see #DOUBLE_CLICK
*/
public static final String DOUBLE_CLICK_GOES_INTO= "packageview.gointo"; //$NON-NLS-1$
/**
* A string value used by the named preference <code>DOUBLE_CLICK</code>.
*
* @see #DOUBLE_CLICK
*/
public static final String DOUBLE_CLICK_EXPANDS= "packageview.doubleclick.expands"; //$NON-NLS-1$
/**
* A named preference that controls whether Java views update their presentation while editing or when saving the
* content of an editor.
* <p>
* Value is of type <code>String</code>: possible values are <code>
* UPDATE_ON_SAVE</code> or <code>
* UPDATE_WHILE_EDITING</code>.
* </p>
*
* @see #UPDATE_ON_SAVE
* @see #UPDATE_WHILE_EDITING
*/
public static final String UPDATE_JAVA_VIEWS= "JavaUI.update"; //$NON-NLS-1$
/**
* A string value used by the named preference <code>UPDATE_JAVA_VIEWS</code>
*
* @see #UPDATE_JAVA_VIEWS
*/
public static final String UPDATE_ON_SAVE= "JavaUI.update.onSave"; //$NON-NLS-1$
/**
* A string value used by the named preference <code>UPDATE_JAVA_VIEWS</code>
*
* @see #UPDATE_JAVA_VIEWS
*/
public static final String UPDATE_WHILE_EDITING= "JavaUI.update.whileEditing"; //$NON-NLS-1$
/**
* A named preference that holds the path of the Javadoc command used by the Javadoc creation wizard.
* <p>
* Value is of type <code>String</code>.
* </p>
*/
public static final String JAVADOC_COMMAND= "command"; //$NON-NLS-1$
/**
* A named preference that controls whether bracket matching highlighting is turned on or off.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_MATCHING_BRACKETS= "matchingBrackets"; //$NON-NLS-1$
/**
* A named preference that holds the color used to highlight matching brackets.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_MATCHING_BRACKETS_COLOR= "matchingBracketsColor"; //$NON-NLS-1$
/**
* A named preference that controls whether the current line highlighting is turned on or off.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_CURRENT_LINE= "currentLine"; //$NON-NLS-1$
/**
* A named preference that holds the color used to highlight the current line.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_CURRENT_LINE_COLOR= "currentLineColor"; //$NON-NLS-1$
/**
* A named preference that controls whether the print margin is turned on or off.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_PRINT_MARGIN= "printMargin"; //$NON-NLS-1$
/**
* A named preference that holds the color used to render the print margin.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_PRINT_MARGIN_COLOR= "printMarginColor"; //$NON-NLS-1$
/**
* Print margin column. Int value.
*/
public final static String EDITOR_PRINT_MARGIN_COLUMN= "printMarginColumn"; //$NON-NLS-1$
/**
* A named preference that holds the color used for the find/replace scope.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_FIND_SCOPE_COLOR= AbstractTextEditor.PREFERENCE_COLOR_FIND_SCOPE;
/**
* A named preference that specifies if the editor uses spaces for tabs.
* <p>
* Value is of type <code>Boolean</code>. If <code>true</code>spaces instead of tabs are used
* in the editor. If <code>false</code> the editor inserts a tab character when pressing the tab
* key.
* </p>
*/
public final static String EDITOR_SPACES_FOR_TABS= "spacesForTabs"; //$NON-NLS-1$
/**
* A named preference that holds the number of spaces used per tab in the editor.
* <p>
* Value is of type <code>Int</code>: positive int value specifying the number of
* spaces per tab.
* </p>
*/
public final static String EDITOR_TAB_WIDTH= "org.eclipse.jdt.ui.editor.tab.width"; //$NON-NLS-1$
/**
* A named preference that controls whether the outline view selection
* should stay in sync with with the element at the current cursor position.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE= "JavaEditor.SyncOutlineOnCursorMove"; //$NON-NLS-1$
/**
* A named preference that controls if correction indicators are shown in the UI.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_CORRECTION_INDICATION= "JavaEditor.ShowTemporaryProblem"; //$NON-NLS-1$
/**
* A named preference that controls whether the editor shows problem indicators in text (squiggly lines).
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_PROBLEM_INDICATION= "problemIndication"; //$NON-NLS-1$
/**
* A named preference that holds the color used to render problem indicators.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see #EDITOR_PROBLEM_INDICATION
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_PROBLEM_INDICATION_COLOR= "problemIndicationColor"; //$NON-NLS-1$
/**PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR;
* A named preference that controls whether the editor shows warning indicators in text (squiggly lines).
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_WARNING_INDICATION= "warningIndication"; //$NON-NLS-1$
/**
* A named preference that holds the color used to render warning indicators.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see #EDITOR_WARNING_INDICATION
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_WARNING_INDICATION_COLOR= "warningIndicationColor"; //$NON-NLS-1$
/**
* A named preference that controls whether the editor shows task indicators in text (squiggly lines).
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_TASK_INDICATION= "taskIndication"; //$NON-NLS-1$
/**
* A named preference that holds the color used to render task indicators.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see #EDITOR_TASK_INDICATION
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_TASK_INDICATION_COLOR= "taskIndicationColor"; //$NON-NLS-1$
/**
* A named preference that controls whether the editor shows bookmark
* indicators in text (squiggly lines).
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_BOOKMARK_INDICATION= "bookmarkIndication"; //$NON-NLS-1$
/**
* A named preference that holds the color used to render bookmark indicators.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see #EDITOR_BOOKMARK_INDICATION
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
* @since 2.1
*/
public final static String EDITOR_BOOKMARK_INDICATION_COLOR= "bookmarkIndicationColor"; //$NON-NLS-1$
/**
* A named preference that controls whether the editor shows search
* indicators in text (squiggly lines).
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_SEARCH_RESULT_INDICATION= "searchResultIndication"; //$NON-NLS-1$
/**
* A named preference that holds the color used to render search indicators.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see #EDITOR_SEARCH_RESULT_INDICATION
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
* @since 2.1
*/
public final static String EDITOR_SEARCH_RESULT_INDICATION_COLOR= "searchResultIndicationColor"; //$NON-NLS-1$
/**
* A named preference that controls whether the editor shows unknown
* indicators in text (squiggly lines).
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_UNKNOWN_INDICATION= "othersIndication"; //$NON-NLS-1$
/**
* A named preference that holds the color used to render unknown
* indicators.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see #EDITOR_UNKNOWN_INDICATION
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
* @since 2.1
*/
public final static String EDITOR_UNKNOWN_INDICATION_COLOR= "othersIndicationColor"; //$NON-NLS-1$
/**
* A named preference that controls whether the overview ruler shows error
* indicators.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER= "errorIndicationInOverviewRuler"; //$NON-NLS-1$
/**
* A named preference that controls whether the overview ruler shows warning
* indicators.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER= "warningIndicationInOverviewRuler"; //$NON-NLS-1$
/**
* A named preference that controls whether the overview ruler shows task
* indicators.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER= "taskIndicationInOverviewRuler"; //$NON-NLS-1$
/**
* A named preference that controls whether the overview ruler shows
* bookmark indicators.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER= "bookmarkIndicationInOverviewRuler"; //$NON-NLS-1$
/**
* A named preference that controls whether the overview ruler shows
* search result indicators.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER= "searchResultIndicationInOverviewRuler"; //$NON-NLS-1$
/**
* A named preference that controls whether the overview ruler shows
* unknown indicators.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER= "othersIndicationInOverviewRuler"; //$NON-NLS-1$
/**
* A named preference that controls whether the 'close strings' feature
* is enabled.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_CLOSE_STRINGS= "closeStrings"; //$NON-NLS-1$
/**
* A named preference that controls whether the 'wrap strings' feature is
* enabled.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_WRAP_STRINGS= "wrapStrings"; //$NON-NLS-1$
/**
* A named preference that controls whether the 'close brackets' feature is
* enabled.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_CLOSE_BRACKETS= "closeBrackets"; //$NON-NLS-1$
/**
* A named preference that controls whether the 'close java docs' feature is
* enabled.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_CLOSE_JAVADOCS= "closeJavaDocs"; //$NON-NLS-1$
/**
* A named preference that controls whether the 'add JavaDoc tags' feature
* is enabled.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_ADD_JAVADOC_TAGS= "addJavaDocTags"; //$NON-NLS-1$
/**
* A named preference that controls whether the 'format Javadoc tags'
* feature is enabled.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_FORMAT_JAVADOCS= "formatJavaDocs"; //$NON-NLS-1$
/**
* A named preference that controls whether the 'smart paste' feature is
* enabled.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_SMART_PASTE= "smartPaste"; //$NON-NLS-1$
/**
* A named preference that controls whether the 'smart home-end' feature is
* enabled.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_SMART_HOME_END= AbstractTextEditor.PREFERENCE_NAVIGATION_SMART_HOME_END;
/**
* A named preference that controls if temporary problems are evaluated and shown in the UI.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_EVALUTE_TEMPORARY_PROBLEMS= "handleTemporaryProblems"; //$NON-NLS-1$
/**
* A named preference that controls if the overview ruler is shown in the UI.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_OVERVIEW_RULER= "overviewRuler"; //$NON-NLS-1$
/**
* A named preference that controls if the line number ruler is shown in the UI.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_LINE_NUMBER_RULER= "lineNumberRuler"; //$NON-NLS-1$
/**
* A named preference that holds the color used to render line numbers inside the line number ruler.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
* @see #EDITOR_LINE_NUMBER_RULER
*/
public final static String EDITOR_LINE_NUMBER_RULER_COLOR= "lineNumberColor"; //$NON-NLS-1$
/**
* A named preference that holds the color used to render linked positions inside code templates.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_LINKED_POSITION_COLOR= "linkedPositionColor"; //$NON-NLS-1$
/**
* A named preference that holds the color used as the text foreground.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_FOREGROUND_COLOR= AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND;
/**
* A named preference that describes if the system default foreground color
* is used as the text foreground.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_FOREGROUND_DEFAULT_COLOR= AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT;
/**
* A named preference that holds the color used as the text background.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_BACKGROUND_COLOR= AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND;
/**
* A named preference that describes if the system default background color
* is used as the text foreground.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_BACKGROUND_DEFAULT_COLOR= AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT;
/**
* Preference key suffix for bold text style preference keys.
*/
public static final String EDITOR_BOLD_SUFFIX= "_bold"; //$NON-NLS-1$
/**
* A named preference that holds the color used to render multi line comments.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_MULTI_LINE_COMMENT_COLOR= IJavaColorConstants.JAVA_MULTI_LINE_COMMENT;
/**
* A named preference that controls whether multi line comments are rendered in bold.
* <p>
* Value is of type <code>Boolean</code>. If <code>true</code> multi line comments are rendered
* in bold. If <code>false</code> the are rendered using no font style attribute.
* </p>
*/
public final static String EDITOR_MULTI_LINE_COMMENT_BOLD= IJavaColorConstants.JAVA_MULTI_LINE_COMMENT + EDITOR_BOLD_SUFFIX;
/**
* A named preference that holds the color used to render single line comments.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_SINGLE_LINE_COMMENT_COLOR= IJavaColorConstants.JAVA_SINGLE_LINE_COMMENT;
/**
* A named preference that controls whether sinle line comments are rendered in bold.
* <p>
* Value is of type <code>Boolean</code>. If <code>true</code> single line comments are rendered
* in bold. If <code>false</code> the are rendered using no font style attribute.
* </p>
*/
public final static String EDITOR_SINGLE_LINE_COMMENT_BOLD= IJavaColorConstants.JAVA_SINGLE_LINE_COMMENT + EDITOR_BOLD_SUFFIX;
/**
* A named preference that holds the color used to render java keywords.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_JAVA_KEYWORD_COLOR= IJavaColorConstants.JAVA_KEYWORD;
/**
* A named preference that controls whether keywords are rendered in bold.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_JAVA_KEYWORD_BOLD= IJavaColorConstants.JAVA_KEYWORD + EDITOR_BOLD_SUFFIX;
/**
* A named preference that holds the color used to render string constants.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_STRING_COLOR= IJavaColorConstants.JAVA_STRING;
/**
* A named preference that controls whether string constants are rendered in bold.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_STRING_BOLD= IJavaColorConstants.JAVA_STRING + EDITOR_BOLD_SUFFIX;
/**
* A named preference that holds the color used to render java default text.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_JAVA_DEFAULT_COLOR= IJavaColorConstants.JAVA_DEFAULT;
/**
* A named preference that controls whether Java default text is rendered in bold.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_JAVA_DEFAULT_BOLD= IJavaColorConstants.JAVA_DEFAULT + EDITOR_BOLD_SUFFIX;
/**
* A named preference that holds the color used to render javadoc keywords.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_JAVADOC_KEYWORD_COLOR= IJavaColorConstants.JAVADOC_KEYWORD;
/**
* A named preference that controls whether javadoc keywords are rendered in bold.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_JAVADOC_KEYWORD_BOLD= IJavaColorConstants.JAVADOC_KEYWORD + EDITOR_BOLD_SUFFIX;
/**
* A named preference that holds the color used to render javadoc tags.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_JAVADOC_TAG_COLOR= IJavaColorConstants.JAVADOC_TAG;
/**
* A named preference that controls whether javadoc tags are rendered in bold.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_JAVADOC_TAG_BOLD= IJavaColorConstants.JAVADOC_TAG + EDITOR_BOLD_SUFFIX;
/**
* A named preference that holds the color used to render javadoc links.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_JAVADOC_LINKS_COLOR= IJavaColorConstants.JAVADOC_LINK;
/**
* A named preference that controls whether javadoc links are rendered in bold.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_JAVADOC_LINKS_BOLD= IJavaColorConstants.JAVADOC_LINK + EDITOR_BOLD_SUFFIX;
/**
* A named preference that holds the color used to render javadoc default text.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_JAVADOC_DEFAULT_COLOR= IJavaColorConstants.JAVADOC_DEFAULT;
/**
* A named preference that controls whether javadoc default text is rendered in bold.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_JAVADOC_DEFAULT_BOLD= IJavaColorConstants.JAVADOC_DEFAULT + EDITOR_BOLD_SUFFIX;
/**
* A named preference that holds the color used for 'linked-mode' underline.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
* @since 2.1
*/
public final static String EDITOR_LINK_COLOR= "linkColor"; //$NON-NLS-1$
/**
* A named preference that controls whether hover tooltips in the editor are turned on or off.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public static final String EDITOR_SHOW_HOVER= "org.eclipse.jdt.ui.editor.showHover"; //$NON-NLS-1$
/**
* A named preference that defines the hover shown when no control key is
* pressed.
* <p>Value is of type <code>String</code>: possible values are <code>
* EDITOR_NO_HOVER_CONFIGURED_ID</code> or
* <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a hover
* contributed as <code>javaEditorTextHovers</code>.
* </p>
* @see #EDITOR_NO_HOVER_CONFIGURED_ID
* @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID
* @see JavaUI
* @since 2.1
*/
public static final String EDITOR_NONE_HOVER= "noneHover"; //$NON-NLS-1$
/**
* A named preference that defines the hover shown when the
* <code>CTRL</code> modifier key is pressed.
* <p>Value is of type <code>String</code>: possible values are <code>
* EDITOR_NO_HOVER_CONFIGURED_ID</code> or
* <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a
* hover contributed as <code>javaEditorTextHovers</code>.
* </p>
* @see #EDITOR_NO_HOVER_CONFIGURED_ID
* @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID
* @see JavaUI
* @since 2.1
*/
public static final String EDITOR_CTRL_HOVER= "ctrlHover"; //$NON-NLS-1$
/**
* A named preference that defines the hover shown when the
* <code>SHIFT</code> modifier key is pressed.
* <p>Value is of type <code>String</code>: possible values are <code>
* EDITOR_NO_HOVER_CONFIGURED_ID</code> or
* <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a
* hover contributed as <code>javaEditorTextHovers</code>.
* </p>
* @see #EDITOR_NO_HOVER_CONFIGURED_ID
* @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID
* @see JavaUI ID_*_HOVER
* @since 2.1
*/
public static final String EDITOR_SHIFT_HOVER= "shiftHover"; //$NON-NLS-1$
/**
* A named preference that defines the hover shown when the
* <code>CTRL + ALT</code> modifier keys is pressed.
* <p>Value is of type <code>String</code>: possible values are <code>
* EDITOR_NO_HOVER_CONFIGURED_ID</code> or
* <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a
* hover contributed as <code>javaEditorTextHovers</code>.
* </p>
* @see #EDITOR_NO_HOVER_CONFIGURED_ID
* @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID
* @see JavaUI ID_*_HOVER
* @since 2.1
*/
public static final String EDITOR_CTRL_ALT_HOVER= "ctrlAltHover"; //$NON-NLS-1$
/**
* A named preference that defines the hover shown when the
* <code>CTRL + ALT + SHIFT</code> modifier keys is pressed.
* <p>Value is of type <code>String</code>: possible values are <code>
* EDITOR_NO_HOVER_CONFIGURED_ID</code> or
* <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a
* hover contributed as <code>javaEditorTextHovers</code>.
* </p>
* @see #EDITOR_NO_HOVER_CONFIGURED_ID
* @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID
* @see JavaUI ID_*_HOVER
* @since 2.1
*/
public static final String EDITOR_CTRL_ALT_SHIFT_HOVER= "ctrlAltShiftHover"; //$NON-NLS-1$
/**
* A named preference that defines the hover shown when the
* <code>CTRL + SHIFT</code> modifier keys is pressed.
* <p>Value is of type <code>String</code>: possible values are <code>
* EDITOR_NO_HOVER_CONFIGURED_ID</code> or
* <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a
* hover contributed as <code>javaEditorTextHovers</code>.
* </p>
* @see #EDITOR_NO_HOVER_CONFIGURED_ID
* @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID
* @see JavaUI ID_*_HOVER
* @since 2.1
*/
public static final String EDITOR_CTRL_SHIFT_HOVER= "ctrlShiftHover"; //$NON-NLS-1$
/**
* A named preference that defines the hover shown when the
* <code>ALT</code> modifier key is pressed.
* <p>Value is of type <code>String</code>: possible values are <code>
* EDITOR_NO_HOVER_CONFIGURED_ID</code>,
* <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a
* hover contributed as <code>javaEditorTextHovers</code>.
* </p>
* @see #EDITOR_NO_HOVER_CONFIGURED_ID
* @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID
* @see JavaUI ID_*_HOVER
* @since 2.1
*/
public static final String EDITOR_ALT_SHIFT_HOVER= "altShiftHover"; //$NON-NLS-1$
/**
* A string value used by the named preferences for hover configuration to
* descibe that no hover should be shown for the given key modifiers.
* @since 2.1
*/
public static final String EDITOR_NO_HOVER_CONFIGURED_ID= "noHoverConfiguredId"; //$NON-NLS-1$
/**
* A string value used by the named preferences for hover configuration to
* descibe that the default hover should be shown for the given key
* modifiers. The default hover is described by the
* <code>EDITOR_DEFAULT_HOVER</code> property.
* @since 2.1
*/
public static final String EDITOR_DEFAULT_HOVER_CONFIGURED_ID= "defaultHoverConfiguredId"; //$NON-NLS-1$
/**
* A named preference that defines the hover named the 'default hover'.
* Value is of type <code>String</code>: possible values are <code>
* EDITOR_NO_HOVER_CONFIGURED_ID</code> or <code> the hover id of a hover
* contributed as <code>javaEditorTextHovers</code>.
* </p>
*@since 2.1
*/
public static final String EDITOR_DEFAULT_HOVER= "defaultHover"; //$NON-NLS-1$
/**
* A named preference that controls if segmented view (show selected element only) is turned on or off.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public static final String EDITOR_SHOW_SEGMENTS= "org.eclipse.jdt.ui.editor.showSegments"; //$NON-NLS-1$
/**
* A named preference that controls if the Java code assist gets auto activated.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String CODEASSIST_AUTOACTIVATION= "content_assist_autoactivation"; //$NON-NLS-1$
/**
* A name preference that holds the auto activation delay time in milli seconds.
* <p>
* Value is of type <code>Int</code>.
* </p>
*/
public final static String CODEASSIST_AUTOACTIVATION_DELAY= "content_assist_autoactivation_delay"; //$NON-NLS-1$
/**
* A named preference that controls if code assist contains only visible proposals.
* <p>
* Value is of type <code>Boolean</code>. if <code>true<code> code assist only contains visible members. If
* <code>false</code> all members are included.
* </p>
*/
public final static String CODEASSIST_SHOW_VISIBLE_PROPOSALS= "content_assist_show_visible_proposals"; //$NON-NLS-1$
/**
* A named preference that controls if the Java code assist inserts a
* proposal automatically if only one proposal is available.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String CODEASSIST_AUTOINSERT= "content_assist_autoinsert"; //$NON-NLS-1$
/**
* A named preference that controls if the Java code assist adds import
* statements.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String CODEASSIST_ADDIMPORT= "content_assist_add_import"; //$NON-NLS-1$
/**
* A named preference that controls if the Java code assist only inserts
* completions. If set to false the proposals can also _replace_ code.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String CODEASSIST_INSERT_COMPLETION= "content_assist_insert_completion"; //$NON-NLS-1$
/**
* A named preference that controls whether code assist proposals filtering is case sensitive or not.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String CODEASSIST_CASE_SENSITIVITY= "content_assist_case_sensitivity"; //$NON-NLS-1$
/**
* A named preference that defines if code assist proposals are sorted in alphabetical order.
* <p>
* Value is of type <code>Boolean</code>. If <code>true</code> that are sorted in alphabetical
* order. If <code>false</code> that are unsorted.
* </p>
*/
public final static String CODEASSIST_ORDER_PROPOSALS= "content_assist_order_proposals"; //$NON-NLS-1$
/**
* A named preference that controls if argument names are filled in when a method is selected from as list
* of code assist proposal.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String CODEASSIST_FILL_ARGUMENT_NAMES= "content_assist_fill_method_arguments"; //$NON-NLS-1$
/**
* A named preference that controls if method arguments are guessed when a
* method is selected from as list of code assist proposal.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String CODEASSIST_GUESS_METHOD_ARGUMENTS= "content_assist_guess_method_arguments"; //$NON-NLS-1$
/**
* A named preference that holds the characters that auto activate code assist in Java code.
* <p>
* Value is of type <code>Sring</code>. All characters that trigger auto code assist in Java code.
* </p>
*/
public final static String CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA= "content_assist_autoactivation_triggers_java"; //$NON-NLS-1$
/**
* A named preference that holds the characters that auto activate code assist in Javadoc.
* <p>
* Value is of type <code>Sring</code>. All characters that trigger auto code assist in Javadoc.
* </p>
*/
public final static String CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC= "content_assist_autoactivation_triggers_javadoc"; //$NON-NLS-1$
/**
* A named preference that holds the background color used in the code assist selection dialog.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String CODEASSIST_PROPOSALS_BACKGROUND= "content_assist_proposals_background"; //$NON-NLS-1$
/**
* A named preference that holds the foreground color used in the code assist selection dialog.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String CODEASSIST_PROPOSALS_FOREGROUND= "content_assist_proposals_foreground"; //$NON-NLS-1$
/**
* A named preference that holds the background color used for parameter hints.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String CODEASSIST_PARAMETERS_BACKGROUND= "content_assist_parameters_background"; //$NON-NLS-1$
/**
* A named preference that holds the foreground color used in the code assist selection dialog
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String CODEASSIST_PARAMETERS_FOREGROUND= "content_assist_parameters_foreground"; //$NON-NLS-1$
/**
* A named preference that holds the background color used in the code
* assist selection dialog to mark replaced code.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
* @since 2.1
*/
public final static String CODEASSIST_REPLACEMENT_BACKGROUND= "content_assist_completion_replacement_background"; //$NON-NLS-1$
/**
* A named preference that holds the foreground color used in the code
* assist selection dialog to mark replaced code.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
* @since 2.1
*/
public final static String CODEASSIST_REPLACEMENT_FOREGROUND= "content_assist_completion_replacement_foreground"; //$NON-NLS-1$
/**
* A named preference that controls the behaviour of the refactoring wizard for showing the error page.
* <p>
* Value is of type <code>String</code>. Valid values are:
* <code>REFACTOR_FATAL_SEVERITY</code>,
* <code>REFACTOR_ERROR_SEVERITY</code>,
* <code>REFACTOR_WARNING_SEVERITY</code>
* <code>REFACTOR_INFO_SEVERITY</code>,
* <code>REFACTOR_OK_SEVERITY</code>.
* </p>
*
* @see #REFACTOR_FATAL_SEVERITY
* @see #REFACTOR_ERROR_SEVERITY
* @see #REFACTOR_WARNING_SEVERITY
* @see #REFACTOR_INFO_SEVERITY
* @see #REFACTOR_OK_SEVERITY
*/
public static final String REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD= "Refactoring.ErrorPage.severityThreshold"; //$NON-NLS-1$
/**
* A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>.
*
* @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD
*/
public static final String REFACTOR_FATAL_SEVERITY= "4"; //$NON-NLS-1$
/**
* A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>.
*
* @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD
*/
public static final String REFACTOR_ERROR_SEVERITY= "3"; //$NON-NLS-1$
/**
* A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>.
*
* @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD
*/
public static final String REFACTOR_WARNING_SEVERITY= "2"; //$NON-NLS-1$
/**
* A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>.
*
* @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD
*/
public static final String REFACTOR_INFO_SEVERITY= "1"; //$NON-NLS-1$
/**
* A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>.
*
* @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD
*/
public static final String REFACTOR_OK_SEVERITY= "0"; //$NON-NLS-1$
/**
* A named preference thet controls whether all dirty editors are automatically saved before a refactoring is
* executed.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public static final String REFACTOR_SAVE_ALL_EDITORS= "Refactoring.savealleditors"; //$NON-NLS-1$
/**
* A named preference that controls if the Java Browsing views are linked to the active editor.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*
* @see #LINK_PACKAGES_TO_EDITOR
*/
public static final String BROWSING_LINK_VIEW_TO_EDITOR= "org.eclipse.jdt.ui.browsing.linktoeditor"; //$NON-NLS-1$
/**
* A named preference that controls the layout of the Java Browsing views vertically. Boolean value.
* <p>
* Value is of type <code>Boolean</code>. If <code>true<code> the views are stacked vertical.
* If <code>false</code> they are stacked horizontal.
* </p>
*/
public static final String BROWSING_STACK_VERTICALLY= "org.eclipse.jdt.ui.browsing.stackVertically"; //$NON-NLS-1$
/**
* A named preference that controls if templates are formatted when applied.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*
* @since 2.1
*/
public static final String TEMPLATES_USE_CODEFORMATTER= "org.eclipse.jdt.ui.template.format"; //$NON-NLS-1$
public static void initializeDefaultValues(IPreferenceStore store) {
store.setDefault(PreferenceConstants.EDITOR_SHOW_HOVER, true);
store.setDefault(PreferenceConstants.EDITOR_SHOW_SEGMENTS, false);
// JavaBasePreferencePage
store.setDefault(PreferenceConstants.LINK_PACKAGES_TO_EDITOR, true);
store.setDefault(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR, false);
store.setDefault(PreferenceConstants.LINK_BROWSING_VIEW_TO_EDITOR, true);
store.setDefault(PreferenceConstants.OPEN_TYPE_HIERARCHY, PreferenceConstants.OPEN_TYPE_HIERARCHY_IN_VIEW_PART);
store.setDefault(PreferenceConstants.DOUBLE_CLICK, PreferenceConstants.DOUBLE_CLICK_EXPANDS);
store.setDefault(PreferenceConstants.UPDATE_JAVA_VIEWS, PreferenceConstants.UPDATE_WHILE_EDITING);
// AppearancePreferencePage
store.setDefault(PreferenceConstants.APPEARANCE_COMPRESS_PACKAGE_NAMES, false);
store.setDefault(PreferenceConstants.APPEARANCE_METHOD_RETURNTYPE, false);
store.setDefault(PreferenceConstants.APPEARANCE_OVERRIDE_INDICATOR, true);
store.setDefault(PreferenceConstants.SHOW_CU_CHILDREN, true);
store.setDefault(PreferenceConstants.BROWSING_STACK_VERTICALLY, false);
store.setDefault(PreferenceConstants.APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW, ""); //$NON-NLS-1$
store.setDefault(PreferenceConstants.APPEARANCE_FOLD_PACKAGES_IN_PACKAGE_EXPLORER, true);
// ImportOrganizePreferencePage
store.setDefault(PreferenceConstants.ORGIMPORTS_IMPORTORDER, "java;javax;org;com"); //$NON-NLS-1$
store.setDefault(PreferenceConstants.ORGIMPORTS_ONDEMANDTHRESHOLD, 99);
store.setDefault(PreferenceConstants.ORGIMPORTS_IGNORELOWERCASE, true);
// ClasspathVariablesPreferencePage
// CodeFormatterPreferencePage
// CompilerPreferencePage
// no initialization needed
// RefactoringPreferencePage
store.setDefault(PreferenceConstants.REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD, PreferenceConstants.REFACTOR_ERROR_SEVERITY);
store.setDefault(PreferenceConstants.REFACTOR_SAVE_ALL_EDITORS, false);
// TemplatePreferencePage
store.setDefault(PreferenceConstants.TEMPLATES_USE_CODEFORMATTER, true);
// CodeGenerationPreferencePage
store.setDefault(PreferenceConstants.CODEGEN_USE_GETTERSETTER_PREFIX, false);
store.setDefault(PreferenceConstants.CODEGEN_USE_GETTERSETTER_SUFFIX, false);
store.setDefault(PreferenceConstants.CODEGEN_GETTERSETTER_PREFIX, "fg, f, _$, _, m_"); //$NON-NLS-1$
store.setDefault(PreferenceConstants.CODEGEN_GETTERSETTER_SUFFIX, "_"); //$NON-NLS-1$
store.setDefault(PreferenceConstants.CODEGEN__JAVADOC_STUBS, true);
store.setDefault(PreferenceConstants.CODEGEN__NON_JAVADOC_COMMENTS, false);
store.setDefault(PreferenceConstants.CODEGEN__FILE_COMMENTS, false);
// MembersOrderPreferencePage
store.setDefault(PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER, "T,SI,SF,SM,I,F,C,M"); //$NON-NLS-1$
// JavaEditorPreferencePage
/*
* Ensure that the display is accessed only in the UI thread.
* Ensure that there are no side effects of switching the thread.
*/
final RGB[] rgbs= new RGB[3];
final Display display= Display.getDefault();
display.syncExec(new Runnable() {
public void run() {
Color c= display.getSystemColor(SWT.COLOR_GRAY);
rgbs[0]= c.getRGB();
c= display.getSystemColor(SWT.COLOR_LIST_FOREGROUND);
rgbs[1]= c.getRGB();
c= display.getSystemColor(SWT.COLOR_LIST_BACKGROUND);
rgbs[2]= c.getRGB();
}
});
store.setDefault(PreferenceConstants.EDITOR_MATCHING_BRACKETS, true);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR, rgbs[0]);
store.setDefault(PreferenceConstants.EDITOR_CURRENT_LINE, true);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_CURRENT_LINE_COLOR, new RGB(225, 235, 224));
store.setDefault(PreferenceConstants.EDITOR_PRINT_MARGIN, false);
store.setDefault(PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN, 80);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR, new RGB(176, 180 , 185));
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_FIND_SCOPE_COLOR, new RGB(185, 176 , 180));
store.setDefault(PreferenceConstants.EDITOR_PROBLEM_INDICATION, true);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR, new RGB(255, 0 , 128));
store.setDefault(PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER, true);
store.setDefault(PreferenceConstants.EDITOR_WARNING_INDICATION, true);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR, new RGB(244, 200 , 45));
store.setDefault(PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER, true);
store.setDefault(PreferenceConstants.EDITOR_TASK_INDICATION, false);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_TASK_INDICATION_COLOR, new RGB(0, 128, 255));
store.setDefault(PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER, false);
store.setDefault(PreferenceConstants.EDITOR_BOOKMARK_INDICATION, false);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR, new RGB(34, 164, 99));
store.setDefault(PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER, false);
store.setDefault(PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION, false);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR, new RGB(192, 192, 192));
store.setDefault(PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER, false);
store.setDefault(PreferenceConstants.EDITOR_UNKNOWN_INDICATION, false);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR, new RGB(0, 0, 0));
store.setDefault(PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER, false);
store.setDefault(PreferenceConstants.EDITOR_CORRECTION_INDICATION, true);
store.setDefault(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE, false);
store.setDefault(PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS, true);
store.setDefault(PreferenceConstants.EDITOR_OVERVIEW_RULER, true);
store.setDefault(PreferenceConstants.EDITOR_LINE_NUMBER_RULER, false);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR, new RGB(0, 0, 0));
WorkbenchChainedTextFontFieldEditor.startPropagate(store, JFaceResources.TEXT_FONT);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_LINKED_POSITION_COLOR, new RGB(0, 200 , 100));
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_LINK_COLOR, new RGB(0, 0, 255));
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_FOREGROUND_COLOR, rgbs[1]);
store.setDefault(PreferenceConstants.EDITOR_FOREGROUND_DEFAULT_COLOR, true);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_BACKGROUND_COLOR, rgbs[2]);
store.setDefault(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR, true);
store.setDefault(PreferenceConstants.EDITOR_TAB_WIDTH, 4);
store.setDefault(PreferenceConstants.EDITOR_SPACES_FOR_TABS, false);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_COLOR, new RGB(63, 127, 95));
store.setDefault(PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_BOLD, false);
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_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_PASTE, true);
store.setDefault(PreferenceConstants.EDITOR_CLOSE_STRINGS, true);
store.setDefault(PreferenceConstants.EDITOR_CLOSE_BRACKETS, true);
store.setDefault(PreferenceConstants.EDITOR_CLOSE_JAVADOCS, true);
store.setDefault(PreferenceConstants.EDITOR_WRAP_STRINGS, true);
store.setDefault(PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS, true);
store.setDefault(PreferenceConstants.EDITOR_FORMAT_JAVADOCS, true);
store.setDefault(PreferenceConstants.EDITOR_SMART_HOME_END, true);
store.setDefault(PreferenceConstants.EDITOR_DEFAULT_HOVER, JavaPlugin.ID_BESTMATCH_HOVER);
store.setDefault(PreferenceConstants.EDITOR_NONE_HOVER, PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID);
store.setDefault(PreferenceConstants.EDITOR_CTRL_HOVER, JavaPlugin.ID_SOURCE_HOVER);
store.setDefault(PreferenceConstants.EDITOR_SHIFT_HOVER, PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID);
store.setDefault(PreferenceConstants.EDITOR_CTRL_SHIFT_HOVER, PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID);
store.setDefault(PreferenceConstants.EDITOR_CTRL_ALT_HOVER, PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID);
store.setDefault(PreferenceConstants.EDITOR_ALT_SHIFT_HOVER, PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID);
store.setDefault(PreferenceConstants.EDITOR_CTRL_ALT_SHIFT_HOVER, PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID);
// 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();
}
}
|
26,261 |
Bug 26261 Confusion after setting hover prefs due to disabled hover - remove hover toggle
|
20021113 i set the 'shift' hover to source - nothing happens on hovering with shift down
|
resolved fixed
|
eb40e76
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-22T09:52:19Z | 2002-11-14T10:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/text/JavaSourceViewerConfiguration.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.ui.text;
import java.util.Vector;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.DefaultInformationControl;
import org.eclipse.jface.text.DefaultTextDoubleClickStrategy;
import org.eclipse.jface.text.IAutoIndentStrategy;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IInformationControl;
import org.eclipse.jface.text.IInformationControlCreator;
import org.eclipse.jface.text.ITextDoubleClickStrategy;
import org.eclipse.jface.text.ITextHover;
import org.eclipse.jface.text.ITextViewerExtension2;
import org.eclipse.jface.text.contentassist.ContentAssistant;
import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
import org.eclipse.jface.text.contentassist.IContentAssistant;
import org.eclipse.jface.text.formatter.ContentFormatter;
import org.eclipse.jface.text.formatter.IContentFormatter;
import org.eclipse.jface.text.formatter.IFormattingStrategy;
import org.eclipse.jface.text.information.IInformationPresenter;
import org.eclipse.jface.text.information.IInformationProvider;
import org.eclipse.jface.text.information.InformationPresenter;
import org.eclipse.jface.text.presentation.IPresentationReconciler;
import org.eclipse.jface.text.presentation.PresentationReconciler;
import org.eclipse.jface.text.reconciler.IReconciler;
import org.eclipse.jface.text.rules.DefaultDamagerRepairer;
import org.eclipse.jface.text.rules.RuleBasedScanner;
import org.eclipse.jface.text.source.IAnnotationHover;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.ContentAssistPreference;
import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter;
import org.eclipse.jdt.internal.ui.text.JavaAnnotationHover;
import org.eclipse.jdt.internal.ui.text.JavaElementProvider;
import org.eclipse.jdt.internal.ui.text.JavaOutlineInformationControl;
import org.eclipse.jdt.internal.ui.text.JavaPartitionScanner;
import org.eclipse.jdt.internal.ui.text.JavaReconciler;
import org.eclipse.jdt.internal.ui.text.java.JavaAutoIndentStrategy;
import org.eclipse.jdt.internal.ui.text.java.JavaCompletionProcessor;
import org.eclipse.jdt.internal.ui.text.java.JavaDoubleClickSelector;
import org.eclipse.jdt.internal.ui.text.java.JavaFormattingStrategy;
import org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy;
import org.eclipse.jdt.internal.ui.text.java.JavaStringAutoIndentStrategy;
import org.eclipse.jdt.internal.ui.text.java.JavaStringDoubleClickSelector;
import org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverDescriptor;
import org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy;
import org.eclipse.jdt.internal.ui.text.java.hover.JavaInformationProvider;
import org.eclipse.jdt.internal.ui.text.javadoc.JavaDocAutoIndentStrategy;
import org.eclipse.jdt.internal.ui.text.javadoc.JavaDocCompletionProcessor;
/**
* Configuration for a source viewer which shows Java code.
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*/
public class JavaSourceViewerConfiguration extends SourceViewerConfiguration {
/**
* Preference key used to look up display tab width.
*
* @since 2.0
*/
public final static String PREFERENCE_TAB_WIDTH= PreferenceConstants.EDITOR_TAB_WIDTH;
/**
* Preference key for inserting spaces rather than tabs.
*
* @since 2.0
*/
public final static String SPACES_FOR_TABS= PreferenceConstants.EDITOR_SPACES_FOR_TABS;
private JavaTextTools fJavaTextTools;
private ITextEditor fTextEditor;
/**
* Creates a new Java source viewer configuration for viewers in the given editor
* using the given Java tools.
*
* @param tools the Java tools to be used
* @param editor the editor in which the configured viewer(s) will reside
*/
public JavaSourceViewerConfiguration(JavaTextTools tools, ITextEditor editor) {
fJavaTextTools= tools;
fTextEditor= editor;
}
/**
* Returns the Java source code scanner for this configuration.
*
* @return the Java source code scanner
*/
protected RuleBasedScanner getCodeScanner() {
return fJavaTextTools.getCodeScanner();
}
/**
* Returns the Java multiline comment scanner for this configuration.
*
* @return the Java multiline comment scanner
*
* @since 2.0
*/
protected RuleBasedScanner getMultilineCommentScanner() {
return fJavaTextTools.getMultilineCommentScanner();
}
/**
* Returns the Java singleline comment scanner for this configuration.
*
* @return the Java singleline comment scanner
*
* @since 2.0
*/
protected RuleBasedScanner getSinglelineCommentScanner() {
return fJavaTextTools.getSinglelineCommentScanner();
}
/**
* Returns the Java string scanner for this configuration.
*
* @return the Java string scanner
*
* @since 2.0
*/
protected RuleBasedScanner getStringScanner() {
return fJavaTextTools.getStringScanner();
}
/**
* Returns the JavaDoc scanner for this configuration.
*
* @return the JavaDoc scanner
*/
protected RuleBasedScanner getJavaDocScanner() {
return fJavaTextTools.getJavaDocScanner();
}
/**
* Returns the color manager for this configuration.
*
* @return the color manager
*/
protected IColorManager getColorManager() {
return fJavaTextTools.getColorManager();
}
/**
* Returns the editor in which the configured viewer(s) will reside.
*
* @return the enclosing editor
*/
protected ITextEditor getEditor() {
return fTextEditor;
}
/**
* Returns the preference store used by this configuration to initialize
* the individual bits and pieces.
*
* @return the preference store used to initialize this configuration
*
* @since 2.0
*/
protected IPreferenceStore getPreferenceStore() {
return JavaPlugin.getDefault().getPreferenceStore();
}
/*
* @see ISourceViewerConfiguration#getPresentationReconciler(ISourceViewer)
*/
public IPresentationReconciler getPresentationReconciler(ISourceViewer sourceViewer) {
PresentationReconciler reconciler= new PresentationReconciler();
DefaultDamagerRepairer dr= new DefaultDamagerRepairer(getCodeScanner());
reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE);
reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE);
dr= new DefaultDamagerRepairer(getJavaDocScanner());
reconciler.setDamager(dr, JavaPartitionScanner.JAVA_DOC);
reconciler.setRepairer(dr, JavaPartitionScanner.JAVA_DOC);
dr= new DefaultDamagerRepairer(getMultilineCommentScanner());
reconciler.setDamager(dr, JavaPartitionScanner.JAVA_MULTI_LINE_COMMENT);
reconciler.setRepairer(dr, JavaPartitionScanner.JAVA_MULTI_LINE_COMMENT);
dr= new DefaultDamagerRepairer(getSinglelineCommentScanner());
reconciler.setDamager(dr, JavaPartitionScanner.JAVA_SINGLE_LINE_COMMENT);
reconciler.setRepairer(dr, JavaPartitionScanner.JAVA_SINGLE_LINE_COMMENT);
dr= new DefaultDamagerRepairer(getStringScanner());
reconciler.setDamager(dr, JavaPartitionScanner.JAVA_STRING);
reconciler.setRepairer(dr, JavaPartitionScanner.JAVA_STRING);
return reconciler;
}
/*
* @see SourceViewerConfiguration#getContentAssistant(ISourceViewer)
*/
public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) {
if (getEditor() != null) {
ContentAssistant assistant= new ContentAssistant();
IContentAssistProcessor processor= new JavaCompletionProcessor(getEditor());
assistant.setContentAssistProcessor(processor, 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(processor, JavaPartitionScanner.JAVA_STRING);
assistant.setContentAssistProcessor(processor, JavaPartitionScanner.JAVA_SINGLE_LINE_COMMENT);
assistant.setContentAssistProcessor(new JavaDocCompletionProcessor(getEditor()), JavaPartitionScanner.JAVA_DOC);
ContentAssistPreference.configure(assistant, getPreferenceStore());
assistant.setContextInformationPopupOrientation(ContentAssistant.CONTEXT_INFO_ABOVE);
assistant.setInformationControlCreator(getInformationControlCreator(sourceViewer));
return assistant;
}
return null;
}
/*
* @see SourceViewerConfiguration#getReconciler(ISourceViewer)
*/
public IReconciler getReconciler(ISourceViewer sourceViewer) {
if (getEditor() != null && getEditor().isEditable()) {
JavaReconciler reconciler= new JavaReconciler(getEditor(), new JavaReconcilingStrategy(getEditor()), false);
reconciler.setProgressMonitor(new NullProgressMonitor());
reconciler.setDelay(500);
return reconciler;
}
return null;
}
/*
* @see SourceViewerConfiguration#getAutoIndentStrategy(ISourceViewer, String)
*/
public IAutoIndentStrategy getAutoIndentStrategy(ISourceViewer sourceViewer, String contentType) {
if (JavaPartitionScanner.JAVA_DOC.equals(contentType) ||
JavaPartitionScanner.JAVA_MULTI_LINE_COMMENT.equals(contentType))
return new JavaDocAutoIndentStrategy();
else if (JavaPartitionScanner.JAVA_STRING.equals(contentType))
return new JavaStringAutoIndentStrategy();
return new JavaAutoIndentStrategy();
}
/*
* @see SourceViewerConfiguration#getDoubleClickStrategy(ISourceViewer, String)
*/
public ITextDoubleClickStrategy getDoubleClickStrategy(ISourceViewer sourceViewer, String contentType) {
if (JavaPartitionScanner.JAVA_DOC.equals(contentType) ||
JavaPartitionScanner.JAVA_MULTI_LINE_COMMENT.equals(contentType) ||
JavaPartitionScanner.JAVA_SINGLE_LINE_COMMENT.equals(contentType))
return new DefaultTextDoubleClickStrategy();
else if (JavaPartitionScanner.JAVA_STRING.equals(contentType))
return new JavaStringDoubleClickSelector();
return new JavaDoubleClickSelector();
}
/*
* @see SourceViewerConfiguration#getDefaultPrefix(ISourceViewer, String)
* @since 2.0
*/
public String[] getDefaultPrefixes(ISourceViewer sourceViewer, String contentType) {
return new String[] { "//", "" }; //$NON-NLS-1$ //$NON-NLS-2$
}
/*
* @see SourceViewerConfiguration#getIndentPrefixes(ISourceViewer, String)
*/
public String[] getIndentPrefixes(ISourceViewer sourceViewer, String contentType) {
Vector vector= new Vector();
// prefix[0] is either '\t' or ' ' x tabWidth, depending on useSpaces
Preferences preferences= JavaCore.getPlugin().getPluginPreferences();
int tabWidth= preferences.getInt(JavaCore.FORMATTER_TAB_SIZE);
boolean useSpaces= getPreferenceStore().getBoolean(SPACES_FOR_TABS);
for (int i= 0; i <= tabWidth; i++) {
StringBuffer prefix= new StringBuffer();
if (useSpaces) {
for (int j= 0; j + i < tabWidth; j++)
prefix.append(' ');
if (i != 0)
prefix.append('\t');
} else {
for (int j= 0; j < i; j++)
prefix.append(' ');
if (i != tabWidth)
prefix.append('\t');
}
vector.add(prefix.toString());
}
vector.add(""); //$NON-NLS-1$
return (String[]) vector.toArray(new String[vector.size()]);
}
/*
* @see SourceViewerConfiguration#getTabWidth(ISourceViewer)
*/
public int getTabWidth(ISourceViewer sourceViewer) {
return getPreferenceStore().getInt(PREFERENCE_TAB_WIDTH);
}
/*
* @see SourceViewerConfiguration#getAnnotationHover(ISourceViewer)
*/
public IAnnotationHover getAnnotationHover(ISourceViewer sourceViewer) {
return new JavaAnnotationHover();
}
public int[] getConfiguredTextHoverStateMasks(ISourceViewer sourceViewer, String contentType) {
return new int[] { ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK, SWT.NONE, SWT.CTRL, SWT.SHIFT, SWT.CTRL | SWT.SHIFT, SWT.CTRL | SWT.ALT, SWT.ALT | SWT.SHIFT | SWT.CTRL | SWT.ALT | SWT.SHIFT };
}
/*
* @see SourceViewerConfiguration#getTextHover(ISourceViewer, String, int)
*/
public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType, int stateMask) {
boolean enabled= JavaPlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SHOW_HOVER);
if (!enabled)
return null;
JavaEditorTextHoverDescriptor descriptor= JavaEditorTextHoverDescriptor.getTextHoverDescriptor(stateMask);
if (stateMask != ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK) {
// Ensure that no additional instance is created for default hover
if ((descriptor == null && JavaEditorTextHoverDescriptor.getDefaultHoverId().equals(PreferenceConstants.EDITOR_NO_HOVER_CONFIGURED_ID)) ||(descriptor != null && descriptor.isDefaultTextHoverDescriptor()))
return null; // use default hover instance
}
return new JavaEditorTextHoverProxy(descriptor, getEditor());
}
/*
* @see SourceViewerConfiguration#getTextHover(ISourceViewer, String)
*/
public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType) {
return getTextHover(sourceViewer, contentType, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK);
}
/*
* @see SourceViewerConfiguration#getConfiguredContentTypes(ISourceViewer)
*/
public String[] getConfiguredContentTypes(ISourceViewer sourceViewer) {
return new String[] {
IDocument.DEFAULT_CONTENT_TYPE,
JavaPartitionScanner.JAVA_DOC,
JavaPartitionScanner.JAVA_MULTI_LINE_COMMENT,
JavaPartitionScanner.JAVA_SINGLE_LINE_COMMENT,
JavaPartitionScanner.JAVA_STRING
};
}
/*
* @see SourceViewerConfiguration#getContentFormatter(ISourceViewer)
*/
public IContentFormatter getContentFormatter(ISourceViewer sourceViewer) {
ContentFormatter formatter= new ContentFormatter();
IFormattingStrategy strategy= new JavaFormattingStrategy(sourceViewer);
formatter.setFormattingStrategy(strategy, IDocument.DEFAULT_CONTENT_TYPE);
formatter.enablePartitionAwareFormatting(false);
formatter.setPartitionManagingPositionCategories(fJavaTextTools.getPartitionManagingPositionCategories());
return formatter;
}
/*
* @see SourceViewerConfiguration#getHoverControlCreator(ISourceViewer)
* @since 2.0
*/
public IInformationControlCreator getInformationControlCreator(ISourceViewer sourceViewer) {
return new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell parent) {
return new DefaultInformationControl(parent, SWT.NONE, new HTMLTextPresenter(true));
// return new HoverBrowserControl(parent);
}
};
}
private IInformationControlCreator getInformationPresenterControlCreator(ISourceViewer sourceViewer) {
return new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell parent) {
int shellStyle= SWT.RESIZE;
int style= SWT.V_SCROLL | SWT.H_SCROLL;
return new DefaultInformationControl(parent, shellStyle, style, new HTMLTextPresenter(false));
// return new HoverBrowserControl(parent);
}
};
}
private IInformationControlCreator getOutlinePresenterControlCreator(ISourceViewer sourceViewer) {
return new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell parent) {
int shellStyle= SWT.RESIZE;
int treeStyle= SWT.V_SCROLL | SWT.H_SCROLL;
return new JavaOutlineInformationControl(parent, shellStyle, treeStyle);
}
};
}
/*
* @see SourceViewerConfiguration#getInformationPresenter(ISourceViewer)
* @since 2.0
*/
public IInformationPresenter getInformationPresenter(ISourceViewer sourceViewer) {
InformationPresenter presenter= new InformationPresenter(getInformationPresenterControlCreator(sourceViewer));
IInformationProvider provider= new JavaInformationProvider(getEditor());
presenter.setInformationProvider(provider, IDocument.DEFAULT_CONTENT_TYPE);
presenter.setInformationProvider(provider, JavaPartitionScanner.JAVA_DOC);
presenter.setSizeConstraints(60, 10, true, true);
return presenter;
}
/**
* Returns the outline presenter which will determine and shown
* information requested for the current cursor position.
*
* @param sourceViewer the source viewer to be configured by this configuration
* @return an information presenter
* @since 2.1
*/
public IInformationPresenter getOutlinePresenter(ISourceViewer sourceViewer, boolean doCodeResolve) {
InformationPresenter presenter= new InformationPresenter(getOutlinePresenterControlCreator(sourceViewer));
IInformationProvider provider= new JavaElementProvider(getEditor(), doCodeResolve);
presenter.setInformationProvider(provider, IDocument.DEFAULT_CONTENT_TYPE);
presenter.setInformationProvider(provider, JavaPartitionScanner.JAVA_DOC);
presenter.setSizeConstraints(30, 20, true, false);
return presenter;
}
}
|
26,862 |
Bug 26862 Packages view in Java Browsing updates to navigator selection [browsing]
|
If I open the Navigator in the Java Browsing perspective and select a non-jaa project, the Packages view shows the folders in the project as empty packages. I would have expected the packages view to be empty in this case.
|
resolved fixed
|
8afb181
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-22T14:55:18Z | 2002-11-21T14:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/browsing/PackagesView.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.browsing;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.actions.SelectAllAction;
import org.eclipse.jdt.internal.ui.filters.NonJavaElementFilter;
import org.eclipse.jdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
import org.eclipse.jdt.internal.ui.viewsupport.LibraryFilter;
public class PackagesView extends JavaBrowsingPart {
private SelectAllAction fSelectAllAction;
/**
* Adds filters the viewer of this part.
*/
protected void addFilters() {
super.addFilters();
getViewer().addFilter(new NonJavaElementFilter());
getViewer().addFilter(new LibraryFilter());
}
protected ILabelProvider createLabelProvider() {
return new AppearanceAwareLabelProvider(
AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS | JavaElementLabels.P_COMPRESSED,
AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS | JavaElementImageProvider.SMALL_ICONS,
AppearanceAwareLabelProvider.getDecorators(true, null)
);
}
/**
* Returns the context ID for the Help system
*
* @return the string used as ID for the Help context
*/
protected String getHelpContextId() {
return IJavaHelpContextIds.PACKAGES_BROWSING_VIEW;
}
/**
* Answers if the given <code>element</code> is a valid
* input for this part.
*
* @param element the object to test
* @return <true> if the given element is a valid input
*/
protected boolean isValidInput(Object element) {
return element instanceof IJavaProject
|| (element instanceof IPackageFragmentRoot && ((IJavaElement)element).getElementName() != IPackageFragmentRoot.DEFAULT_PACKAGEROOT_PATH);
}
/*
* Gets suitable input.
*/
/**
* Answers if the given <code>element</code> is a valid
* element for this part.
*
* @param element the object to test
* @return <true> if the given element is a valid element
*/
protected boolean isValidElement(Object element) {
if (element instanceof IPackageFragment) {
IJavaElement parent= ((IPackageFragment)element).getParent();
if (parent != null)
return super.isValidElement(parent) || super.isValidElement(parent.getJavaProject());
}
return false;
}
/**
* Finds the element which has to be selected in this part.
*
* @param je the Java element which has the focus
*/
protected IJavaElement findElementToSelect(IJavaElement je) {
if (je == null)
return null;
switch (je.getElementType()) {
case IJavaElement.PACKAGE_FRAGMENT:
return je;
case IJavaElement.COMPILATION_UNIT:
return ((ICompilationUnit)je).getParent();
case IJavaElement.CLASS_FILE:
return ((IClassFile)je).getParent();
case IJavaElement.TYPE:
return ((IType)je).getPackageFragment();
default:
return findElementToSelect(je.getParent());
}
}
protected void createActions() {
super.createActions();
fSelectAllAction= new SelectAllAction((TableViewer)getViewer());
}
protected void fillActionBars(IActionBars actionBars) {
super.fillActionBars(actionBars);
// Add selectAll action handlers.
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.SELECT_ALL, fSelectAllAction);
}
}
|
25,370 |
Bug 25370 Linked Mode: Want to define where to focus
|
20021022 I added a new feature that starts the linked mode on all usages of a variable. e.g. int i; i= 1; i++; would link all 3 occurrences of i, so when edited, all 3 references are changed simultanously. Problem is that the liked mode does not allow me to set the focus (where to edit) to e.g. the 'i' in 'i++'. The linked mode only allows to edit the top most linked position ('int i'). The feature can be invoked on any reference. Jumping to the top not so ideal.
|
resolved fixed
|
5f2e5d3
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-22T16:42:18Z | 2002-10-25T10:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/LinkedNamesAssistProposal.java
|
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.ArrayList;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.contentassist.ICompletionProposalExtension2;
import org.eclipse.jface.text.contentassist.IContextInformation;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.IBinding;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.text.java.IJavaCompletionProposal;
import org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager;
import org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI;
/**
* A template proposal.
*/
public class LinkedNamesAssistProposal implements IJavaCompletionProposal, ICompletionProposalExtension2 {
private SimpleName fNode;
private IRegion fSelectedRegion; // initialized by apply()
private static class LinkedNodeFinder extends ASTVisitor {
private IBinding fBinding;
private ArrayList fResult;
public LinkedNodeFinder(IBinding binding, ArrayList result) {
fBinding= binding;
fResult= result;
}
public boolean visit(MethodDeclaration node) {
if (node.isConstructor() && fBinding.getKind() == IBinding.TYPE) {
ASTNode typeNode= node.getParent();
if (typeNode instanceof TypeDeclaration) {
if (fBinding == ((TypeDeclaration) typeNode).resolveBinding()) {
fResult.add(node.getName());
}
}
}
return true;
}
public boolean visit(SimpleName node) {
if (fBinding == node.resolveBinding()) {
fResult.add(node);
}
return false;
}
}
public LinkedNamesAssistProposal(SimpleName node) {
fNode= node;
}
/* (non-Javadoc)
* @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#apply(org.eclipse.jface.text.ITextViewer, char, int, int)
*/
public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) {
try {
ArrayList sameNodes= new ArrayList();
LinkedNodeFinder finder= new LinkedNodeFinder(fNode.resolveBinding(), sameNodes);
ASTResolving.findParentCompilationUnit(fNode).accept(finder);
IDocument document= viewer.getDocument();
LinkedPositionManager manager= new LinkedPositionManager(document);
for (int i= 0; i < sameNodes.size(); i++) {
ASTNode elem= (ASTNode) sameNodes.get(i);
manager.addPosition(elem.getStartPosition(), elem.getLength());
}
LinkedPositionUI editor= new LinkedPositionUI(viewer, manager);
editor.setFinalCaretOffset(offset);
editor.enter();
fSelectedRegion= editor.getSelectedRegion();
} catch (BadLocationException e) {
}
}
/*
* @see ICompletionProposal#apply(IDocument)
*/
public void apply(IDocument document) {
// can't do anything
}
/*
* @see ICompletionProposal#getSelection(IDocument)
*/
public Point getSelection(IDocument document) {
return new Point(fSelectedRegion.getOffset(), fSelectedRegion.getLength());
}
/*
* @see ICompletionProposal#getAdditionalProposalInfo()
*/
public String getAdditionalProposalInfo() {
return "Linked rename";
}
/*
* @see ICompletionProposal#getDisplayString()
*/
public String getDisplayString() {
return "Rename";
}
/*
* @see ICompletionProposal#getImage()
*/
public Image getImage() {
return JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
}
/*
* @see ICompletionProposal#getContextInformation()
*/
public IContextInformation getContextInformation() {
return null;
}
/*
* @see IJavaCompletionProposal#getRelevance()
*/
public int getRelevance() {
return 1;
}
/* (non-Javadoc)
* @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#selected(org.eclipse.jface.text.ITextViewer, boolean)
*/
public void selected(ITextViewer textViewer, boolean smartToggle) {
}
/* (non-Javadoc)
* @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#unselected(org.eclipse.jface.text.ITextViewer)
*/
public void unselected(ITextViewer textViewer) {
}
/* (non-Javadoc)
* @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#validate(org.eclipse.jface.text.IDocument, int, org.eclipse.jface.text.DocumentEvent)
*/
public boolean validate(IDocument document, int offset, DocumentEvent event) {
return false;
}
}
|
25,370 |
Bug 25370 Linked Mode: Want to define where to focus
|
20021022 I added a new feature that starts the linked mode on all usages of a variable. e.g. int i; i= 1; i++; would link all 3 occurrences of i, so when edited, all 3 references are changed simultanously. Problem is that the liked mode does not allow me to set the focus (where to edit) to e.g. the 'i' in 'i++'. The linked mode only allows to edit the top most linked position ('int i'). The feature can be invoked on any reference. Jumping to the top not so ideal.
|
resolved fixed
|
5f2e5d3
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-22T16:42:18Z | 2002-10-25T10:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaCompletionProposal.java
|
/**********************************************************************
Copyright (c) 2000, 2002 IBM Corp. and others.
All rights reserved. This program and the accompanying materials
are made available under the terms of the Common Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/cpl-v10.html
Contributors:
IBM Corporation - Initial implementation
**********************************************************************/
package org.eclipse.jdt.internal.ui.text.java;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.ITextViewerExtension2;
import org.eclipse.jface.text.contentassist.ICompletionProposalExtension;
import org.eclipse.jface.text.contentassist.ICompletionProposalExtension2;
import org.eclipse.jface.text.contentassist.IContextInformation;
import org.eclipse.jface.util.Assert;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager;
import org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI;
import org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.ExitFlags;
public class JavaCompletionProposal implements IJavaCompletionProposal, ICompletionProposalExtension, ICompletionProposalExtension2 {
private String fDisplayString;
private String fReplacementString;
private int fReplacementOffset;
private int fReplacementLength;
private int fCursorPosition;
private Image fImage;
private IContextInformation fContextInformation;
private int fContextInformationPosition;
private ProposalInfo fProposalInfo;
private char[] fTriggerCharacters;
protected boolean fToggleEating;
protected ITextViewer fTextViewer;
private int fRelevance;
private StyleRange fRememberedStyleRange;
/**
* Creates a new completion proposal. All fields are initialized based on the provided information.
*
* @param replacementString the actual string to be inserted into the document
* @param replacementOffset the offset of the text to be replaced
* @param replacementLength the length of the text to be replaced
* @param image the image to display for this proposal
* @param displayString the string to be displayed for the proposal
* If set to <code>null</code>, the replacement string will be taken as display string.
*/
public JavaCompletionProposal(String replacementString, int replacementOffset, int replacementLength, Image image, String displayString, int relevance) {
this(replacementString, replacementOffset, replacementLength, image, displayString, relevance, null);
}
/**
* Creates a new completion proposal. All fields are initialized based on the provided information.
*
* @param replacementString the actual string to be inserted into the document
* @param replacementOffset the offset of the text to be replaced
* @param replacementLength the length of the text to be replaced
* @param image the image to display for this proposal
* @param displayString the string to be displayed for the proposal
* @param viewer the text viewer for which this proposal is computed, may be <code>null</code>
* If set to <code>null</code>, the replacement string will be taken as display string.
*/
public JavaCompletionProposal(String replacementString, int replacementOffset, int replacementLength, Image image, String displayString, int relevance, ITextViewer viewer) {
Assert.isNotNull(replacementString);
Assert.isTrue(replacementOffset >= 0);
Assert.isTrue(replacementLength >= 0);
fReplacementString= replacementString;
fReplacementOffset= replacementOffset;
fReplacementLength= replacementLength;
fImage= image;
fDisplayString= displayString != null ? displayString : replacementString;
fRelevance= relevance;
fTextViewer= viewer;
fCursorPosition= replacementString.length();
fContextInformation= null;
fContextInformationPosition= -1;
fTriggerCharacters= null;
fProposalInfo= null;
}
/**
* Sets the context information.
* @param contentInformation The context information associated with this proposal
*/
public void setContextInformation(IContextInformation contextInformation) {
fContextInformation= contextInformation;
fContextInformationPosition= (fContextInformation != null ? fCursorPosition : -1);
}
/**
* Sets the trigger characters.
* @param triggerCharacters The set of characters which can trigger the application of this completion proposal
*/
public void setTriggerCharacters(char[] triggerCharacters) {
fTriggerCharacters= triggerCharacters;
}
/**
* Sets the proposal info.
* @param additionalProposalInfo The additional information associated with this proposal or <code>null</code>
*/
public void setProposalInfo(ProposalInfo proposalInfo) {
fProposalInfo= proposalInfo;
}
/**
* Sets the cursor position relative to the insertion offset. By default this is the length of the completion string
* (Cursor positioned after the completion)
* @param cursorPosition The cursorPosition to set
*/
public void setCursorPosition(int cursorPosition) {
Assert.isTrue(cursorPosition >= 0);
fCursorPosition= cursorPosition;
fContextInformationPosition= (fContextInformation != null ? fCursorPosition : -1);
}
/*
* @see ICompletionProposalExtension#apply(IDocument, char, int)
*/
public void apply(IDocument document, char trigger, int offset) {
try {
// patch replacement length
int delta= offset - (fReplacementOffset + fReplacementLength);
if (delta > 0)
fReplacementLength += delta;
String string;
if (trigger == (char) 0) {
string= fReplacementString;
} else {
StringBuffer buffer= new StringBuffer(fReplacementString);
// fix for PR #5533. Assumes that no eating takes place.
if ((fCursorPosition > 0 && fCursorPosition <= buffer.length() && buffer.charAt(fCursorPosition - 1) != trigger)) {
buffer.insert(fCursorPosition, trigger);
++fCursorPosition;
}
string= buffer.toString();
}
replace(document, fReplacementOffset, fReplacementLength, string);
if (fTextViewer != null && string != null) {
int index= string.indexOf("()"); //$NON-NLS-1$
if (index != -1) {
IPreferenceStore preferenceStore= JavaPlugin.getDefault().getPreferenceStore();
if (preferenceStore.getBoolean(PreferenceConstants.EDITOR_CLOSE_BRACKETS)) {
int newOffset= fReplacementOffset + index;
LinkedPositionManager manager= new LinkedPositionManager(document);
manager.addPosition(newOffset + 1, 0);
LinkedPositionUI editor= new LinkedPositionUI(fTextViewer, manager);
editor.setExitPolicy(new ExitPolicy(')'));
editor.setFinalCaretOffset(newOffset + 2);
editor.enter();
}
}
}
} catch (BadLocationException x) {
// ignore
}
}
private static class ExitPolicy implements LinkedPositionUI.ExitPolicy {
final char fExitCharacter;
public ExitPolicy(char exitCharacter) {
fExitCharacter= exitCharacter;
}
/*
* @see org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.ExitPolicy#doExit(org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager, org.eclipse.swt.events.VerifyEvent, int, int)
*/
public ExitFlags doExit(LinkedPositionManager manager, VerifyEvent event, int offset, int length) {
if (event.character == fExitCharacter) {
if (manager.anyPositionIncludes(offset, length))
return new ExitFlags(LinkedPositionUI.COMMIT| LinkedPositionUI.UPDATE_CARET, false);
else
return new ExitFlags(LinkedPositionUI.COMMIT, true);
}
switch (event.character) {
case '\b':
if (manager.getFirstPosition().length == 0)
return new ExitFlags(0, true);
else
return null;
case '\n':
case '\r':
return new ExitFlags(LinkedPositionUI.COMMIT, true);
default:
return null;
}
}
}
// #6410 - File unchanged but dirtied by code assist
private void replace(IDocument document, int offset, int length, String string) throws BadLocationException {
if (!document.get(offset, length).equals(string))
document.replace(offset, length, string);
}
/*
* @see ICompletionProposal#apply
*/
public void apply(IDocument document) {
apply(document, (char) 0, fReplacementOffset + fReplacementLength);
}
/*
* @see ICompletionProposal#getSelection
*/
public Point getSelection(IDocument document) {
return new Point(fReplacementOffset + fCursorPosition, 0);
}
/*
* @see ICompletionProposal#getContextInformation()
*/
public IContextInformation getContextInformation() {
return fContextInformation;
}
/*
* @see ICompletionProposal#getImage()
*/
public Image getImage() {
return fImage;
}
/*
* @see ICompletionProposal#getDisplayString()
*/
public String getDisplayString() {
return fDisplayString;
}
/*
* @see ICompletionProposal#getAdditionalProposalInfo()
*/
public String getAdditionalProposalInfo() {
if (fProposalInfo != null) {
return fProposalInfo.getInfo();
}
return null;
}
/*
* @see ICompletionProposalExtension#getTriggerCharacters()
*/
public char[] getTriggerCharacters() {
return fTriggerCharacters;
}
/*
* @see ICompletionProposalExtension#getContextInformationPosition()
*/
public int getContextInformationPosition() {
return fReplacementOffset + fContextInformationPosition;
}
/**
* Gets the replacement offset.
* @return Returns a int
*/
public int getReplacementOffset() {
return fReplacementOffset;
}
/**
* Sets the replacement offset.
* @param replacementOffset The replacement offset to set
*/
public void setReplacementOffset(int replacementOffset) {
Assert.isTrue(replacementOffset >= 0);
fReplacementOffset= replacementOffset;
}
/**
* Gets the replacement length.
* @return Returns a int
*/
public int getReplacementLength() {
return fReplacementLength;
}
/**
* Sets the replacement length.
* @param replacementLength The replacementLength to set
*/
public void setReplacementLength(int replacementLength) {
Assert.isTrue(replacementLength >= 0);
fReplacementLength= replacementLength;
}
/**
* Gets the replacement string.
* @return Returns a String
*/
public String getReplacementString() {
return fReplacementString;
}
/**
* Sets the replacement string.
* @param replacementString The replacement string to set
*/
public void setReplacementString(String replacementString) {
fReplacementString= replacementString;
}
/**
* Sets the image.
* @param image The image to set
*/
public void setImage(Image image) {
fImage= image;
}
/*
* @see ICompletionProposalExtension#isValidFor(IDocument, int)
*/
public boolean isValidFor(IDocument document, int offset) {
return validate(document, offset, null);
}
/*
* @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#validate(org.eclipse.jface.text.IDocument, int, org.eclipse.jface.text.DocumentEvent)
*/
public boolean validate(IDocument document, int offset, DocumentEvent event) {
if (offset < fReplacementOffset)
return false;
/*
* See http://dev.eclipse.org/bugs/show_bug.cgi?id=17667
String word= fReplacementString;
*/
boolean validated= startsWith(document, offset, fDisplayString);
if (validated && event != null) {
// adapt replacement range to document change
int delta= (event.fText == null ? 0 : event.fText.length()) - event.fLength;
fReplacementLength += delta;
}
return validated;
}
/**
* Gets the proposal's relevance.
* @return Returns a int
*/
public int getRelevance() {
return fRelevance;
}
/**
* Sets the proposal's relevance.
* @param relevance The relevance to set
*/
public void setRelevance(int relevance) {
fRelevance= relevance;
}
/**
* Returns <code>true</code> if a words starts with the code completion prefix in the document,
* <code>false</code> otherwise.
*/
protected boolean startsWith(IDocument document, int offset, String word) {
int wordLength= word == null ? 0 : word.length();
if (offset > fReplacementOffset + wordLength)
return false;
try {
int length= offset - fReplacementOffset;
String start= document.get(fReplacementOffset, length);
return word.substring(0, length).equalsIgnoreCase(start);
} catch (BadLocationException x) {
}
return false;
}
private static boolean insertCompletion() {
IPreferenceStore preference= JavaPlugin.getDefault().getPreferenceStore();
return preference.getBoolean(PreferenceConstants.CODEASSIST_INSERT_COMPLETION);
}
/*
* @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension1#apply(org.eclipse.jface.text.ITextViewer, char, int, int)
*/
public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) {
IDocument document= viewer.getDocument();
fToggleEating= (stateMask & SWT.CTRL) != 0;
if (insertCompletion() ^ fToggleEating)
fReplacementLength= offset - fReplacementOffset;
apply(document, trigger, offset);
fToggleEating= false;
}
private static Color getForegroundColor(StyledText text) {
IPreferenceStore preference= JavaPlugin.getDefault().getPreferenceStore();
RGB rgb= PreferenceConverter.getColor(preference, PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND);
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
return textTools.getColorManager().getColor(rgb);
}
private static Color getBackgroundColor(StyledText text) {
IPreferenceStore preference= JavaPlugin.getDefault().getPreferenceStore();
RGB rgb= PreferenceConverter.getColor(preference, PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND);
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
return textTools.getColorManager().getColor(rgb);
}
private void repairPresentation(ITextViewer viewer) {
if (fRememberedStyleRange != null) {
if (viewer instanceof ITextViewerExtension2) {
// attempts to reduce the redraw area
ITextViewerExtension2 viewer2= (ITextViewerExtension2) viewer;
viewer2.invalidateTextPresentation(fRememberedStyleRange.start + viewer.getVisibleRegion().getOffset(), fRememberedStyleRange.length);
} else
viewer.invalidateTextPresentation();
}
}
private void updateStyle(ITextViewer viewer) {
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
IRegion visibleRegion= viewer.getVisibleRegion();
int caretOffset= text.getCaretOffset() + visibleRegion.getOffset();
if (caretOffset >= fReplacementOffset + fReplacementLength) {
repairPresentation(viewer);
return;
}
int offset= caretOffset - visibleRegion.getOffset();
int length= fReplacementOffset + fReplacementLength - caretOffset;
Color foreground= getForegroundColor(text);
Color background= getBackgroundColor(text);
repairPresentation(viewer);
fRememberedStyleRange= new StyleRange(offset, length, foreground, background);
text.setStyleRange(fRememberedStyleRange);
}
/*
* @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#selected(ITextViewer, boolean)
*/
public void selected(ITextViewer viewer, boolean smartToggle) {
if (!insertCompletion() ^ smartToggle)
updateStyle(viewer);
else {
repairPresentation(viewer);
fRememberedStyleRange= null;
}
}
/*
* @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#unselected(ITextViewer)
*/
public void unselected(ITextViewer viewer) {
repairPresentation(viewer);
fRememberedStyleRange= null;
}
}
|
25,370 |
Bug 25370 Linked Mode: Want to define where to focus
|
20021022 I added a new feature that starts the linked mode on all usages of a variable. e.g. int i; i= 1; i++; would link all 3 occurrences of i, so when edited, all 3 references are changed simultanously. Problem is that the liked mode does not allow me to set the focus (where to edit) to e.g. the 'i' in 'i++'. The linked mode only allows to edit the top most linked position ('int i'). The feature can be invoked on any reference. Jumping to the top not so ideal.
|
resolved fixed
|
5f2e5d3
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-22T16:42:18Z | 2002-10-25T10:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/link/LinkedPositionManager.java
|
/**********************************************************************
Copyright (c) 2000, 2002 IBM Corp. and others.
All rights reserved. This program and the accompanying materials
are made available under the terms of the Common Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/cpl-v10.html
Contributors:
IBM Corporation - Initial implementation
**********************************************************************/
package org.eclipse.jdt.internal.ui.text.link;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.BadPositionCategoryException;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentExtension;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.jface.text.IPositionUpdater;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.TypedPosition;
import org.eclipse.jface.util.Assert;
import org.eclipse.jdt.internal.ui.JavaPlugin;
/**
* This class manages linked positions in a document. Positions are linked
* by type names. If positions have the same type name, they are considered
* as <em>linked</em>.
*
* The manager remains active on a document until any of the following actions
* occurs:
*
* <ul>
* <li>A document change is performed which would invalidate any of the
* above constraints.</li>
*
* <li>The method <code>uninstall()</code> is called.</li>
*
* <li>Another instance of <code>LinkedPositionManager</code> tries to
* gain control of the same document.
* </ul>
*/
public class LinkedPositionManager implements IDocumentListener, IPositionUpdater {
private static class PositionComparator implements Comparator {
/*
* @see Comparator#compare(Object, Object)
*/
public int compare(Object object0, Object object1) {
Position position0= (Position) object0;
Position position1= (Position) object1;
return position0.getOffset() - position1.getOffset();
}
}
private class Replace implements IDocumentExtension.IReplace {
private Position fReplacePosition;
private int fReplaceDeltaOffset;
private int fReplaceLength;
private String fReplaceText;
public Replace(Position position, int deltaOffset, int length, String text) {
fReplacePosition= position;
fReplaceDeltaOffset= deltaOffset;
fReplaceLength= length;
fReplaceText= text;
}
public void perform(IDocument document, IDocumentListener owner) {
document.removeDocumentListener(owner);
try {
document.replace(fReplacePosition.getOffset() + fReplaceDeltaOffset, fReplaceLength, fReplaceText);
} catch (BadLocationException e) {
JavaPlugin.log(e);
// TBD
}
document.addDocumentListener(owner);
}
}
private static final String LINKED_POSITION= "LinkedPositionManager.linked.position"; //$NON-NLS-1$
private static final Comparator fgPositionComparator= new PositionComparator();
private static final Map fgActiveManagers= new HashMap();
private IDocument fDocument;
private LinkedPositionListener fListener;
/**
* Creates a <code>LinkedPositionManager</code> for a <code>IDocument</code>.
*
* @param document the document to use with linked positions.
*/
public LinkedPositionManager(IDocument document) {
Assert.isNotNull(document);
fDocument= document;
install();
}
/**
* Sets a listener to notify changes of current linked position.
*/
public void setLinkedPositionListener(LinkedPositionListener listener) {
fListener= listener;
}
/**
* Adds a linked position to the manager.
* There are the following constraints for linked positions:
*
* <ul>
* <li>Any two positions have spacing of at least one character.
* This implies that two positions must not overlap.</li>
*
* <li>The string at any position must not contain line delimiters.</li>
* </ul>
*
* @param offset the offset of the position.
* @param length the length of the position.
*/
public void addPosition(int offset, int length) throws BadLocationException {
Position[] positions= getPositions(fDocument);
if (positions != null) {
for (int i = 0; i < positions.length; i++)
if (collides(positions[i], offset, length))
throw new BadLocationException(LinkedPositionMessages.getString(("LinkedPositionManager.error.position.collision"))); //$NON-NLS-1$
}
String type= fDocument.get(offset, length);
if (containsLineDelimiters(type))
throw new BadLocationException(LinkedPositionMessages.getString(("LinkedPositionManager.error.contains.line.delimiters"))); //$NON-NLS-1$
try {
fDocument.addPosition(LINKED_POSITION, new TypedPosition(offset, length, type));
} catch (BadPositionCategoryException e) {
JavaPlugin.log(e);
Assert.isTrue(false);
}
}
/**
* Tests if a manager is already active for a document.
*/
public static boolean hasActiveManager(IDocument document) {
return fgActiveManagers.get(document) != null;
}
private void install() {
LinkedPositionManager manager= (LinkedPositionManager) fgActiveManagers.get(fDocument);
if (manager != null)
manager.leave(true);
fgActiveManagers.put(fDocument, this);
fDocument.addPositionCategory(LINKED_POSITION);
fDocument.addPositionUpdater(this);
fDocument.addDocumentListener(this);
}
/**
* Leaves the linked mode. If unsuccessful, the linked positions
* are restored to the values at the time they were added.
*/
public void uninstall(boolean success) {
fDocument.removeDocumentListener(this);
try {
Position[] positions= getPositions(fDocument);
if ((!success) && (positions != null)) {
// restore
for (int i= 0; i != positions.length; i++) {
TypedPosition position= (TypedPosition) positions[i];
fDocument.replace(position.getOffset(), position.getLength(), position.getType());
}
}
fDocument.removePositionCategory(LINKED_POSITION);
} catch (BadLocationException e) {
JavaPlugin.log(e);
Assert.isTrue(false);
} catch (BadPositionCategoryException e) {
JavaPlugin.log(e);
Assert.isTrue(false);
} finally {
fDocument.removePositionUpdater(this);
fgActiveManagers.remove(fDocument);
}
}
/**
* Returns the first linked position.
*
* @return returns <code>null</code> if no linked position exist.
*/
public Position getFirstPosition() {
return getNextPosition(-1);
}
/**
* Returns the next linked position with an offset greater than <code>offset</code>.
* If another position with the same type and offset lower than <code>offset</code>
* exists, the position is skipped.
*
* @return returns <code>null</code> if no linked position exist.
*/
public Position getNextPosition(int offset) {
Position[] positions= getPositions(fDocument);
return findNextPosition(positions, offset);
}
private static Position findNextPosition(Position[] positions, int offset) {
// skip already visited types
for (int i= 0; i != positions.length; i++) {
if (positions[i].getOffset() > offset) {
String type= ((TypedPosition) positions[i]).getType();
int j;
for (j = 0; j != i; j++)
if (((TypedPosition) positions[j]).getType().equals(type))
break;
if (j == i)
return positions[i];
}
}
return null;
}
/**
* Returns the position with the greatest offset smaller than <code>offset</code>.
*
* @return returns <code>null</code> if no linked position exist.
*/
public Position getPreviousPosition(int offset) {
Position[] positions= getPositions(fDocument);
if (positions == null)
return null;
Position lastPosition= null;
Position position= getFirstPosition();
while ((position != null) && (position.getOffset() < offset)) {
lastPosition= position;
position= findNextPosition(positions, position.getOffset());
}
return lastPosition;
}
private static Position[] getPositions(IDocument document) {
try {
Position[] positions= document.getPositions(LINKED_POSITION);
Arrays.sort(positions, fgPositionComparator);
return positions;
} catch (BadPositionCategoryException e) {
JavaPlugin.log(e);
Assert.isTrue(false);
}
return null;
}
public static boolean includes(Position position, int offset, int length) {
return
(offset >= position.getOffset()) &&
(offset + length <= position.getOffset() + position.getLength());
}
public static boolean excludes(Position position, int offset, int length) {
return
(offset + length <= position.getOffset()) ||
(position.getOffset() + position.getLength() <= offset);
}
/*
* Collides if spacing if positions intersect each other or are adjacent.
*/
private static boolean collides(Position position, int offset, int length) {
return
(offset <= position.getOffset() + position.getLength()) &&
(position.getOffset() <= offset + length);
}
private void leave(boolean success) {
uninstall(success);
if (fListener != null)
fListener.exit(success);
}
/*
* @see IDocumentListener#documentAboutToBeChanged(DocumentEvent)
*/
public void documentAboutToBeChanged(DocumentEvent event) {
IDocument document= event.getDocument();
Position[] positions= getPositions(document);
Position position= findCurrentEditablePosition(positions, event.getOffset());
// modification outside editable position
if (position == null) {
position= findCurrentPosition(positions, event.getOffset());
// modification outside any position
if (position == null) {
// check for destruction of constraints (spacing of at least 1)
if ((event.getText().length() == 0) &&
(findCurrentPosition(positions, event.getOffset()) != null) &&
(findCurrentPosition(positions, event.getOffset() + event.getLength()) != null))
{
leave(true);
}
// modification intersects non-editable position
} else {
leave(true);
}
// modification intersects editable position
} else {
// modificaction inside editable position
if (includes(position, event.getOffset(), event.getLength())) {
if (containsLineDelimiters(event.getText()))
leave(true);
// modificaction exceeds editable position
} else {
leave(true);
}
}
}
/*
* @see IDocumentListener#documentChanged(DocumentEvent)
*/
public void documentChanged(DocumentEvent event) {
IDocument document= event.getDocument();
Position[] positions= getPositions(document);
TypedPosition currentPosition= (TypedPosition) findCurrentEditablePosition(positions, event.getOffset());
// ignore document changes (assume it won't invalidate constraints)
if (currentPosition == null)
return;
int deltaOffset= event.getOffset() - currentPosition.getOffset();
if (fListener != null)
fListener.setCurrentPosition(currentPosition, deltaOffset + event.getText().length());
for (int i= 0; i != positions.length; i++) {
TypedPosition p= (TypedPosition) positions[i];
if (p.getType().equals(currentPosition.getType()) && !p.equals(currentPosition)) {
Replace replace= new Replace(p, deltaOffset, event.getLength(), event.getText());
((IDocumentExtension) document).registerPostNotificationReplace(this, replace);
}
}
}
/*
* @see IPositionUpdater#update(DocumentEvent)
*/
public void update(DocumentEvent event) {
int deltaLength= event.getText().length() - event.getLength();
Position[] positions= getPositions(event.getDocument());
TypedPosition currentPosition= (TypedPosition) findCurrentPosition(positions, event.getOffset());
// document change outside positions
if (currentPosition == null) {
for (int i= 0; i != positions.length; i++) {
TypedPosition position= (TypedPosition) positions[i];
int offset= position.getOffset();
if (offset >= event.getOffset())
position.setOffset(offset + deltaLength);
}
// document change within a position
} else {
int length= currentPosition.getLength();
for (int i= 0; i != positions.length; i++) {
TypedPosition position= (TypedPosition) positions[i];
int offset= position.getOffset();
if (position.equals(currentPosition)) {
position.setLength(length + deltaLength);
} else if (offset > currentPosition.getOffset()) {
position.setOffset(offset + deltaLength);
}
}
}
}
private static Position findCurrentPosition(Position[] positions, int offset) {
for (int i= 0; i != positions.length; i++)
if (includes(positions[i], offset, 0))
return positions[i];
return null;
}
private static Position findCurrentEditablePosition(Position[] positions, int offset) {
Position position= positions[0];
while ((position != null) && !includes(position, offset, 0))
position= findNextPosition(positions, position.getOffset());
return position;
}
private boolean containsLineDelimiters(String string) {
String[] delimiters= fDocument.getLegalLineDelimiters();
for (int i= 0; i != delimiters.length; i++)
if (string.indexOf(delimiters[i]) != -1)
return true;
return false;
}
/**
* Test if ok to modify through UI.
*/
public boolean anyPositionIncludes(int offset, int length) {
Position[] positions= getPositions(fDocument);
Position position= findCurrentEditablePosition(positions, offset);
if (position == null)
return false;
return includes(position, offset, length);
}
}
|
25,370 |
Bug 25370 Linked Mode: Want to define where to focus
|
20021022 I added a new feature that starts the linked mode on all usages of a variable. e.g. int i; i= 1; i++; would link all 3 occurrences of i, so when edited, all 3 references are changed simultanously. Problem is that the liked mode does not allow me to set the focus (where to edit) to e.g. the 'i' in 'i++'. The linked mode only allows to edit the top most linked position ('int i'). The feature can be invoked on any reference. Jumping to the top not so ideal.
|
resolved fixed
|
5f2e5d3
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-22T16:42:18Z | 2002-10-25T10:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/link/LinkedPositionUI.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.text.link;
import java.lang.reflect.InvocationTargetException;
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.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.BadPositionCategoryException;
import org.eclipse.jface.text.DefaultPositionUpdater;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IPositionUpdater;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextInputListener;
import org.eclipse.jface.text.ITextListener;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.ITextViewerExtension;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextEvent;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
/**
* A user interface for <code>LinkedPositionManager</code>, using <code>ITextViewer</code>.
*/
public class LinkedPositionUI implements LinkedPositionListener,
ITextInputListener, ITextListener, ModifyListener, VerifyListener, VerifyKeyListener, PaintListener, IPropertyChangeListener {
/**
* A listener for notification when the user cancelled the edit operation.
*/
public interface ExitListener {
void exit(boolean accept);
}
public static class ExitFlags {
public int flags;
public boolean doit;
public ExitFlags(int flags, boolean doit) {
this.flags= flags;
this.doit= doit;
}
}
public interface ExitPolicy {
ExitFlags doExit(LinkedPositionManager manager, VerifyEvent event, int offset, int length);
}
// leave flags
private static final int UNINSTALL= 1; // uninstall linked position manager
public static final int COMMIT= 2; // commit changes
private static final int DOCUMENT_CHANGED= 4; // document has changed
public static final int UPDATE_CARET= 8; // update caret
private static final String CARET_POSITION= "LinkedPositionUI.caret.position"; //$NON-NLS-1$
private static final IPositionUpdater fgUpdater= new DefaultPositionUpdater(CARET_POSITION);
private static final IPreferenceStore fgStore= JavaPlugin.getDefault().getPreferenceStore();
private final ITextViewer fViewer;
private final LinkedPositionManager fManager;
private Color fFrameColor;
private int fFinalCaretOffset= -1; // no final caret offset
private Position fFramePosition;
private int fCaretOffset;
private ExitPolicy fExitPolicy;
private ExitListener fExitListener;
private boolean fNeedRedraw;
/**
* Creates a user interface for <code>LinkedPositionManager</code>.
*
* @param viewer the text viewer.
* @param manager the <code>LinkedPositionManager</code> managing a <code>IDocument</code> of the <code>ITextViewer</code>.
*/
public LinkedPositionUI(ITextViewer viewer, LinkedPositionManager manager) {
Assert.isNotNull(viewer);
Assert.isNotNull(manager);
fViewer= viewer;
fManager= manager;
fManager.setLinkedPositionListener(this);
initializeHighlightColor(viewer);
}
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(PreferenceConstants.EDITOR_LINKED_POSITION_COLOR)) {
initializeHighlightColor(fViewer);
redrawRegion();
}
}
private void initializeHighlightColor(ITextViewer viewer) {
if (fFrameColor != null)
fFrameColor.dispose();
StyledText text= viewer.getTextWidget();
if (text != null) {
Display display= text.getDisplay();
fFrameColor= createColor(fgStore, PreferenceConstants.EDITOR_LINKED_POSITION_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;
}
/**
* Sets the final position of the caret when the linked mode is exited
* successfully by leaving the last linked position using TAB.
*/
public void setFinalCaretOffset(int offset) {
fFinalCaretOffset= offset;
}
/**
* Sets a <code>CancelListener</code> which is notified if the linked mode
* is exited unsuccessfully by hitting ESC.
*/
public void setCancelListener(ExitListener listener) {
fExitListener= listener;
}
/**
* Sets an <code>ExitPolicy</code> which decides when and how
* the linked mode is exited.
*/
public void setExitPolicy(ExitPolicy policy) {
fExitPolicy= policy;
}
/*
* @see LinkedPositionManager.LinkedPositionListener#setCurrentPositions(Position, int)
*/
public void setCurrentPosition(Position position, int caretOffset) {
if (!fFramePosition.equals(position)) {
fNeedRedraw= true;
fFramePosition= position;
}
fCaretOffset= caretOffset;
}
/**
* Enters the linked mode. The linked mode can be left by calling
* <code>exit</code>.
*
* @see #exit(boolean)
*/
public void enter() {
// track final caret
IDocument document= fViewer.getDocument();
document.addPositionCategory(CARET_POSITION);
document.addPositionUpdater(fgUpdater);
try {
if (fFinalCaretOffset != -1)
document.addPosition(CARET_POSITION, new Position(fFinalCaretOffset));
} catch (BadLocationException e) {
handleException(fViewer.getTextWidget().getShell(), e);
} catch (BadPositionCategoryException e) {
JavaPlugin.log(e);
Assert.isTrue(false);
}
fViewer.addTextInputListener(this);
fViewer.addTextListener(this);
ITextViewerExtension extension= (ITextViewerExtension) fViewer;
extension.prependVerifyKeyListener(this);
StyledText text= fViewer.getTextWidget();
text.addVerifyListener(this);
text.addModifyListener(this);
text.addPaintListener(this);
text.showSelection();
fFramePosition= fManager.getFirstPosition();
if (fFramePosition == null)
leave(UNINSTALL | COMMIT | UPDATE_CARET);
fgStore.addPropertyChangeListener(this);
}
/*
* @see LinkedPositionManager.LinkedPositionListener#exit(boolean)
*/
public void exit(boolean success) {
// no UNINSTALL since manager has already uninstalled itself
leave((success ? COMMIT : 0) | UPDATE_CARET);
}
/**
* Returns the cursor selection, after having entered the linked mode.
* <code>enter()</code> must be called prior to a call to this method.
*/
public IRegion getSelectedRegion() {
if (fFramePosition == null)
return new Region(fFinalCaretOffset, 0);
else
return new Region(fFramePosition.getOffset(), fFramePosition.getLength());
}
private void leave(int flags) {
if ((flags & UNINSTALL) != 0)
fManager.uninstall((flags & COMMIT) != 0);
fgStore.removePropertyChangeListener(this);
if (fFrameColor != null) {
fFrameColor.dispose();
fFrameColor= null;
}
StyledText text= fViewer.getTextWidget();
text.removePaintListener(this);
text.removeModifyListener(this);
text.removeVerifyListener(this);
ITextViewerExtension extension= (ITextViewerExtension) fViewer;
extension.removeVerifyKeyListener(this);
fViewer.removeTextListener(this);
fViewer.removeTextInputListener(this);
try {
IRegion region= fViewer.getVisibleRegion();
IDocument document= fViewer.getDocument();
if (((flags & COMMIT) != 0) &&
((flags & DOCUMENT_CHANGED) == 0) &&
((flags & UPDATE_CARET) != 0))
{
Position[] positions= document.getPositions(CARET_POSITION);
if ((positions != null) && (positions.length != 0)) {
int offset= positions[0].getOffset() - region.getOffset();
if ((offset >= 0) && (offset <= region.getLength()))
text.setSelection(offset, offset);
}
}
document.removePositionUpdater(fgUpdater);
document.removePositionCategory(CARET_POSITION);
if (fExitListener != null)
fExitListener.exit(
((flags & COMMIT) != 0) ||
((flags & DOCUMENT_CHANGED) != 0));
} catch (BadPositionCategoryException e) {
JavaPlugin.log(e);
Assert.isTrue(false);
}
if ((flags & DOCUMENT_CHANGED) == 0)
text.redraw();
}
private void next() {
redrawRegion();
fFramePosition= fManager.getNextPosition(fFramePosition.getOffset());
if (fFramePosition == null) {
leave(UNINSTALL | COMMIT | UPDATE_CARET);
} else {
selectRegion();
redrawRegion();
}
}
private void previous() {
redrawRegion();
Position position= fManager.getPreviousPosition(fFramePosition.getOffset());
if (position == null) {
fViewer.getTextWidget().getDisplay().beep();
} else {
fFramePosition= position;
selectRegion();
redrawRegion();
}
}
/*
* @see VerifyKeyListener#verifyKey(VerifyEvent)
*/
public void verifyKey(VerifyEvent event) {
if (!event.doit)
return;
Point selection= fViewer.getSelectedRange();
int offset= selection.x;
int length= selection.y;
ExitFlags exitFlags= fExitPolicy == null ? null : fExitPolicy.doExit(fManager, event, offset, length);
if (exitFlags != null) {
leave(UNINSTALL | exitFlags.flags);
event.doit= exitFlags.doit;
return;
}
switch (event.character) {
// [SHIFT-]TAB = hop between edit boxes
case 0x09:
{
// if tab was treated as a document change, would it exceed variable range?
if (!LinkedPositionManager.includes(fFramePosition, offset, length)) {
leave(UNINSTALL | COMMIT | UPDATE_CARET);
return;
}
}
if (event.stateMask == SWT.SHIFT)
previous();
else
next();
event.doit= false;
break;
// ENTER
case 0x0D:
leave(UNINSTALL | COMMIT | UPDATE_CARET);
event.doit= false;
break;
// ESC
case 0x1B:
leave(UNINSTALL | COMMIT);
event.doit= false;
break;
}
}
/*
* @see VerifyListener#verifyText(VerifyEvent)
*/
public void verifyText(VerifyEvent event) {
if (!event.doit)
return;
IRegion region= fViewer.getVisibleRegion();
int offset= event.start + region.getOffset();
int length= event.end - event.start;
// allow changes only within linked positions when coming through UI
if (!fManager.anyPositionIncludes(offset, length))
leave(UNINSTALL | COMMIT);
}
/*
* @see PaintListener#paintControl(PaintEvent)
*/
public void paintControl(PaintEvent event) {
if (fFramePosition == null)
return;
IRegion region= fViewer.getVisibleRegion();
// #6824
if (!includes(region, fFramePosition)) {
leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED);
return;
}
int offset= fFramePosition.getOffset() - region.getOffset();
int length= fFramePosition.getLength();
StyledText text= fViewer.getTextWidget();
// support for bidi
Point minLocation= getMinimumLocation(text, offset, length);
Point maxLocation= getMaximumLocation(text, offset, length);
int x1= minLocation.x;
int x2= minLocation.x + maxLocation.x - minLocation.x - 1;
int y= minLocation.y + text.getLineHeight() - 1;
GC gc= event.gc;
gc.setForeground(fFrameColor);
gc.drawLine(x1, y, x2, y);
}
private static Point getMinimumLocation(StyledText text, int offset, int length) {
Point minLocation= new Point(Integer.MAX_VALUE, Integer.MAX_VALUE);
for (int i= 0; i <= length; i++) {
Point location= text.getLocationAtOffset(offset + i);
if (location.x < minLocation.x)
minLocation.x= location.x;
if (location.y < minLocation.y)
minLocation.y= location.y;
}
return minLocation;
}
private static Point getMaximumLocation(StyledText text, int offset, int length) {
Point maxLocation= new Point(Integer.MIN_VALUE, Integer.MIN_VALUE);
for (int i= 0; i <= length; i++) {
Point location= text.getLocationAtOffset(offset + i);
if (location.x > maxLocation.x)
maxLocation.x= location.x;
if (location.y > maxLocation.y)
maxLocation.y= location.y;
}
return maxLocation;
}
private void redrawRegion() {
IRegion region= fViewer.getVisibleRegion();
if (!includes(region, fFramePosition)) {
leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED);
return;
}
int offset= fFramePosition.getOffset() - region.getOffset();
int length= fFramePosition.getLength();
StyledText text= fViewer.getTextWidget();
if (text != null && !text.isDisposed())
text.redrawRange(offset, length, true);
}
private void selectRegion() {
IRegion region= fViewer.getVisibleRegion();
if (!includes(region, fFramePosition)) {
leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED);
return;
}
int start= fFramePosition.getOffset() - region.getOffset();
int end= fFramePosition.getLength() + start;
StyledText text= fViewer.getTextWidget();
if (text != null && !text.isDisposed())
text.setSelection(start, end);
}
private void updateCaret() {
IRegion region= fViewer.getVisibleRegion();
if (!includes(region, fFramePosition)) {
leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED);
return;
}
int offset= fFramePosition.getOffset() + fCaretOffset - region.getOffset();
if ((offset >= 0) && (offset <= region.getLength())) {
StyledText text= fViewer.getTextWidget();
if (text != null && !text.isDisposed())
text.setCaretOffset(offset);
}
}
/*
* @see ModifyListener#modifyText(ModifyEvent)
*/
public void modifyText(ModifyEvent e) {
// reposition caret after StyledText
redrawRegion();
updateCaret();
}
private static void handleException(Shell shell, Exception e) {
String title= LinkedPositionMessages.getString("LinkedPositionUI.error.title"); //$NON-NLS-1$
if (e instanceof CoreException)
ExceptionHandler.handle((CoreException)e, shell, title, null);
else if (e instanceof InvocationTargetException)
ExceptionHandler.handle((InvocationTargetException)e, shell, title, null);
else {
MessageDialog.openError(shell, title, e.getMessage());
JavaPlugin.log(e);
}
}
/*
* @see ITextInputListener#inputDocumentAboutToBeChanged(IDocument, IDocument)
*/
public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) {
// 5326: leave linked mode on document change
int flags= UNINSTALL | COMMIT | (oldInput.equals(newInput) ? 0 : DOCUMENT_CHANGED);
leave(flags);
}
/*
* @see ITextInputListener#inputDocumentChanged(IDocument, IDocument)
*/
public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
}
private static boolean includes(IRegion region, Position position) {
return
position.getOffset() >= region.getOffset() &&
position.getOffset() + position.getLength() <= region.getOffset() + region.getLength();
}
/*
* @see org.eclipse.jface.text.ITextListener#textChanged(TextEvent)
*/
public void textChanged(TextEvent event) {
if (!fNeedRedraw)
return;
redrawRegion();
fNeedRedraw= false;
}
}
|
26,504 |
Bug 26504 Refactoring - touches files not involved in action [refactiong]
|
20021114 1. In the Java perspective, package explorer visible. 2. Open FilterDescriptor (jdt.ui) select ID_PLUGIN (line 76). 3. From the context menu choose Refactoring -> Inline Constant 4. On the first page press next 5. On the preview page, uncheck all checkboxes, except for the first 6. press finish. Several files touched: Probably all including the uncheck ones.
|
resolved fixed
|
943f1d4
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-22T16:43:44Z | 2002-11-15T19:53:20Z |
org.eclipse.jdt.ui/core
| |
26,504 |
Bug 26504 Refactoring - touches files not involved in action [refactiong]
|
20021114 1. In the Java perspective, package explorer visible. 2. Open FilterDescriptor (jdt.ui) select ID_PLUGIN (line 76). 3. From the context menu choose Refactoring -> Inline Constant 4. On the first page press next 5. On the preview page, uncheck all checkboxes, except for the first 6. press finish. Several files touched: Probably all including the uncheck ones.
|
resolved fixed
|
943f1d4
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-22T16:43:44Z | 2002-11-15T19:53:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/changes/AbstractTextChange.java
| |
26,504 |
Bug 26504 Refactoring - touches files not involved in action [refactiong]
|
20021114 1. In the Java perspective, package explorer visible. 2. Open FilterDescriptor (jdt.ui) select ID_PLUGIN (line 76). 3. From the context menu choose Refactoring -> Inline Constant 4. On the first page press next 5. On the preview page, uncheck all checkboxes, except for the first 6. press finish. Several files touched: Probably all including the uncheck ones.
|
resolved fixed
|
943f1d4
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-22T16:43:44Z | 2002-11-15T19:53:20Z |
org.eclipse.jdt.ui/core
| |
26,504 |
Bug 26504 Refactoring - touches files not involved in action [refactiong]
|
20021114 1. In the Java perspective, package explorer visible. 2. Open FilterDescriptor (jdt.ui) select ID_PLUGIN (line 76). 3. From the context menu choose Refactoring -> Inline Constant 4. On the first page press next 5. On the preview page, uncheck all checkboxes, except for the first 6. press finish. Several files touched: Probably all including the uncheck ones.
|
resolved fixed
|
943f1d4
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-22T16:43:44Z | 2002-11-15T19:53:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/changes/TextFileChange.java
| |
24,892 |
Bug 24892 inline method does nothing
|
20021016-I linux-gtk: public class Foo { public static final void foo() { System.out.println("hello"); } public static void main(String[] args) { foo(); } } 1. select foo() used in main 2. refactor inline method 3. press next 4. press back 5. press finish 6. observe that nothing happens
|
resolved fixed
|
64e2080
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-22T17:28:58Z | 2002-10-17T10:20:00Z |
org.eclipse.jdt.ui/core
| |
24,892 |
Bug 24892 inline method does nothing
|
20021016-I linux-gtk: public class Foo { public static final void foo() { System.out.println("hello"); } public static void main(String[] args) { foo(); } } 1. select foo() used in main 2. refactor inline method 3. press next 4. press back 5. press finish 6. observe that nothing happens
|
resolved fixed
|
64e2080
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-22T17:28:58Z | 2002-10-17T10:20:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/InlineMethodRefactoring.java
| |
24,892 |
Bug 24892 inline method does nothing
|
20021016-I linux-gtk: public class Foo { public static final void foo() { System.out.println("hello"); } public static void main(String[] args) { foo(); } } 1. select foo() used in main 2. refactor inline method 3. press next 4. press back 5. press finish 6. observe that nothing happens
|
resolved fixed
|
64e2080
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-22T17:28:58Z | 2002-10-17T10:20:00Z |
org.eclipse.jdt.ui/core
| |
24,892 |
Bug 24892 inline method does nothing
|
20021016-I linux-gtk: public class Foo { public static final void foo() { System.out.println("hello"); } public static void main(String[] args) { foo(); } } 1. select foo() used in main 2. refactor inline method 3. press next 4. press back 5. press finish 6. observe that nothing happens
|
resolved fixed
|
64e2080
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-22T17:28:58Z | 2002-10-17T10:20:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/TargetProvider.java
| |
26,746 |
Bug 26746 Organize Imports leaves an unnecessary import of inner interface [code manipulation]
|
The compiler warns about an unnecessary import, while the organize imports does not remove it. This can be reproduced with these sources: MyClass.java: import MyInterface.MyInnerInterface; public class MyClass implements MyInterface{ public MyInnerInterface myMethod() { return null; } } MyInterface.java: public interface MyInterface { public interface MyInnerInterface { } }
|
resolved fixed
|
4767461
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-25T15:50:08Z | 2002-11-20T11:00:00Z |
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/ImportOrganizeTest.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.ui.tests.core;
import java.io.File;
import java.util.zip.ZipFile;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.testplugin.JavaProjectHelper;
import org.eclipse.jdt.testplugin.JavaTestPlugin;
import org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation;
import org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation.IChooseImportQuery;
import org.eclipse.jdt.internal.corext.util.TypeInfo;
public class ImportOrganizeTest extends TestCase {
private static final Class THIS= ImportOrganizeTest.class;
private IJavaProject fJProject1;
public ImportOrganizeTest(String name) {
super(name);
}
public static Test suite() {
if (true) {
return new TestSuite(THIS);
} else {
TestSuite suite= new TestSuite();
suite.addTest(new ImportOrganizeTest("test_bug25773"));
return suite;
}
}
protected void setUp() throws Exception {
fJProject1= JavaProjectHelper.createJavaProject("TestProject1", "bin");
assertTrue("rt not found", JavaProjectHelper.addRTJar(fJProject1) != null);
}
protected void tearDown() throws Exception {
JavaProjectHelper.delete(fJProject1);
}
private IChooseImportQuery createQuery(final String name, final String[] choices, final int[] nEntries) {
return new IChooseImportQuery() {
public TypeInfo[] chooseImports(TypeInfo[][] openChoices, ISourceRange[] ranges) {
assertTrue(name + "-query-nchoices1", choices.length == openChoices.length);
assertTrue(name + "-query-nchoices2", nEntries.length == openChoices.length);
if (nEntries != null) {
for (int i= 0; i < nEntries.length; i++) {
assertTrue(name + "-query-cnt" + i, openChoices[i].length == nEntries[i]);
}
}
TypeInfo[] res= new TypeInfo[openChoices.length];
for (int i= 0; i < openChoices.length; i++) {
TypeInfo[] selection= openChoices[i];
assertNotNull(name + "-query-setset" + i, selection);
assertTrue(name + "-query-setlen" + i, selection.length > 0);
TypeInfo found= null;
for (int k= 0; k < selection.length; k++) {
if (selection[k].getFullyQualifiedName().equals(choices[i])) {
found= selection[k];
}
}
assertNotNull(name + "-query-notfound" + i, found);
res[i]= found;
}
return res;
}
};
}
private void assertImports(ICompilationUnit cu, String[] imports) throws Exception {
IImportDeclaration[] desc= cu.getImports();
assertTrue(cu.getElementName() + "-count", desc.length == imports.length);
for (int i= 0; i < imports.length; i++) {
assertEquals(cu.getElementName() + "-cmpentries" + i, desc[i].getElementName(), imports[i]);
}
}
public void test1() throws Exception {
File junitSrcArchive= JavaTestPlugin.getDefault().getFileInPlugin(JavaProjectHelper.JUNIT_SRC);
assertTrue("junit src not found", junitSrcArchive != null && junitSrcArchive.exists());
ZipFile zipfile= new ZipFile(junitSrcArchive);
JavaProjectHelper.addSourceContainerWithImport(fJProject1, "src", zipfile);
ICompilationUnit cu= (ICompilationUnit) fJProject1.findElement(new Path("junit/runner/BaseTestRunner.java"));
assertNotNull("BaseTestRunner.java", cu);
IPackageFragmentRoot root= (IPackageFragmentRoot)cu.getParent().getParent();
IPackageFragment pack= root.createPackageFragment("mytest", true, null);
ICompilationUnit colidingCU= pack.getCompilationUnit("TestListener.java");
colidingCU.createType("public abstract class TestListener {\n}\n", null, true, null);
String[] order= new String[0];
IChooseImportQuery query= createQuery("BaseTestRunner", new String[] { "junit.framework.TestListener" }, new int[] { 2 });
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
assertImports(cu, new String[] {
"java.io.BufferedReader",
"java.io.File",
"java.io.FileInputStream",
"java.io.IOException",
"java.io.InputStream",
"java.io.PrintWriter",
"java.io.StringReader",
"java.io.StringWriter",
"java.lang.reflect.InvocationTargetException",
"java.lang.reflect.Method",
"java.text.NumberFormat",
"java.util.Properties",
"junit.framework.Test",
"junit.framework.TestListener",
"junit.framework.TestSuite"
});
}
public void test1WithOrder() throws Exception {
File junitSrcArchive= JavaTestPlugin.getDefault().getFileInPlugin(JavaProjectHelper.JUNIT_SRC);
assertTrue("junit src not found", junitSrcArchive != null && junitSrcArchive.exists());
ZipFile zipfile= new ZipFile(junitSrcArchive);
JavaProjectHelper.addSourceContainerWithImport(fJProject1, "src", zipfile);
ICompilationUnit cu= (ICompilationUnit) fJProject1.findElement(new Path("junit/runner/BaseTestRunner.java"));
assertNotNull("BaseTestRunner.java", cu);
IPackageFragmentRoot root= (IPackageFragmentRoot)cu.getParent().getParent();
IPackageFragment pack= root.createPackageFragment("mytest", true, null);
ICompilationUnit colidingCU= pack.getCompilationUnit("TestListener.java");
colidingCU.createType("public abstract class TestListener {\n}\n", null, true, null);
String[] order= new String[] { "junit", "java.text", "java.io", "java" };
IChooseImportQuery query= createQuery("BaseTestRunner", new String[] { "junit.framework.TestListener" }, new int[] { 2 });
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
assertImports(cu, new String[] {
"junit.framework.Test",
"junit.framework.TestListener",
"junit.framework.TestSuite",
"java.text.NumberFormat",
"java.io.BufferedReader",
"java.io.File",
"java.io.FileInputStream",
"java.io.IOException",
"java.io.InputStream",
"java.io.PrintWriter",
"java.io.StringReader",
"java.io.StringWriter",
"java.lang.reflect.InvocationTargetException",
"java.lang.reflect.Method",
"java.util.Properties"
});
}
public void test2() throws Exception {
File junitSrcArchive= JavaTestPlugin.getDefault().getFileInPlugin(JavaProjectHelper.JUNIT_SRC);
assertTrue("junit src not found", junitSrcArchive != null && junitSrcArchive.exists());
ZipFile zipfile= new ZipFile(junitSrcArchive);
JavaProjectHelper.addSourceContainerWithImport(fJProject1, "src", zipfile);
ICompilationUnit cu= (ICompilationUnit) fJProject1.findElement(new Path("junit/runner/LoadingTestCollector.java"));
assertNotNull("LoadingTestCollector.java", cu);
String[] order= new String[0];
IChooseImportQuery query= createQuery("LoadingTestCollector", new String[] { }, new int[] { });
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
assertImports(cu, new String[] {
"java.lang.reflect.Constructor",
"java.lang.reflect.Method",
"java.lang.reflect.Modifier",
"junit.framework.Test"
});
}
public void test3() throws Exception {
File junitSrcArchive= JavaTestPlugin.getDefault().getFileInPlugin(JavaProjectHelper.JUNIT_SRC);
assertTrue("junit src not found", junitSrcArchive != null && junitSrcArchive.exists());
ZipFile zipfile= new ZipFile(junitSrcArchive);
JavaProjectHelper.addSourceContainerWithImport(fJProject1, "src", zipfile);
ICompilationUnit cu= (ICompilationUnit) fJProject1.findElement(new Path("junit/runner/TestCaseClassLoader.java"));
assertNotNull("TestCaseClassLoader.java", cu);
String[] order= new String[0];
IChooseImportQuery query= createQuery("TestCaseClassLoader", new String[] { }, new int[] { });
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 3, false, true, true, query);
op.run(null);
assertImports(cu, new String[] {
"java.io.*",
"java.net.URL",
"java.util.*",
"java.util.zip.ZipEntry",
"java.util.zip.ZipFile",
});
}
public void test4() throws Exception {
File junitSrcArchive= JavaTestPlugin.getDefault().getFileInPlugin(JavaProjectHelper.JUNIT_SRC);
assertTrue("junit src not found", junitSrcArchive != null && junitSrcArchive.exists());
ZipFile zipfile= new ZipFile(junitSrcArchive);
JavaProjectHelper.addSourceContainerWithImport(fJProject1, "src", zipfile);
ICompilationUnit cu= (ICompilationUnit) fJProject1.findElement(new Path("junit/textui/TestRunner.java"));
assertNotNull("TestRunner.java", cu);
String[] order= new String[0];
IChooseImportQuery query= createQuery("TestRunner", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
assertImports(cu, new String[] {
"java.io.PrintStream",
"java.util.Enumeration",
"junit.framework.AssertionFailedError",
"junit.framework.Test",
"junit.framework.TestFailure",
"junit.framework.TestResult",
"junit.framework.TestSuite",
"junit.runner.BaseTestRunner",
"junit.runner.StandardTestSuiteLoader",
"junit.runner.TestSuiteLoader",
"junit.runner.Version"
});
}
public void testVariousTypeReferences() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack= sourceFolder.createPackageFragment("test", false, null);
for (int ch= 'A'; ch < 'M'; ch++) {
String name= String.valueOf((char) ch);
ICompilationUnit cu= pack.getCompilationUnit(name + ".java");
String content= "public class " + name + " {}";
cu.createType(content, null, false, null);
}
for (int ch= 'A'; ch < 'M'; ch++) {
String name= "I" + String.valueOf((char) ch);
ICompilationUnit cu= pack.getCompilationUnit(name + ".java");
String content= "public interface " + name + " {}";
cu.createType(content, null, false, null);
}
StringBuffer buf= new StringBuffer();
buf.append("public class ImportTest extends A implements IA, IB {\n");
buf.append(" private B fB;\n");
buf.append(" private Object fObj= new C();\n");
buf.append(" public IB foo(IC c, ID d) throws IOException {\n");
buf.append(" Object local= (D) fObj;\n");
buf.append(" if (local instanceof E) {};\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append("}\n");
pack= sourceFolder.createPackageFragment("other", false, null);
ICompilationUnit cu= pack.getCompilationUnit("ImportTest.java");
cu.createType(buf.toString(), null, false, null);
String[] order= new String[0];
IChooseImportQuery query= createQuery("ImportTest", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
assertImports(cu, new String[] {
"java.io.IOException",
"test.A",
"test.B",
"test.C",
"test.D",
"test.E",
"test.IA",
"test.IB",
"test.IC",
"test.ID",
});
}
public void testInnerClassVisibility() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack1= sourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class C {\n");
buf.append(" protected static class C1 {\n");
buf.append(" public static class C2 {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("C.java", buf.toString(), false, null);
IPackageFragment pack2= sourceFolder.createPackageFragment("test2", false, null);
buf= new StringBuffer();
buf.append("package test2;\n");
buf.append("import test2.A.A1;\n");
buf.append("import test2.A.A1.A2;\n");
buf.append("import test2.A.A1.A2.A3;\n");
buf.append("import test2.A.B1;\n");
buf.append("import test2.A.B1.B2;\n");
buf.append("import test1.C;\n");
buf.append("import test1.C.C1.C2;\n");
buf.append("public class A {\n");
buf.append(" public static class A1 {\n");
buf.append(" public static class A2 {\n");
buf.append(" public static class A3 {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" public static class B1 {\n");
buf.append(" public static class B2 {\n");
buf.append(" }\n");
buf.append(" public static class B3 {\n");
buf.append(" public static class B4 extends C {\n");
buf.append(" B4 b4;\n");
buf.append(" B3 b3;\n");
buf.append(" B2 b2;\n");
buf.append(" B1 b1;\n");
buf.append(" A1 a1;\n");
buf.append(" A2 a2;\n");
buf.append(" A3 a3;\n");
buf.append(" C1 c1;\n");
buf.append(" C2 c2;\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" }\n");
ICompilationUnit cu2= pack2.createCompilationUnit("A.java", buf.toString(), false, null);
String[] order= new String[0];
IChooseImportQuery query= createQuery("A", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu2, order, 99, false, true, true, query);
op.run(null);
assertImports(cu2, new String[] {
"test1.C",
"test1.C.C1.C2",
"test2.A.A1.A2",
"test2.A.A1.A2.A3"
});
}
private static final int printRange= 6;
public static void assertEqualString(String str1, String str2) {
int len1= Math.min(str1.length(), str2.length());
int diffPos= -1;
for (int i= 0; i < len1; i++) {
if (str1.charAt(i) != str2.charAt(i)) {
diffPos= i;
break;
}
}
if (diffPos == -1 && str1.length() != str2.length()) {
diffPos= len1;
}
if (diffPos != -1) {
int diffAhead= Math.max(0, diffPos - printRange);
int diffAfter= Math.min(str1.length(), diffPos + printRange);
String diffStr= str1.substring(diffAhead, diffPos) + '^' + str1.substring(diffPos, diffAfter);
assertTrue("Content not as expected: is\n" + str1 + "\nDiffers at pos " + diffPos + ": " + diffStr + "\nexpected:\n" + str2, false);
}
}
public void testClearImports() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack1= sourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class C {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[0];
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class C {\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testNewImports() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack1= sourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class C extends Vector {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[0];
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
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 C extends Vector {\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testReplaceImports() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack1= sourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("import java.util.Set;\n");
buf.append("\n");
buf.append("public class C extends Vector {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[0];
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
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 C extends Vector {\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testClearImportsNoPackage() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack1= sourceFolder.getPackageFragment("");
StringBuffer buf= new StringBuffer();
buf.append("import java.util.Vector;\n");
buf.append("public class C {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[0];
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("public class C {\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testNewImportsNoPackage() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack1= sourceFolder.getPackageFragment("");
StringBuffer buf= new StringBuffer();
buf.append("public class C extends Vector {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[0];
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("import java.util.Vector;\n");
buf.append("\n");
buf.append("public class C extends Vector {\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testReplaceImportsNoPackage() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack1= sourceFolder.getPackageFragment("");
StringBuffer buf= new StringBuffer();
buf.append("import java.util.Set;\n");
buf.append("\n");
buf.append("public class C extends Vector {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[0];
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("import java.util.Vector;\n");
buf.append("\n");
buf.append("public class C extends Vector {\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testCommentAfterImport() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package pack1;\r\n");
buf.append("\r\n");
buf.append("import x;\r\n");
buf.append("import java.util.Vector; // comment\r\n");
buf.append("\r\n");
buf.append("public class C {\r\n");
buf.append(" Vector v;\r\n");
buf.append("}\r\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[0];
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("package pack1;\r\n");
buf.append("\r\n");
buf.append("import java.util.Vector;\r\n");
buf.append("\r\n");
buf.append("public class C {\r\n");
buf.append(" Vector v;\r\n");
buf.append("}\r\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testImportToStar() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack2= sourceFolder.createPackageFragment("pack", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class List {\n");
buf.append("}\n");
pack2.createCompilationUnit("List.java", buf.toString(), false, null);
IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import java.util.Set;\n");
buf.append("import java.util.Vector;\n");
buf.append("import java.util.Map;\n");
buf.append("\n");
buf.append("import pack.List;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" Vector v;\n");
buf.append(" Set v2;\n");
buf.append(" Map v3;\n");
buf.append(" List v4;\n");
buf.append(" String v5;\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[] { "java", "pack" };
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 2, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import java.util.*;\n");
buf.append("\n");
buf.append("import pack.List;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" Vector v;\n");
buf.append(" Set v2;\n");
buf.append(" Map v3;\n");
buf.append(" List v4;\n");
buf.append(" String v5;\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testImportToStarWithExplicit() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack2= sourceFolder.createPackageFragment("pack", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class List {\n");
buf.append("}\n");
pack2.createCompilationUnit("List.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class List2 {\n");
buf.append("}\n");
pack2.createCompilationUnit("List2.java", buf.toString(), false, null);
IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import java.util.Set;\n");
buf.append("import java.util.Vector;\n");
buf.append("import java.util.Map;\n");
buf.append("\n");
buf.append("import pack.List;\n");
buf.append("import pack.List2;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" Vector v;\n");
buf.append(" Set v2;\n");
buf.append(" Map v3;\n");
buf.append(" List v4;\n");
buf.append(" List2 v5;\n");
buf.append(" String v6;\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[] { "java", "pack" };
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 2, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import java.util.*;\n");
buf.append("\n");
buf.append("import pack.*;\n");
buf.append("import pack.List;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" Vector v;\n");
buf.append(" Set v2;\n");
buf.append(" Map v3;\n");
buf.append(" List v4;\n");
buf.append(" List2 v5;\n");
buf.append(" String v6;\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testImportFromDefault() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack2= sourceFolder.createPackageFragment("", false, null);
StringBuffer buf= new StringBuffer();
buf.append("public class List1 {\n");
buf.append("}\n");
pack2.createCompilationUnit("List1.java", buf.toString(), false, null);
IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import java.util.Set;\n");
buf.append("import java.util.Vector;\n");
buf.append("import java.util.Map;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" Vector v;\n");
buf.append(" Set v2;\n");
buf.append(" Map v3;\n");
buf.append(" List1 v4;\n");
buf.append(" String v5;\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[] { "java", "pack" };
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 2, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import List1;\n");
buf.append("\n");
buf.append("import java.util.*;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" Vector v;\n");
buf.append(" Set v2;\n");
buf.append(" Map v3;\n");
buf.append(" List1 v4;\n");
buf.append(" String v5;\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testImportFromDefaultWithStar() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack2= sourceFolder.createPackageFragment("", false, null);
StringBuffer buf= new StringBuffer();
buf.append("public class List1 {\n");
buf.append("}\n");
pack2.createCompilationUnit("List1.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("public class List2 {\n");
buf.append("}\n");
pack2.createCompilationUnit("List2.java", buf.toString(), false, null);
IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import java.util.Set;\n");
buf.append("import java.util.Vector;\n");
buf.append("import java.util.Map;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" Vector v;\n");
buf.append(" Set v2;\n");
buf.append(" Map v3;\n");
buf.append(" List1 v4;\n");
buf.append(" List2 v5;\n");
buf.append(" String v6;\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[] { "java", "pack" };
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 2, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import List1;\n");
buf.append("import List2;\n");
buf.append("\n");
buf.append("import java.util.*;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" Vector v;\n");
buf.append(" Set v2;\n");
buf.append(" Map v3;\n");
buf.append(" List1 v4;\n");
buf.append(" List2 v5;\n");
buf.append(" String v6;\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testImportOfMemberFromLocal() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" public void foo() {\n");
buf.append(" class Local {\n");
buf.append(" class LocalMember {\n");
buf.append(" }\n");
buf.append(" LocalMember x;\n");
buf.append(" Vector v;\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[] { "java", "pack" };
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import java.util.Vector;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" public void foo() {\n");
buf.append(" class Local {\n");
buf.append(" class LocalMember {\n");
buf.append(" }\n");
buf.append(" LocalMember x;\n");
buf.append(" Vector v;\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testGroups1() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack2= sourceFolder.createPackageFragment("pack0", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package pack0;\n");
buf.append("public class List1 {\n");
buf.append("}\n");
pack2.createCompilationUnit("List1.java", buf.toString(), false, null);
IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" File f;\n");
buf.append(" IOException f1;\n");
buf.append(" RandomAccessFile f2;\n");
buf.append(" ArrayList f3;\n");
buf.append(" List1 f4;\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[] { "java.io", "java.util" };
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import java.io.File;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.io.RandomAccessFile;\n");
buf.append("\n");
buf.append("import java.util.ArrayList;\n");
buf.append("\n");
buf.append("import pack0.List1;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" File f;\n");
buf.append(" IOException f1;\n");
buf.append(" RandomAccessFile f2;\n");
buf.append(" ArrayList f3;\n");
buf.append(" List1 f4;\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void testBaseGroups1() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack2= sourceFolder.createPackageFragment("pack0", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package pack0;\n");
buf.append("public class List1 {\n");
buf.append("}\n");
pack2.createCompilationUnit("List1.java", buf.toString(), false, null);
IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" File f;\n");
buf.append(" IOException f1;\n");
buf.append(" RandomAccessFile f2;\n");
buf.append(" ArrayList f3;\n");
buf.append(" List1 f4;\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
String[] order= new String[] { "java", "java.io" };
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import java.util.ArrayList;\n");
buf.append("\n");
buf.append("import java.io.File;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.io.RandomAccessFile;\n");
buf.append("\n");
buf.append("import pack0.List1;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append(" File f;\n");
buf.append(" IOException f1;\n");
buf.append(" RandomAccessFile f2;\n");
buf.append(" ArrayList f3;\n");
buf.append(" List1 f4;\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
}
public void test5() throws Exception {
String[] types= new String[] {
"org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader",
"org.eclipse.core.resources.IContainer",
"org.eclipse.core.runtime.IPath",
"org.eclipse.core.runtime.CoreException",
"org.eclipse.core.resources.IResource",
"org.eclipse.jdt.internal.compiler.env.NameEnvironmentAnswer"
};
String[] order= new String[] { "org.eclipse.jdt", "org.eclipse" };
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
for (int i= 0; i < types.length; i++) {
String pack= Signature.getQualifier(types[i]);
String name= Signature.getSimpleName(types[i]);
IPackageFragment pack2= sourceFolder.createPackageFragment(pack, false, null);
StringBuffer buf= new StringBuffer();
buf.append("package "); buf.append(pack); buf.append(";\n");
buf.append("public class "); buf.append(name); buf.append(" {\n");
buf.append("}\n");
pack2.createCompilationUnit(name + ".java", buf.toString(), false, null);
}
StringBuffer body= new StringBuffer();
body.append("public class C {\n");
for (int i= 0; i < types.length; i++) {
String name= Signature.getSimpleName(types[i]);
body.append(name); body.append(" a"); body.append(i); body.append(";\n");
}
body.append("}\n");
IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append(body.toString());
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader;\n");
buf.append("import org.eclipse.jdt.internal.compiler.env.NameEnvironmentAnswer;\n");
buf.append("\n");
buf.append("import org.eclipse.core.resources.IContainer;\n");
buf.append("import org.eclipse.core.resources.IResource;\n");
buf.append("import org.eclipse.core.runtime.CoreException;\n");
buf.append("import org.eclipse.core.runtime.IPath;\n");
buf.append("\n");
buf.append(body.toString());
assertEqualString(cu.getSource(), buf.toString());
}
public void test_bug25773() throws Exception {
String[] types= new String[] {
"java.util.Vector",
"java.util.Map",
"java.util.Set",
"org.eclipse.gef.X1",
"org.eclipse.gef.X2",
"org.eclipse.gef.X3",
"org.eclipse.core.runtime.IAdaptable",
"org.eclipse.draw2d.IFigure",
"org.eclipse.draw2d.LayoutManager",
"org.eclipse.draw2d.geometry.Point",
"org.eclipse.draw2d.geometry.Rectangle",
"org.eclipse.swt.accessibility.ACC",
"org.eclipse.swt.accessibility.AccessibleControlEvent"
};
String[] order= new String[] { "java", "org.eclipse", "org.eclipse.gef", "org.eclipse.draw2d", "org.eclipse.gef.examples" };
int threshold= 3;
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
for (int i= 0; i < types.length; i++) {
String pack= Signature.getQualifier(types[i]);
if (!pack.startsWith("java.")) {
String name= Signature.getSimpleName(types[i]);
IPackageFragment pack2= sourceFolder.createPackageFragment(pack, false, null);
StringBuffer buf= new StringBuffer();
buf.append("package "); buf.append(pack); buf.append(";\n");
buf.append("public class "); buf.append(name); buf.append(" {\n");
buf.append("}\n");
pack2.createCompilationUnit(name + ".java", buf.toString(), false, null);
}
}
StringBuffer body= new StringBuffer();
body.append("public class C {\n");
for (int i= 0; i < types.length; i++) {
String name= Signature.getSimpleName(types[i]);
body.append(name); body.append(" a"); body.append(i); body.append(";\n");
}
body.append("}\n");
IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append(body.toString());
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, threshold, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import java.util.*;\n");
buf.append("\n");
buf.append("import org.eclipse.core.runtime.IAdaptable;\n");
buf.append("import org.eclipse.swt.accessibility.ACC;\n");
buf.append("import org.eclipse.swt.accessibility.AccessibleControlEvent;\n");
buf.append("\n");
buf.append("import org.eclipse.gef.*;\n");
buf.append("\n");
buf.append("import org.eclipse.draw2d.IFigure;\n");
buf.append("import org.eclipse.draw2d.LayoutManager;\n");
buf.append("import org.eclipse.draw2d.geometry.Point;\n");
buf.append("import org.eclipse.draw2d.geometry.Rectangle;\n");
buf.append("\n");
buf.append(body.toString());
assertEqualString(cu.getSource(), buf.toString());
}
public void test_bug25113() throws Exception {
String[] types= new String[] {
"com.mycompany.Class1",
"com.foreigncompany.Class2",
"com.foreigncompany.Class3",
"com.mycompany.Class4",
"com.misc.Class5"
};
String[] order= new String[] { "com", "com.foreigncompany", "com.mycompany" };
int threshold= 99;
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
for (int i= 0; i < types.length; i++) {
String pack= Signature.getQualifier(types[i]);
if (!pack.startsWith("java.")) {
String name= Signature.getSimpleName(types[i]);
IPackageFragment pack2= sourceFolder.createPackageFragment(pack, false, null);
StringBuffer buf= new StringBuffer();
buf.append("package "); buf.append(pack); buf.append(";\n");
buf.append("public class "); buf.append(name); buf.append(" {\n");
buf.append("}\n");
pack2.createCompilationUnit(name + ".java", buf.toString(), false, null);
}
}
StringBuffer body= new StringBuffer();
body.append("public class C {\n");
for (int i= 0; i < types.length; i++) {
String name= Signature.getSimpleName(types[i]);
body.append(name); body.append(" a"); body.append(i); body.append(";\n");
}
body.append("}\n");
IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append(body.toString());
ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, threshold, false, true, true, query);
op.run(null);
buf= new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import com.misc.Class5;\n");
buf.append("\n");
buf.append("import com.foreigncompany.Class2;\n");
buf.append("import com.foreigncompany.Class3;\n");
buf.append("\n");
buf.append("import com.mycompany.Class1;\n");
buf.append("import com.mycompany.Class4;\n");
buf.append("\n");
buf.append(body.toString());
assertEqualString(cu.getSource(), buf.toString());
}
}
|
26,746 |
Bug 26746 Organize Imports leaves an unnecessary import of inner interface [code manipulation]
|
The compiler warns about an unnecessary import, while the organize imports does not remove it. This can be reproduced with these sources: MyClass.java: import MyInterface.MyInnerInterface; public class MyClass implements MyInterface{ public MyInnerInterface myMethod() { return null; } } MyInterface.java: public interface MyInterface { public interface MyInnerInterface { } }
|
resolved fixed
|
4767461
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-25T15:50:08Z | 2002-11-20T11:00:00Z |
org.eclipse.jdt.ui/core
| |
26,746 |
Bug 26746 Organize Imports leaves an unnecessary import of inner interface [code manipulation]
|
The compiler warns about an unnecessary import, while the organize imports does not remove it. This can be reproduced with these sources: MyClass.java: import MyInterface.MyInnerInterface; public class MyClass implements MyInterface{ public MyInnerInterface myMethod() { return null; } } MyInterface.java: public interface MyInterface { public interface MyInnerInterface { } }
|
resolved fixed
|
4767461
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-25T15:50:08Z | 2002-11-20T11:00:00Z |
extension/org/eclipse/jdt/internal/corext/codemanipulation/OrganizeImportsOperation.java
| |
26,313 |
Bug 26313 Assign to new local should not be available on assignmet statement
|
Build I2002113 Quick assist new local should not be available on statements like x= name when selecting name.
|
resolved fixed
|
e78128e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-25T17:22:09Z | 2002-11-14T16:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/QuickAssistProcessor.java
|
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.BodyDeclaration;
import org.eclipse.jdt.core.dom.CatchClause;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.ExpressionStatement;
import org.eclipse.jdt.core.dom.IBinding;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.Name;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.core.dom.SimpleType;
import org.eclipse.jdt.core.dom.Statement;
import org.eclipse.jdt.core.dom.TryStatement;
import org.eclipse.jdt.core.dom.Type;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
/**
*/
public class QuickAssistProcessor implements ICorrectionProcessor {
/**
* Constructor for CodeManipulationProcessor.
*/
public QuickAssistProcessor() {
super();
}
public void process(ICorrectionContext context, List resultingCollections) throws CoreException {
int id= context.getProblemId();
if (id != 0) { // no proposals for problem locations
return;
}
getAssignToVariableProposals(context, resultingCollections);
getCatchClauseToThrowsProposals(context, resultingCollections);
getRenameLocalProposals(context, resultingCollections);
}
private void getAssignToVariableProposals(ICorrectionContext context, List resultingCollections) throws CoreException {
ASTNode node= context.getCoveringNode();
Statement statement= ASTResolving.findParentStatement(node);
if (!(statement instanceof ExpressionStatement)) {
return;
}
ExpressionStatement expressionStatement= (ExpressionStatement) statement;
Expression expression= expressionStatement.getExpression();
ITypeBinding typeBinding= expression.resolveTypeBinding();
typeBinding= ASTResolving.normalizeTypeBinding(typeBinding);
if (typeBinding == null) {
return;
}
ICompilationUnit cu= context.getCompilationUnit();
AssignToVariableAssistProposal localProposal= new AssignToVariableAssistProposal(cu, AssignToVariableAssistProposal.LOCAL, expressionStatement, typeBinding, 2);
resultingCollections.add(localProposal);
ASTNode type= ASTResolving.findParentType(expression);
if (type != null) {
AssignToVariableAssistProposal fieldProposal= new AssignToVariableAssistProposal(cu, AssignToVariableAssistProposal.FIELD, expressionStatement, typeBinding, 1);
resultingCollections.add(fieldProposal);
}
}
private void getCatchClauseToThrowsProposals(ICorrectionContext context, List resultingCollections) throws CoreException {
ASTNode node= context.getCoveringNode();
CatchClause catchClause= (CatchClause) ASTResolving.findAncestor(node, ASTNode.CATCH_CLAUSE);
if (catchClause == null) {
return;
}
Type type= catchClause.getException().getType();
if (!type.isSimpleType()) {
return;
}
BodyDeclaration bodyDeclaration= ASTResolving.findParentBodyDeclaration(catchClause);
if (!(bodyDeclaration instanceof MethodDeclaration)) {
return;
}
MethodDeclaration methodDeclaration= (MethodDeclaration) bodyDeclaration;
ASTRewrite rewrite= new ASTRewrite(methodDeclaration);
AST ast= methodDeclaration.getAST();
TryStatement tryStatement= (TryStatement) catchClause.getParent();
if (tryStatement.catchClauses().size() > 1 || tryStatement.getFinally() != null) {
rewrite.markAsRemoved(catchClause);
} else {
List statements= tryStatement.getBody().statements();
if (statements.size() > 0) {
ASTNode placeholder= rewrite.createCopy((ASTNode) statements.get(0), (ASTNode) statements.get(statements.size() - 1));
rewrite.markAsReplaced(tryStatement, placeholder);
} else {
rewrite.markAsRemoved(tryStatement);
}
}
Name name= ((SimpleType) type).getName();
Name newName= (Name) ASTNode.copySubtree(ast, name);
rewrite.markAsInserted(newName);
methodDeclaration.thrownExceptions().add(newName);
String label= CorrectionMessages.getString("QuickAssistProcessor.catchclausetothrows.description");
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 1, image);
proposal.ensureNoModifications();
resultingCollections.add(proposal);
}
private void getRenameLocalProposals(ICorrectionContext context, List resultingCollections) throws CoreException {
ASTNode node= context.getCoveringNode();
if (!(node instanceof SimpleName)) {
return;
}
SimpleName name= (SimpleName) node;
IBinding binding= name.resolveBinding();
if (binding == null || binding.getKind() == IBinding.PACKAGE) {
return;
}
LinkedNamesAssistProposal proposal= new LinkedNamesAssistProposal(name);
resultingCollections.add(proposal);
}
}
|
26,306 |
Bug 26306 Quick assist offers rename on expression
|
Build I20021113 - open TestCase.toString - select name()+"("+getClass().getName()+")" - open quick assist ==> offers rename (surprisingly) and not new local
|
resolved fixed
|
6549d92
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-25T17:48:18Z | 2002-11-14T16:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/JavaCorrectionAssistant.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.Iterator;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DefaultInformationControl;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IInformationControl;
import org.eclipse.jface.text.IInformationControlCreator;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.contentassist.ContentAssistant;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.util.Assert;
import org.eclipse.ui.IEditorPart;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.text.IColorManager;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.javaeditor.IProblemAnnotation;
import org.eclipse.jdt.internal.ui.javaeditor.ProblemAnnotationIterator;
import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter;
import org.eclipse.jdt.internal.ui.text.JavaPartitionScanner;
public class JavaCorrectionAssistant extends ContentAssistant {
private ITextViewer fViewer;
private IEditorPart fEditor;
private Position fPosition;
/**
* Constructor for CorrectionAssistant.
*/
public JavaCorrectionAssistant(IEditorPart editor) {
super();
Assert.isNotNull(editor);
fEditor= editor;
JavaCorrectionProcessor processor= new JavaCorrectionProcessor(editor);
setContentAssistProcessor(processor, IDocument.DEFAULT_CONTENT_TYPE);
setContentAssistProcessor(processor, JavaPartitionScanner.JAVA_STRING);
enableAutoActivation(false);
enableAutoInsert(false);
setContextInformationPopupOrientation(CONTEXT_INFO_ABOVE);
setInformationControlCreator(getInformationControlCreator());
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
IColorManager manager= textTools.getColorManager();
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
Color c= getColor(store, PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND, manager);
setProposalSelectorForeground(c);
c= getColor(store, PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND, manager);
setProposalSelectorBackground(c);
}
private IInformationControlCreator getInformationControlCreator() {
return new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell parent) {
return new DefaultInformationControl(parent, new HTMLTextPresenter());
}
};
}
private static Color getColor(IPreferenceStore store, String key, IColorManager manager) {
RGB rgb= PreferenceConverter.getColor(store, key);
return manager.getColor(rgb);
}
public void install(ITextViewer textViewer) {
super.install(textViewer);
fViewer= textViewer;
}
/**
* Show completions at caret position. If current
* position does not contain quick fixes look for
* next quick fix on same line by moving from left
* to right and restarting at end of line if the
* beginning of the line is reached.
*
* @see org.eclipse.jface.text.contentassist.IContentAssistant#showPossibleCompletions()
*/
public String showPossibleCompletions() {
if (fViewer == null)
// Let superclass deal with this
return super.showPossibleCompletions();
int initalOffset= fViewer.getSelectedRange().x;
int invocationOffset= computeOffsetWithCorrection(initalOffset);
storePosition();
fViewer.setSelectedRange(invocationOffset, 0);
fViewer.revealRange(invocationOffset, 0);
String errorMsg= super.showPossibleCompletions();
return errorMsg;
}
/**
* Find offset which contains corrections.
* Search on same line by moving from left
* to right and restarting at end of line if the
* beginning of the line is reached.
*
* @return an offset where corrections are available or initalOffset if none
*/
private int computeOffsetWithCorrection(int initalOffset) {
if (fViewer == null || fViewer.getDocument() == null)
return initalOffset;
IRegion lineInfo= null;
try {
lineInfo= fViewer.getDocument().getLineInformationOfOffset(initalOffset);
} catch (BadLocationException ex) {
return initalOffset;
}
int startOffset= lineInfo.getOffset();
int endOffset= startOffset + lineInfo.getLength();
int result= computeOffsetWithCorrection(startOffset, endOffset, initalOffset);
if (result > 0)
return result;
else
return initalOffset;
}
/**
* @return the best matching offset with corrections or -1 if nothing is found
*/
private int computeOffsetWithCorrection(int startOffset, int endOffset, int offset) {
IAnnotationModel model= JavaUI.getDocumentProvider().getAnnotationModel(fEditor.getEditorInput());
int invocationOffset= -1;
Iterator iter= new ProblemAnnotationIterator(model, true);
while (iter.hasNext()) {
IProblemAnnotation annot= (IProblemAnnotation)iter.next();
Position pos= model.getPosition((Annotation)annot);
if (isIncluded(pos, startOffset, endOffset)) {
if (JavaCorrectionProcessor.hasCorrections(annot)) {
invocationOffset= computeBestOffset(invocationOffset, pos, offset);
}
}
}
return invocationOffset;
}
private boolean isIncluded(Position pos, int lineStart, int lineEnd) {
return (pos != null) && (pos.getOffset() >= lineStart && (pos.getOffset() + pos.getLength() <= lineEnd));
}
/**
* Computes and returns the invocation offset given a new
* position, the initial offset and the best invocation offset
* found so far.
* <p>
* The closest offset to the left of the initial offset is the
* best. If there is no offset on the left, the closest on the
* right is the best.</p>
*/
private int computeBestOffset(int invocationOffset, Position pos, int initalOffset) {
int newOffset= pos.offset;
if (newOffset <= initalOffset && initalOffset <= newOffset + pos.length)
return initalOffset;
if (invocationOffset < 0)
return newOffset;
if (newOffset <= initalOffset && invocationOffset >= initalOffset)
return newOffset;
if (newOffset <= initalOffset && invocationOffset < initalOffset)
return Math.max(invocationOffset, newOffset);;
if (invocationOffset <= initalOffset)
return invocationOffset;
return Math.max(invocationOffset, newOffset);
}
/*
* @see org.eclipse.jface.text.contentassist.ContentAssistant#possibleCompletionsClosed()
*/
protected void possibleCompletionsClosed() {
super.possibleCompletionsClosed();
restorePosition();
}
private void storePosition() {
int initalOffset= fViewer.getSelectedRange().x;
int length= fViewer.getSelectedRange().y;
fPosition= new Position(initalOffset, length);
}
private void restorePosition() {
if (fPosition != null && !fPosition.isDeleted()) {
fViewer.setSelectedRange(fPosition.offset, fPosition.length);
fViewer.revealRange(fPosition.offset, fPosition.length);
}
fPosition= null;
}
}
|
26,265 |
Bug 26265 No busy cursor when selecting type in type hierarchy [type hierarchy]
|
Build 20021113 - load JUnit - create hierarchy for TestCase - enlarge size of TestCase.java by duplicating methods - select Object in hierarchy - select TextCase in hierarchy observe: you don't get a busy cursor. IDE looks froozen.
|
resolved fixed
|
4aa9aba
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-26T09:14:00Z | 2002-11-14T10:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/TypeHierarchyViewPart.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.typehierarchy;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.ViewForm;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.AbstractTreeViewer;
import org.eclipse.jface.viewers.IBasicPropertyConstants;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.actions.OpenWithMenu;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.PageBook;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.ITypeHierarchyViewPart;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.actions.CCPActionGroup;
import org.eclipse.jdt.ui.actions.GenerateActionGroup;
import org.eclipse.jdt.ui.actions.JavaSearchActionGroup;
import org.eclipse.jdt.ui.actions.OpenEditorActionGroup;
import org.eclipse.jdt.ui.actions.OpenViewActionGroup;
import org.eclipse.jdt.ui.actions.RefactorActionGroup;
import org.eclipse.jdt.ui.actions.ShowActionGroup;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.AddMethodStubAction;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.actions.NewWizardsActionGroup;
import org.eclipse.jdt.internal.ui.actions.SelectAllAction;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter;
import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer;
import org.eclipse.jdt.internal.ui.dnd.TransferDragSourceListener;
import org.eclipse.jdt.internal.ui.dnd.TransferDropTargetListener;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.packageview.SelectionTransferDragAdapter;
import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
import org.eclipse.jdt.internal.ui.viewsupport.JavaUILabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater;
/**
* view showing the supertypes/subtypes of its input.
*/
public class TypeHierarchyViewPart extends ViewPart implements ITypeHierarchyViewPart, IViewPartInputProvider {
public static final int VIEW_ID_TYPE= 2;
public static final int VIEW_ID_SUPER= 0;
public static final int VIEW_ID_SUB= 1;
public static final int VIEW_ORIENTATION_VERTICAL= 0;
public static final int VIEW_ORIENTATION_HORIZONTAL= 1;
public static final int VIEW_ORIENTATION_SINGLE= 2;
private static final String DIALOGSTORE_HIERARCHYVIEW= "TypeHierarchyViewPart.hierarchyview"; //$NON-NLS-1$
private static final String DIALOGSTORE_VIEWORIENTATION= "TypeHierarchyViewPart.orientation"; //$NON-NLS-1$
private static final String TAG_INPUT= "input"; //$NON-NLS-1$
private static final String TAG_VIEW= "view"; //$NON-NLS-1$
private static final String TAG_ORIENTATION= "orientation"; //$NON-NLS-1$
private static final String TAG_RATIO= "ratio"; //$NON-NLS-1$
private static final String TAG_SELECTION= "selection"; //$NON-NLS-1$
private static final String TAG_VERTICAL_SCROLL= "vertical_scroll"; //$NON-NLS-1$
private static final String GROUP_FOCUS= "group.focus"; //$NON-NLS-1$
// the selected type in the hierarchy view
private IType fSelectedType;
// input element or null
private IJavaElement fInputElement;
// history of inut elements. No duplicates
private ArrayList fInputHistory;
private IMemento fMemento;
private TypeHierarchyLifeCycle fHierarchyLifeCycle;
private ITypeHierarchyLifeCycleListener fTypeHierarchyLifeCycleListener;
private IPropertyChangeListener fPropertyChangeListener;
private MethodsViewer fMethodsViewer;
private int fCurrentViewerIndex;
private TypeHierarchyViewer[] fAllViewers;
private SelectionProviderMediator fSelectionProviderMediator;
private ISelectionChangedListener fSelectionChangedListener;
private boolean fIsEnableMemberFilter;
private SashForm fTypeMethodsSplitter;
private PageBook fViewerbook;
private PageBook fPagebook;
private Label fNoHierarchyShownLabel;
private Label fEmptyTypesViewer;
private ViewForm fTypeViewerViewForm;
private ViewForm fMethodViewerViewForm;
private CLabel fMethodViewerPaneLabel;
private JavaUILabelProvider fPaneLabelProvider;
private IDialogSettings fDialogSettings;
private ToggleViewAction[] fViewActions;
private HistoryDropDownAction fHistoryDropDownAction;
private ToggleOrientationAction[] fToggleOrientationActions;
private int fCurrentOrientation;
private EnableMemberFilterAction fEnableMemberFilterAction;
private AddMethodStubAction fAddStubAction;
private FocusOnTypeAction fFocusOnTypeAction;
private FocusOnSelectionAction fFocusOnSelectionAction;
private IPartListener fPartListener;
private CompositeActionGroup fActionGroups;
private CCPActionGroup fCCPActionGroup;
private SelectAllAction fSelectAllAction;
public TypeHierarchyViewPart() {
fSelectedType= null;
fInputElement= null;
boolean isReconciled= PreferenceConstants.UPDATE_WHILE_EDITING.equals(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.UPDATE_JAVA_VIEWS));
fHierarchyLifeCycle= new TypeHierarchyLifeCycle();
fHierarchyLifeCycle.setReconciled(isReconciled);
fTypeHierarchyLifeCycleListener= new ITypeHierarchyLifeCycleListener() {
public void typeHierarchyChanged(TypeHierarchyLifeCycle typeHierarchy, IType[] changedTypes) {
doTypeHierarchyChanged(typeHierarchy, changedTypes);
}
};
fHierarchyLifeCycle.addChangedListener(fTypeHierarchyLifeCycleListener);
fPropertyChangeListener= new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
doPropertyChange(event);
}
};
JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(fPropertyChangeListener);
fIsEnableMemberFilter= false;
fInputHistory= new ArrayList();
fAllViewers= null;
fViewActions= new ToggleViewAction[] {
new ToggleViewAction(this, VIEW_ID_TYPE),
new ToggleViewAction(this, VIEW_ID_SUPER),
new ToggleViewAction(this, VIEW_ID_SUB)
};
fDialogSettings= JavaPlugin.getDefault().getDialogSettings();
fHistoryDropDownAction= new HistoryDropDownAction(this);
fHistoryDropDownAction.setEnabled(false);
fToggleOrientationActions= new ToggleOrientationAction[] {
new ToggleOrientationAction(this, VIEW_ORIENTATION_VERTICAL),
new ToggleOrientationAction(this, VIEW_ORIENTATION_HORIZONTAL),
new ToggleOrientationAction(this, VIEW_ORIENTATION_SINGLE)
};
fEnableMemberFilterAction= new EnableMemberFilterAction(this, false);
fFocusOnTypeAction= new FocusOnTypeAction(this);
fPaneLabelProvider= new JavaUILabelProvider();
fAddStubAction= new AddMethodStubAction();
fFocusOnSelectionAction= new FocusOnSelectionAction(this);
fPartListener= new IPartListener() {
public void partActivated(IWorkbenchPart part) {
if (part instanceof IEditorPart)
editorActivated((IEditorPart) part);
}
public void partBroughtToTop(IWorkbenchPart part) {}
public void partClosed(IWorkbenchPart part) {}
public void partDeactivated(IWorkbenchPart part) {}
public void partOpened(IWorkbenchPart part) {}
};
fSelectionChangedListener= new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
doSelectionChanged(event);
}
};
}
/**
* Method doPropertyChange.
* @param event
*/
private void doPropertyChange(PropertyChangeEvent event) {
if (fMethodsViewer != null) {
if (PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER.equals(event.getProperty())) {
fMethodsViewer.refresh();
}
}
}
/**
* Adds the entry if new. Inserted at the beginning of the history entries list.
*/
private void addHistoryEntry(IJavaElement entry) {
if (fInputHistory.contains(entry)) {
fInputHistory.remove(entry);
}
fInputHistory.add(0, entry);
fHistoryDropDownAction.setEnabled(true);
}
private void updateHistoryEntries() {
for (int i= fInputHistory.size() - 1; i >= 0; i--) {
IJavaElement type= (IJavaElement) fInputHistory.get(i);
if (!type.exists()) {
fInputHistory.remove(i);
}
}
fHistoryDropDownAction.setEnabled(!fInputHistory.isEmpty());
}
/**
* Goes to the selected entry, without updating the order of history entries.
*/
public void gotoHistoryEntry(IJavaElement entry) {
if (fInputHistory.contains(entry)) {
updateInput(entry);
}
}
/**
* Gets all history entries.
*/
public IJavaElement[] getHistoryEntries() {
if (fInputHistory.size() > 0) {
updateHistoryEntries();
}
return (IJavaElement[]) fInputHistory.toArray(new IJavaElement[fInputHistory.size()]);
}
/**
* Sets the history entries
*/
public void setHistoryEntries(IJavaElement[] elems) {
fInputHistory.clear();
for (int i= 0; i < elems.length; i++) {
fInputHistory.add(elems[i]);
}
updateHistoryEntries();
}
/**
* Selects an member in the methods list or in the current hierarchy.
*/
public void selectMember(IMember member) {
ICompilationUnit cu= member.getCompilationUnit();
if (cu != null && cu.isWorkingCopy()) {
member= (IMember) cu.getOriginal(member);
if (member == null) {
return;
}
}
if (member.getElementType() != IJavaElement.TYPE) {
if (fHierarchyLifeCycle.isReconciled() && cu != null) {
try {
member= (IMember) EditorUtility.getWorkingCopy(member);
if (member == null) {
return;
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
return;
}
}
Control methodControl= fMethodsViewer.getControl();
if (methodControl != null && !methodControl.isDisposed()) {
methodControl.setFocus();
}
fMethodsViewer.setSelection(new StructuredSelection(member), true);
} else {
Control viewerControl= getCurrentViewer().getControl();
if (viewerControl != null && !viewerControl.isDisposed()) {
viewerControl.setFocus();
}
getCurrentViewer().setSelection(new StructuredSelection(member), true);
}
}
/**
* @deprecated
*/
public IType getInput() {
if (fInputElement instanceof IType) {
return (IType) fInputElement;
}
return null;
}
/**
* Sets the input to a new type
* @deprecated
*/
public void setInput(IType type) {
setInputElement(type);
}
/**
* Returns the input element of the type hierarchy.
* Can be of type <code>IType</code> or <code>IPackageFragment</code>
*/
public IJavaElement getInputElement() {
return fInputElement;
}
/**
* Sets the input to a new element.
*/
public void setInputElement(IJavaElement element) {
if (element != null) {
if (element instanceof IMember) {
if (element.getElementType() != IJavaElement.TYPE) {
element= ((IMember) element).getDeclaringType();
}
ICompilationUnit cu= ((IMember) element).getCompilationUnit();
if (cu != null && cu.isWorkingCopy()) {
element= cu.getOriginal(element);
if (!element.exists()) {
MessageDialog.openError(getSite().getShell(), TypeHierarchyMessages.getString("TypeHierarchyViewPart.error.title"), TypeHierarchyMessages.getString("TypeHierarchyViewPart.error.message")); //$NON-NLS-1$ //$NON-NLS-2$
return;
}
}
} else {
int kind= element.getElementType();
if (kind != IJavaElement.JAVA_PROJECT && kind != IJavaElement.PACKAGE_FRAGMENT_ROOT && kind != IJavaElement.PACKAGE_FRAGMENT) {
element= null;
JavaPlugin.logErrorMessage("Invalid type hierarchy input type.");//$NON-NLS-1$
}
}
}
if (element != null && !element.equals(fInputElement)) {
addHistoryEntry(element);
}
updateInput(element);
}
/**
* Changes the input to a new type
*/
private void updateInput(IJavaElement inputElement) {
IJavaElement prevInput= fInputElement;
fInputElement= inputElement;
if (fInputElement == null) {
clearInput();
} else {
try {
fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(fInputElement, new BusyIndicatorRunnableContext());
} catch (JavaModelException e) {
JavaPlugin.log(e);
clearInput();
return;
}
fPagebook.showPage(fTypeMethodsSplitter);
if (inputElement.getElementType() != IJavaElement.TYPE) {
setView(VIEW_ID_TYPE);
}
// turn off member filtering
setMemberFilter(null);
fIsEnableMemberFilter= false;
if (!fInputElement.equals(prevInput)) {
updateHierarchyViewer();
}
IType root= getSelectableType(fInputElement);
internalSelectType(root, true);
updateMethodViewer(root);
updateToolbarButtons();
updateTitle();
enableMemberFilter(false);
}
}
private void clearInput() {
fInputElement= null;
fHierarchyLifeCycle.freeHierarchy();
updateHierarchyViewer();
updateToolbarButtons();
}
/*
* @see IWorbenchPart#setFocus
*/
public void setFocus() {
fPagebook.setFocus();
}
/*
* @see IWorkbenchPart#dispose
*/
public void dispose() {
fHierarchyLifeCycle.freeHierarchy();
fHierarchyLifeCycle.removeChangedListener(fTypeHierarchyLifeCycleListener);
fPaneLabelProvider.dispose();
fMethodsViewer.dispose();
if (fPropertyChangeListener != null) {
JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener);
fPropertyChangeListener= null;
}
getSite().getPage().removePartListener(fPartListener);
if (fActionGroups != null)
fActionGroups.dispose();
super.dispose();
}
private Control createTypeViewerControl(Composite parent) {
fViewerbook= new PageBook(parent, SWT.NULL);
KeyListener keyListener= createKeyListener();
// Create the viewers
TypeHierarchyViewer superTypesViewer= new SuperTypeHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this);
initializeTypesViewer(superTypesViewer, keyListener, IContextMenuConstants.TARGET_ID_SUPERTYPES_VIEW);
TypeHierarchyViewer subTypesViewer= new SubTypeHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this);
initializeTypesViewer(subTypesViewer, keyListener, IContextMenuConstants.TARGET_ID_SUBTYPES_VIEW);
TypeHierarchyViewer vajViewer= new TraditionalHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this);
initializeTypesViewer(vajViewer, keyListener, IContextMenuConstants.TARGET_ID_HIERARCHY_VIEW);
fAllViewers= new TypeHierarchyViewer[3];
fAllViewers[VIEW_ID_SUPER]= superTypesViewer;
fAllViewers[VIEW_ID_SUB]= subTypesViewer;
fAllViewers[VIEW_ID_TYPE]= vajViewer;
int currViewerIndex;
try {
currViewerIndex= fDialogSettings.getInt(DIALOGSTORE_HIERARCHYVIEW);
if (currViewerIndex < 0 || currViewerIndex > 2) {
currViewerIndex= VIEW_ID_TYPE;
}
} catch (NumberFormatException e) {
currViewerIndex= VIEW_ID_TYPE;
}
fEmptyTypesViewer= new Label(fViewerbook, SWT.LEFT);
for (int i= 0; i < fAllViewers.length; i++) {
fAllViewers[i].setInput(fAllViewers[i]);
}
// force the update
fCurrentViewerIndex= -1;
setView(currViewerIndex);
return fViewerbook;
}
private KeyListener createKeyListener() {
return new KeyAdapter() {
public void keyReleased(KeyEvent event) {
if (event.stateMask == 0) {
if (event.keyCode == SWT.F5) {
updateHierarchyViewer();
return;
} else if (event.character == SWT.DEL){
if (fCCPActionGroup.getDeleteAction().isEnabled())
fCCPActionGroup.getDeleteAction().run();
return;
}
}
viewPartKeyShortcuts(event);
}
};
}
private void initializeTypesViewer(final TypeHierarchyViewer typesViewer, KeyListener keyListener, String cotextHelpId) {
typesViewer.getControl().setVisible(false);
typesViewer.getControl().addKeyListener(keyListener);
typesViewer.initContextMenu(new IMenuListener() {
public void menuAboutToShow(IMenuManager menu) {
fillTypesViewerContextMenu(typesViewer, menu);
}
}, cotextHelpId, getSite());
typesViewer.addSelectionChangedListener(fSelectionChangedListener);
}
private Control createMethodViewerControl(Composite parent) {
fMethodsViewer= new MethodsViewer(parent, fHierarchyLifeCycle, this);
fMethodsViewer.initContextMenu(new IMenuListener() {
public void menuAboutToShow(IMenuManager menu) {
fillMethodsViewerContextMenu(menu);
}
}, IContextMenuConstants.TARGET_ID_MEMBERS_VIEW, getSite());
fMethodsViewer.addSelectionChangedListener(fSelectionChangedListener);
Control control= fMethodsViewer.getTable();
control.addKeyListener(createKeyListener());
return control;
}
private void initDragAndDrop() {
Transfer[] transfers= new Transfer[] { LocalSelectionTransfer.getInstance() };
int ops= DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK;
for (int i= 0; i < fAllViewers.length; i++) {
addDragAdapters(fAllViewers[i], ops, transfers);
addDropAdapters(fAllViewers[i], ops | DND.DROP_DEFAULT, transfers);
}
addDragAdapters(fMethodsViewer, ops, transfers);
//dnd on empty hierarchy
DropTarget dropTarget = new DropTarget(fNoHierarchyShownLabel, ops | DND.DROP_DEFAULT);
dropTarget.setTransfer(transfers);
dropTarget.addDropListener(new TypeHierarchyTransferDropAdapter(this, fAllViewers[0]));
}
private void addDropAdapters(AbstractTreeViewer viewer, int ops, Transfer[] transfers){
TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] {
new TypeHierarchyTransferDropAdapter(this, viewer)
};
viewer.addDropSupport(ops, transfers, new DelegatingDropAdapter(dropListeners));
}
private void addDragAdapters(StructuredViewer viewer, int ops, Transfer[] transfers){
Control control= viewer.getControl();
TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
new SelectionTransferDragAdapter(viewer)
};
DragSource source= new DragSource(control, ops);
// Note, that the transfer agents are set by the delegating drag adapter itself.
source.addDragListener(new DelegatingDragAdapter(dragListeners));
}
private void viewPartKeyShortcuts(KeyEvent event) {
if (event.stateMask == SWT.CTRL) {
if (event.character == '1') {
setView(VIEW_ID_TYPE);
} else if (event.character == '2') {
setView(VIEW_ID_SUPER);
} else if (event.character == '3') {
setView(VIEW_ID_SUB);
}
}
}
/**
* Returns the inner component in a workbench part.
* @see IWorkbenchPart#createPartControl
*/
public void createPartControl(Composite container) {
fPagebook= new PageBook(container, SWT.NONE);
// page 1 of pagebook (viewers)
fTypeMethodsSplitter= new SashForm(fPagebook, SWT.VERTICAL);
fTypeMethodsSplitter.setVisible(false);
fTypeViewerViewForm= new ViewForm(fTypeMethodsSplitter, SWT.NONE);
Control typeViewerControl= createTypeViewerControl(fTypeViewerViewForm);
fTypeViewerViewForm.setContent(typeViewerControl);
fMethodViewerViewForm= new ViewForm(fTypeMethodsSplitter, SWT.NONE);
fTypeMethodsSplitter.setWeights(new int[] {35, 65});
Control methodViewerPart= createMethodViewerControl(fMethodViewerViewForm);
fMethodViewerViewForm.setContent(methodViewerPart);
fMethodViewerPaneLabel= new CLabel(fMethodViewerViewForm, SWT.NONE);
fMethodViewerViewForm.setTopLeft(fMethodViewerPaneLabel);
ToolBar methodViewerToolBar= new ToolBar(fMethodViewerViewForm, SWT.FLAT | SWT.WRAP);
fMethodViewerViewForm.setTopCenter(methodViewerToolBar);
// page 2 of pagebook (no hierarchy label)
fNoHierarchyShownLabel= new Label(fPagebook, SWT.TOP + SWT.LEFT + SWT.WRAP);
fNoHierarchyShownLabel.setText(TypeHierarchyMessages.getString("TypeHierarchyViewPart.empty")); //$NON-NLS-1$
MenuManager menu= new MenuManager();
menu.add(fFocusOnTypeAction);
fNoHierarchyShownLabel.setMenu(menu.createContextMenu(fNoHierarchyShownLabel));
fPagebook.showPage(fNoHierarchyShownLabel);
int orientation;
try {
orientation= fDialogSettings.getInt(DIALOGSTORE_VIEWORIENTATION);
if (orientation < 0 || orientation > 2) {
orientation= VIEW_ORIENTATION_VERTICAL;
}
} catch (NumberFormatException e) {
orientation= VIEW_ORIENTATION_VERTICAL;
}
// force the update
fCurrentOrientation= -1;
// will fill the main tool bar
setOrientation(orientation);
// set the filter menu items
IActionBars actionBars= getViewSite().getActionBars();
IMenuManager viewMenu= actionBars.getMenuManager();
for (int i= 0; i < fToggleOrientationActions.length; i++) {
viewMenu.add(fToggleOrientationActions[i]);
}
viewMenu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
// fill the method viewer toolbar
ToolBarManager lowertbmanager= new ToolBarManager(methodViewerToolBar);
lowertbmanager.add(fEnableMemberFilterAction);
lowertbmanager.add(new Separator());
fMethodsViewer.contributeToToolBar(lowertbmanager);
lowertbmanager.update(true);
// selection provider
int nHierarchyViewers= fAllViewers.length;
Viewer[] trackedViewers= new Viewer[nHierarchyViewers + 1];
for (int i= 0; i < nHierarchyViewers; i++) {
trackedViewers[i]= fAllViewers[i];
}
trackedViewers[nHierarchyViewers]= fMethodsViewer;
fSelectionProviderMediator= new SelectionProviderMediator(trackedViewers);
IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager();
fSelectionProviderMediator.addSelectionChangedListener(new StatusBarUpdater(slManager));
getSite().setSelectionProvider(fSelectionProviderMediator);
getSite().getPage().addPartListener(fPartListener);
IJavaElement input= determineInputElement();
if (fMemento != null) {
restoreState(fMemento, input);
} else if (input != null) {
setInputElement(input);
} else {
setViewerVisibility(false);
}
WorkbenchHelp.setHelp(fPagebook, IJavaHelpContextIds.TYPE_HIERARCHY_VIEW);
fActionGroups= new CompositeActionGroup(new ActionGroup[] {
new NewWizardsActionGroup(this.getSite()),
new OpenEditorActionGroup(this),
new OpenViewActionGroup(this),
new ShowActionGroup(this),
fCCPActionGroup= new CCPActionGroup(this),
new RefactorActionGroup(this),
new GenerateActionGroup(this),
new JavaSearchActionGroup(this)});
fActionGroups.fillActionBars(actionBars);
fSelectAllAction= new SelectAllAction(fMethodsViewer);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.SELECT_ALL, fSelectAllAction);
initDragAndDrop();
}
/**
* called from ToggleOrientationAction.
* @param orientation VIEW_ORIENTATION_SINGLE, VIEW_ORIENTATION_HORIZONTAL or VIEW_ORIENTATION_VERTICAL
*/
public void setOrientation(int orientation) {
if (fCurrentOrientation != orientation) {
boolean methodViewerNeedsUpdate= false;
if (fMethodViewerViewForm != null && !fMethodViewerViewForm.isDisposed()
&& fTypeMethodsSplitter != null && !fTypeMethodsSplitter.isDisposed()) {
if (orientation == VIEW_ORIENTATION_SINGLE) {
fMethodViewerViewForm.setVisible(false);
enableMemberFilter(false);
updateMethodViewer(null);
} else {
if (fCurrentOrientation == VIEW_ORIENTATION_SINGLE) {
fMethodViewerViewForm.setVisible(true);
methodViewerNeedsUpdate= true;
}
boolean horizontal= orientation == VIEW_ORIENTATION_HORIZONTAL;
fTypeMethodsSplitter.setOrientation(horizontal ? SWT.HORIZONTAL : SWT.VERTICAL);
}
updateMainToolbar(orientation);
fTypeMethodsSplitter.layout();
}
for (int i= 0; i < fToggleOrientationActions.length; i++) {
fToggleOrientationActions[i].setChecked(orientation == fToggleOrientationActions[i].getOrientation());
}
fCurrentOrientation= orientation;
if (methodViewerNeedsUpdate) {
updateMethodViewer(fSelectedType);
}
fDialogSettings.put(DIALOGSTORE_VIEWORIENTATION, orientation);
}
}
private void updateMainToolbar(int orientation) {
IActionBars actionBars= getViewSite().getActionBars();
IToolBarManager tbmanager= actionBars.getToolBarManager();
if (orientation == VIEW_ORIENTATION_HORIZONTAL) {
clearMainToolBar(tbmanager);
ToolBar typeViewerToolBar= new ToolBar(fTypeViewerViewForm, SWT.FLAT | SWT.WRAP);
fillMainToolBar(new ToolBarManager(typeViewerToolBar));
fTypeViewerViewForm.setTopLeft(typeViewerToolBar);
} else {
fTypeViewerViewForm.setTopLeft(null);
fillMainToolBar(tbmanager);
}
}
private void fillMainToolBar(IToolBarManager tbmanager) {
tbmanager.removeAll();
tbmanager.add(fHistoryDropDownAction);
for (int i= 0; i < fViewActions.length; i++) {
tbmanager.add(fViewActions[i]);
}
tbmanager.update(false);
}
private void clearMainToolBar(IToolBarManager tbmanager) {
tbmanager.removeAll();
tbmanager.update(false);
}
/**
* Creates the context menu for the hierarchy viewers
*/
private void fillTypesViewerContextMenu(TypeHierarchyViewer viewer, IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, new Separator(GROUP_FOCUS));
// viewer entries
viewer.contributeToContextMenu(menu);
if (fFocusOnSelectionAction.canActionBeAdded())
menu.appendToGroup(GROUP_FOCUS, fFocusOnSelectionAction);
menu.appendToGroup(GROUP_FOCUS, fFocusOnTypeAction);
fActionGroups.setContext(new ActionContext(getSite().getSelectionProvider().getSelection()));
fActionGroups.fillContextMenu(menu);
fActionGroups.setContext(null);
}
/**
* Creates the context menu for the method viewer
*/
private void fillMethodsViewerContextMenu(IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
// viewer entries
fMethodsViewer.contributeToContextMenu(menu);
if (fSelectedType != null && fAddStubAction.init(fSelectedType, fMethodsViewer.getSelection())) {
menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, fAddStubAction);
}
fActionGroups.setContext(new ActionContext(getSite().getSelectionProvider().getSelection()));
fActionGroups.fillContextMenu(menu);
fActionGroups.setContext(null);
// //menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, new JavaReplaceWithEditionAction(fMethodsViewer));
// addOpenWithMenu(menu, (IStructuredSelection)fMethodsViewer.getSelection());
// ContextMenuGroup.add(menu, new ContextMenuGroup[] { new BuildGroup(this, false)}, fMethodsViewer);
//
// // XXX workaround until we have fully converted the code to use the new action groups
// fActionGroups.get(2).fillContextMenu(menu);
// fActionGroups.get(3).fillContextMenu(menu);
// fActionGroups.get(4).fillContextMenu(menu);
}
private void addOpenWithMenu(IMenuManager menu, IStructuredSelection selection) {
// If one file is selected get it.
// Otherwise, do not show the "open with" menu.
if (selection.size() != 1)
return;
Object element= selection.getFirstElement();
if (!(element instanceof IJavaElement))
return;
IJavaElement openable= (IJavaElement) ((IJavaElement) element).getOpenable();
IResource resource= openable.getResource();
if (!(resource instanceof IFile))
return;
// Create a menu flyout.
MenuManager submenu= new MenuManager(TypeHierarchyMessages.getString("TypeHierarchyViewPart.menu.open")); //$NON-NLS-1$
submenu.add(new OpenWithMenu(getSite().getPage(), (IFile) resource));
// Add the submenu.
menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, submenu);
}
/**
* Toggles between the empty viewer page and the hierarchy
*/
private void setViewerVisibility(boolean showHierarchy) {
if (showHierarchy) {
fViewerbook.showPage(getCurrentViewer().getControl());
} else {
fViewerbook.showPage(fEmptyTypesViewer);
}
}
/**
* Sets the member filter. <code>null</code> disables member filtering.
*/
private void setMemberFilter(IMember[] memberFilter) {
Assert.isNotNull(fAllViewers);
for (int i= 0; i < fAllViewers.length; i++) {
fAllViewers[i].setMemberFilter(memberFilter);
}
}
private IType getSelectableType(IJavaElement elem) {
if (elem.getElementType() != IJavaElement.TYPE) {
return null; //(IType) getCurrentViewer().getTreeRootType();
} else {
return (IType) elem;
}
}
private void internalSelectType(IMember elem, boolean reveal) {
TypeHierarchyViewer viewer= getCurrentViewer();
viewer.removeSelectionChangedListener(fSelectionChangedListener);
viewer.setSelection(elem != null ? new StructuredSelection(elem) : StructuredSelection.EMPTY, reveal);
viewer.addSelectionChangedListener(fSelectionChangedListener);
}
private void internalSelectMember(IMember member) {
fMethodsViewer.removeSelectionChangedListener(fSelectionChangedListener);
fMethodsViewer.setSelection(member != null ? new StructuredSelection(member) : StructuredSelection.EMPTY);
fMethodsViewer.addSelectionChangedListener(fSelectionChangedListener);
}
/**
* When the input changed or the hierarchy pane becomes visible,
* <code>updateHierarchyViewer<code> brings up the correct view and refreshes
* the current tree
*/
private void updateHierarchyViewer() {
if (fInputElement == null) {
fPagebook.showPage(fNoHierarchyShownLabel);
} else {
if (getCurrentViewer().containsElements() != null) {
Runnable runnable= new Runnable() {
public void run() {
getCurrentViewer().updateContent(); // refresh
}
};
BusyIndicator.showWhile(getDisplay(), runnable);
if (!isChildVisible(fViewerbook, getCurrentViewer().getControl())) {
setViewerVisibility(true);
}
} else {
fEmptyTypesViewer.setText(TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.nodecl", fInputElement.getElementName())); //$NON-NLS-1$
setViewerVisibility(false);
}
}
}
private void updateMethodViewer(IType input) {
if (!fIsEnableMemberFilter && fCurrentOrientation != VIEW_ORIENTATION_SINGLE) {
if (input == fMethodsViewer.getInput()) {
if (input != null) {
fMethodsViewer.refresh();
}
} else if (input != null) {
fMethodViewerPaneLabel.setText(fPaneLabelProvider.getText(input));
fMethodViewerPaneLabel.setImage(fPaneLabelProvider.getImage(input));
} else {
fMethodViewerPaneLabel.setText(""); //$NON-NLS-1$
fMethodViewerPaneLabel.setImage(null);
}
fMethodsViewer.setInput(input);
}
}
private void doSelectionChanged(SelectionChangedEvent e) {
if (e.getSelectionProvider() == fMethodsViewer) {
methodSelectionChanged(e.getSelection());
fSelectAllAction.setEnabled(true);
} else {
typeSelectionChanged(e.getSelection());
fSelectAllAction.setEnabled(false);
}
}
private void methodSelectionChanged(ISelection sel) {
if (sel instanceof IStructuredSelection) {
List selected= ((IStructuredSelection)sel).toList();
int nSelected= selected.size();
if (fIsEnableMemberFilter) {
IMember[] memberFilter= null;
if (nSelected > 0) {
memberFilter= new IMember[nSelected];
selected.toArray(memberFilter);
}
setMemberFilter(memberFilter);
updateHierarchyViewer();
updateTitle();
internalSelectType(fSelectedType, true);
}
if (nSelected == 1) {
revealElementInEditor(selected.get(0), fMethodsViewer);
}
}
}
private void typeSelectionChanged(ISelection sel) {
if (sel instanceof IStructuredSelection) {
List selected= ((IStructuredSelection)sel).toList();
int nSelected= selected.size();
if (nSelected != 0) {
List types= new ArrayList(nSelected);
for (int i= nSelected-1; i >= 0; i--) {
Object elem= selected.get(i);
if (elem instanceof IType && !types.contains(elem)) {
types.add(elem);
}
}
if (types.size() == 1) {
fSelectedType= (IType) types.get(0);
updateMethodViewer(fSelectedType);
} else if (types.size() == 0) {
// method selected, no change
}
if (nSelected == 1) {
revealElementInEditor(selected.get(0), getCurrentViewer());
}
} else {
fSelectedType= null;
updateMethodViewer(null);
}
}
}
private void revealElementInEditor(Object elem, Viewer originViewer) {
// only allow revealing when the type hierarchy is the active pagae
// no revealing after selection events due to model changes
if (getSite().getPage().getActivePart() != this) {
return;
}
if (fSelectionProviderMediator.getViewerInFocus() != originViewer) {
return;
}
IEditorPart editorPart= EditorUtility.isOpenInEditor(elem);
if (editorPart != null && (elem instanceof IJavaElement)) {
try {
getSite().getPage().removePartListener(fPartListener);
EditorUtility.openInEditor(elem, false);
EditorUtility.revealInEditor(editorPart, (IJavaElement) elem);
getSite().getPage().addPartListener(fPartListener);
} catch (CoreException e) {
JavaPlugin.log(e);
}
}
}
private Display getDisplay() {
if (fPagebook != null && !fPagebook.isDisposed()) {
return fPagebook.getDisplay();
}
return null;
}
private boolean isChildVisible(Composite pb, Control child) {
Control[] children= pb.getChildren();
for (int i= 0; i < children.length; i++) {
if (children[i] == child && children[i].isVisible())
return true;
}
return false;
}
private void updateTitle() {
String viewerTitle= getCurrentViewer().getTitle();
String tooltip;
String title;
if (fInputElement != null) {
String[] args= new String[] { viewerTitle, JavaElementLabels.getElementLabel(fInputElement, JavaElementLabels.ALL_DEFAULT) };
title= TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.title", args); //$NON-NLS-1$
tooltip= TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.tooltip", args); //$NON-NLS-1$
} else {
title= viewerTitle;
tooltip= viewerTitle;
}
setTitle(title);
setTitleToolTip(tooltip);
}
private void updateToolbarButtons() {
boolean isType= fInputElement instanceof IType;
for (int i= 0; i < fViewActions.length; i++) {
ToggleViewAction action= fViewActions[i];
if (action.getViewerIndex() == VIEW_ID_TYPE) {
action.setEnabled(fInputElement != null);
} else {
action.setEnabled(isType);
}
}
}
/**
* Sets the current view (see view id)
* called from ToggleViewAction. Must be called after creation of the viewpart.
*/
public void setView(int viewerIndex) {
Assert.isNotNull(fAllViewers);
if (viewerIndex < fAllViewers.length && fCurrentViewerIndex != viewerIndex) {
fCurrentViewerIndex= viewerIndex;
updateHierarchyViewer();
if (fInputElement != null) {
ISelection currSelection= getCurrentViewer().getSelection();
if (currSelection == null || currSelection.isEmpty()) {
internalSelectType(getSelectableType(fInputElement), false);
currSelection= getCurrentViewer().getSelection();
}
if (!fIsEnableMemberFilter) {
typeSelectionChanged(currSelection);
}
}
updateTitle();
fDialogSettings.put(DIALOGSTORE_HIERARCHYVIEW, viewerIndex);
getCurrentViewer().getTree().setFocus();
}
for (int i= 0; i < fViewActions.length; i++) {
ToggleViewAction action= fViewActions[i];
action.setChecked(fCurrentViewerIndex == action.getViewerIndex());
}
}
/**
* Gets the curret active view index.
*/
public int getViewIndex() {
return fCurrentViewerIndex;
}
private TypeHierarchyViewer getCurrentViewer() {
return fAllViewers[fCurrentViewerIndex];
}
/**
* called from EnableMemberFilterAction.
* Must be called after creation of the viewpart.
*/
public void enableMemberFilter(boolean on) {
if (on != fIsEnableMemberFilter) {
fIsEnableMemberFilter= on;
if (!on) {
IType methodViewerInput= (IType) fMethodsViewer.getInput();
setMemberFilter(null);
updateHierarchyViewer();
updateTitle();
if (methodViewerInput != null && getCurrentViewer().isElementShown(methodViewerInput)) {
// avoid that the method view changes content by selecting the previous input
internalSelectType(methodViewerInput, true);
} else if (fSelectedType != null) {
// choose a input that exists
internalSelectType(fSelectedType, true);
updateMethodViewer(fSelectedType);
}
} else {
methodSelectionChanged(fMethodsViewer.getSelection());
}
}
fEnableMemberFilterAction.setChecked(on);
}
/**
* Called from ITypeHierarchyLifeCycleListener.
* Can be called from any thread
*/
private void doTypeHierarchyChanged(final TypeHierarchyLifeCycle typeHierarchy, final IType[] changedTypes) {
Display display= getDisplay();
if (display != null) {
display.asyncExec(new Runnable() {
public void run() {
if (fPagebook != null && !fPagebook.isDisposed()) {
doTypeHierarchyChangedOnViewers(changedTypes);
}
}
});
}
}
private void doTypeHierarchyChangedOnViewers(IType[] changedTypes) {
if (fHierarchyLifeCycle.getHierarchy() == null || !fHierarchyLifeCycle.getHierarchy().exists()) {
clearInput();
} else {
if (changedTypes == null) {
// hierarchy change
try {
fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(fInputElement, new BusyIndicatorRunnableContext());
} catch (JavaModelException e) {
JavaPlugin.log(e.getStatus());
clearInput();
return;
}
fMethodsViewer.refresh();
updateHierarchyViewer();
} else {
// elements in hierarchy modified
fMethodsViewer.refresh();
if (getCurrentViewer().isMethodFiltering()) {
if (changedTypes.length == 1) {
getCurrentViewer().refresh(changedTypes[0]);
} else {
updateHierarchyViewer();
}
} else {
getCurrentViewer().update(changedTypes, new String[] { IBasicPropertyConstants.P_TEXT, IBasicPropertyConstants.P_IMAGE } );
}
}
}
}
/**
* Determines the input element to be used initially .
*/
private IJavaElement determineInputElement() {
Object input= getSite().getPage().getInput();
if (input instanceof IJavaElement) {
IJavaElement elem= (IJavaElement) input;
if (elem instanceof IMember) {
return elem;
} else {
int kind= elem.getElementType();
if (kind == IJavaElement.JAVA_PROJECT || kind == IJavaElement.PACKAGE_FRAGMENT_ROOT || kind == IJavaElement.PACKAGE_FRAGMENT) {
return elem;
}
}
}
return null;
}
/*
* @see IViewPart#init
*/
public void init(IViewSite site, IMemento memento) throws PartInitException {
super.init(site, memento);
fMemento= memento;
}
/*
* @see ViewPart#saveState(IMemento)
*/
public void saveState(IMemento memento) {
if (fPagebook == null) {
// part has not been created
if (fMemento != null) { //Keep the old state;
memento.putMemento(fMemento);
}
return;
}
if (fInputElement != null) {
String handleIndentifier= fInputElement.getHandleIdentifier();
if (fInputElement instanceof IType) {
ITypeHierarchy hierarchy= fHierarchyLifeCycle.getHierarchy();
if (hierarchy != null && hierarchy.getSubtypes((IType) fInputElement).length > 1000) {
// for startup performance reasons do not try to recover huge hierarchies
handleIndentifier= null;
}
}
memento.putString(TAG_INPUT, handleIndentifier);
}
memento.putInteger(TAG_VIEW, getViewIndex());
memento.putInteger(TAG_ORIENTATION, fCurrentOrientation);
int weigths[]= fTypeMethodsSplitter.getWeights();
int ratio= (weigths[0] * 1000) / (weigths[0] + weigths[1]);
memento.putInteger(TAG_RATIO, ratio);
ScrollBar bar= getCurrentViewer().getTree().getVerticalBar();
int position= bar != null ? bar.getSelection() : 0;
memento.putInteger(TAG_VERTICAL_SCROLL, position);
IJavaElement selection= (IJavaElement)((IStructuredSelection) getCurrentViewer().getSelection()).getFirstElement();
if (selection != null) {
memento.putString(TAG_SELECTION, selection.getHandleIdentifier());
}
fMethodsViewer.saveState(memento);
}
/**
* Restores the type hierarchy settings from a memento.
*/
private void restoreState(IMemento memento, IJavaElement defaultInput) {
IJavaElement input= defaultInput;
String elementId= memento.getString(TAG_INPUT);
if (elementId != null) {
input= JavaCore.create(elementId);
if (input != null && !input.exists()) {
input= null;
}
}
setInputElement(input);
Integer viewerIndex= memento.getInteger(TAG_VIEW);
if (viewerIndex != null) {
setView(viewerIndex.intValue());
}
Integer orientation= memento.getInteger(TAG_ORIENTATION);
if (orientation != null) {
setOrientation(orientation.intValue());
}
Integer ratio= memento.getInteger(TAG_RATIO);
if (ratio != null) {
fTypeMethodsSplitter.setWeights(new int[] { ratio.intValue(), 1000 - ratio.intValue() });
}
ScrollBar bar= getCurrentViewer().getTree().getVerticalBar();
if (bar != null) {
Integer vScroll= memento.getInteger(TAG_VERTICAL_SCROLL);
if (vScroll != null) {
bar.setSelection(vScroll.intValue());
}
}
//String selectionId= memento.getString(TAG_SELECTION);
// do not restore type hierarchy contents
// if (selectionId != null) {
// IJavaElement elem= JavaCore.create(selectionId);
// if (getCurrentViewer().isElementShown(elem) && elem instanceof IMember) {
// internalSelectType((IMember)elem, false);
// }
// }
fMethodsViewer.restoreState(memento);
}
/**
* Link selection to active editor.
*/
private void editorActivated(IEditorPart editor) {
if (!PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR)) {
return;
}
if (fInputElement == null) {
// no type hierarchy shown
return;
}
IJavaElement elem= (IJavaElement)editor.getEditorInput().getAdapter(IJavaElement.class);
try {
TypeHierarchyViewer currentViewer= getCurrentViewer();
if (elem instanceof IClassFile) {
IType type= ((IClassFile)elem).getType();
if (currentViewer.isElementShown(type)) {
internalSelectType(type, true);
updateMethodViewer(type);
}
} else if (elem instanceof ICompilationUnit) {
IType[] allTypes= ((ICompilationUnit)elem).getAllTypes();
for (int i= 0; i < allTypes.length; i++) {
if (currentViewer.isElementShown(allTypes[i])) {
internalSelectType(allTypes[i], true);
updateMethodViewer(allTypes[i]);
return;
}
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e.getStatus());
}
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
*/
public Object getViewPartInput() {
return fInputElement;
}
}
|
26,979 |
Bug 26979 Outline pop-up: flicker when filtering
|
1) open the outline pop-up (ctrl-O) 2) type in a letter ->observe that you can watch how the tree items are removed and then added again. Use of setRedraw(false/true) during filtering should avoid this flickering
|
resolved fixed
|
8931ba1
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-26T09:43:44Z | 2002-11-22T15:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/JavaOutlineInformationControl.java
| |
26,979 |
Bug 26979 Outline pop-up: flicker when filtering
|
1) open the outline pop-up (ctrl-O) 2) type in a letter ->observe that you can watch how the tree items are removed and then added again. Use of setRedraw(false/true) during filtering should avoid this flickering
|
resolved fixed
|
8931ba1
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-26T09:43:44Z | 2002-11-22T15:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/text/JavaSourceViewerConfiguration.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.ui.text;
import java.util.Vector;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.DefaultInformationControl;
import org.eclipse.jface.text.DefaultTextDoubleClickStrategy;
import org.eclipse.jface.text.IAutoIndentStrategy;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IInformationControl;
import org.eclipse.jface.text.IInformationControlCreator;
import org.eclipse.jface.text.ITextDoubleClickStrategy;
import org.eclipse.jface.text.ITextHover;
import org.eclipse.jface.text.ITextViewerExtension2;
import org.eclipse.jface.text.contentassist.ContentAssistant;
import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
import org.eclipse.jface.text.contentassist.IContentAssistant;
import org.eclipse.jface.text.formatter.ContentFormatter;
import org.eclipse.jface.text.formatter.IContentFormatter;
import org.eclipse.jface.text.formatter.IFormattingStrategy;
import org.eclipse.jface.text.information.IInformationPresenter;
import org.eclipse.jface.text.information.IInformationProvider;
import org.eclipse.jface.text.information.InformationPresenter;
import org.eclipse.jface.text.presentation.IPresentationReconciler;
import org.eclipse.jface.text.presentation.PresentationReconciler;
import org.eclipse.jface.text.reconciler.IReconciler;
import org.eclipse.jface.text.rules.DefaultDamagerRepairer;
import org.eclipse.jface.text.rules.RuleBasedScanner;
import org.eclipse.jface.text.source.IAnnotationHover;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.ContentAssistPreference;
import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter;
import org.eclipse.jdt.internal.ui.text.JavaAnnotationHover;
import org.eclipse.jdt.internal.ui.text.JavaElementProvider;
import org.eclipse.jdt.internal.ui.text.JavaOutlineInformationControl;
import org.eclipse.jdt.internal.ui.text.JavaPartitionScanner;
import org.eclipse.jdt.internal.ui.text.JavaReconciler;
import org.eclipse.jdt.internal.ui.text.java.JavaAutoIndentStrategy;
import org.eclipse.jdt.internal.ui.text.java.JavaCompletionProcessor;
import org.eclipse.jdt.internal.ui.text.java.JavaDoubleClickSelector;
import org.eclipse.jdt.internal.ui.text.java.JavaFormattingStrategy;
import org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy;
import org.eclipse.jdt.internal.ui.text.java.JavaStringAutoIndentStrategy;
import org.eclipse.jdt.internal.ui.text.java.JavaStringDoubleClickSelector;
import org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverDescriptor;
import org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy;
import org.eclipse.jdt.internal.ui.text.java.hover.JavaInformationProvider;
import org.eclipse.jdt.internal.ui.text.javadoc.JavaDocAutoIndentStrategy;
import org.eclipse.jdt.internal.ui.text.javadoc.JavaDocCompletionProcessor;
/**
* Configuration for a source viewer which shows Java code.
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*/
public class JavaSourceViewerConfiguration extends SourceViewerConfiguration {
/**
* Preference key used to look up display tab width.
*
* @since 2.0
*/
public final static String PREFERENCE_TAB_WIDTH= PreferenceConstants.EDITOR_TAB_WIDTH;
/**
* Preference key for inserting spaces rather than tabs.
*
* @since 2.0
*/
public final static String SPACES_FOR_TABS= PreferenceConstants.EDITOR_SPACES_FOR_TABS;
private JavaTextTools fJavaTextTools;
private ITextEditor fTextEditor;
/**
* Creates a new Java source viewer configuration for viewers in the given editor
* using the given Java tools.
*
* @param tools the Java tools to be used
* @param editor the editor in which the configured viewer(s) will reside
*/
public JavaSourceViewerConfiguration(JavaTextTools tools, ITextEditor editor) {
fJavaTextTools= tools;
fTextEditor= editor;
}
/**
* Returns the Java source code scanner for this configuration.
*
* @return the Java source code scanner
*/
protected RuleBasedScanner getCodeScanner() {
return fJavaTextTools.getCodeScanner();
}
/**
* Returns the Java multiline comment scanner for this configuration.
*
* @return the Java multiline comment scanner
*
* @since 2.0
*/
protected RuleBasedScanner getMultilineCommentScanner() {
return fJavaTextTools.getMultilineCommentScanner();
}
/**
* Returns the Java singleline comment scanner for this configuration.
*
* @return the Java singleline comment scanner
*
* @since 2.0
*/
protected RuleBasedScanner getSinglelineCommentScanner() {
return fJavaTextTools.getSinglelineCommentScanner();
}
/**
* Returns the Java string scanner for this configuration.
*
* @return the Java string scanner
*
* @since 2.0
*/
protected RuleBasedScanner getStringScanner() {
return fJavaTextTools.getStringScanner();
}
/**
* Returns the JavaDoc scanner for this configuration.
*
* @return the JavaDoc scanner
*/
protected RuleBasedScanner getJavaDocScanner() {
return fJavaTextTools.getJavaDocScanner();
}
/**
* Returns the color manager for this configuration.
*
* @return the color manager
*/
protected IColorManager getColorManager() {
return fJavaTextTools.getColorManager();
}
/**
* Returns the editor in which the configured viewer(s) will reside.
*
* @return the enclosing editor
*/
protected ITextEditor getEditor() {
return fTextEditor;
}
/**
* Returns the preference store used by this configuration to initialize
* the individual bits and pieces.
*
* @return the preference store used to initialize this configuration
*
* @since 2.0
*/
protected IPreferenceStore getPreferenceStore() {
return JavaPlugin.getDefault().getPreferenceStore();
}
/*
* @see ISourceViewerConfiguration#getPresentationReconciler(ISourceViewer)
*/
public IPresentationReconciler getPresentationReconciler(ISourceViewer sourceViewer) {
PresentationReconciler reconciler= new PresentationReconciler();
DefaultDamagerRepairer dr= new DefaultDamagerRepairer(getCodeScanner());
reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE);
reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE);
dr= new DefaultDamagerRepairer(getJavaDocScanner());
reconciler.setDamager(dr, JavaPartitionScanner.JAVA_DOC);
reconciler.setRepairer(dr, JavaPartitionScanner.JAVA_DOC);
dr= new DefaultDamagerRepairer(getMultilineCommentScanner());
reconciler.setDamager(dr, JavaPartitionScanner.JAVA_MULTI_LINE_COMMENT);
reconciler.setRepairer(dr, JavaPartitionScanner.JAVA_MULTI_LINE_COMMENT);
dr= new DefaultDamagerRepairer(getSinglelineCommentScanner());
reconciler.setDamager(dr, JavaPartitionScanner.JAVA_SINGLE_LINE_COMMENT);
reconciler.setRepairer(dr, JavaPartitionScanner.JAVA_SINGLE_LINE_COMMENT);
dr= new DefaultDamagerRepairer(getStringScanner());
reconciler.setDamager(dr, JavaPartitionScanner.JAVA_STRING);
reconciler.setRepairer(dr, JavaPartitionScanner.JAVA_STRING);
return reconciler;
}
/*
* @see SourceViewerConfiguration#getContentAssistant(ISourceViewer)
*/
public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) {
if (getEditor() != null) {
ContentAssistant assistant= new ContentAssistant();
IContentAssistProcessor processor= new JavaCompletionProcessor(getEditor());
assistant.setContentAssistProcessor(processor, 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(processor, JavaPartitionScanner.JAVA_STRING);
assistant.setContentAssistProcessor(processor, JavaPartitionScanner.JAVA_SINGLE_LINE_COMMENT);
assistant.setContentAssistProcessor(new JavaDocCompletionProcessor(getEditor()), JavaPartitionScanner.JAVA_DOC);
ContentAssistPreference.configure(assistant, getPreferenceStore());
assistant.setContextInformationPopupOrientation(ContentAssistant.CONTEXT_INFO_ABOVE);
assistant.setInformationControlCreator(getInformationControlCreator(sourceViewer));
return assistant;
}
return null;
}
/*
* @see SourceViewerConfiguration#getReconciler(ISourceViewer)
*/
public IReconciler getReconciler(ISourceViewer sourceViewer) {
if (getEditor() != null && getEditor().isEditable()) {
JavaReconciler reconciler= new JavaReconciler(getEditor(), new JavaReconcilingStrategy(getEditor()), false);
reconciler.setProgressMonitor(new NullProgressMonitor());
reconciler.setDelay(500);
return reconciler;
}
return null;
}
/*
* @see SourceViewerConfiguration#getAutoIndentStrategy(ISourceViewer, String)
*/
public IAutoIndentStrategy getAutoIndentStrategy(ISourceViewer sourceViewer, String contentType) {
if (JavaPartitionScanner.JAVA_DOC.equals(contentType) ||
JavaPartitionScanner.JAVA_MULTI_LINE_COMMENT.equals(contentType))
return new JavaDocAutoIndentStrategy();
else if (JavaPartitionScanner.JAVA_STRING.equals(contentType))
return new JavaStringAutoIndentStrategy();
return new JavaAutoIndentStrategy();
}
/*
* @see SourceViewerConfiguration#getDoubleClickStrategy(ISourceViewer, String)
*/
public ITextDoubleClickStrategy getDoubleClickStrategy(ISourceViewer sourceViewer, String contentType) {
if (JavaPartitionScanner.JAVA_DOC.equals(contentType) ||
JavaPartitionScanner.JAVA_MULTI_LINE_COMMENT.equals(contentType) ||
JavaPartitionScanner.JAVA_SINGLE_LINE_COMMENT.equals(contentType))
return new DefaultTextDoubleClickStrategy();
else if (JavaPartitionScanner.JAVA_STRING.equals(contentType))
return new JavaStringDoubleClickSelector();
return new JavaDoubleClickSelector();
}
/*
* @see SourceViewerConfiguration#getDefaultPrefix(ISourceViewer, String)
* @since 2.0
*/
public String[] getDefaultPrefixes(ISourceViewer sourceViewer, String contentType) {
return new String[] { "//", "" }; //$NON-NLS-1$ //$NON-NLS-2$
}
/*
* @see SourceViewerConfiguration#getIndentPrefixes(ISourceViewer, String)
*/
public String[] getIndentPrefixes(ISourceViewer sourceViewer, String contentType) {
Vector vector= new Vector();
// prefix[0] is either '\t' or ' ' x tabWidth, depending on useSpaces
Preferences preferences= JavaCore.getPlugin().getPluginPreferences();
int tabWidth= preferences.getInt(JavaCore.FORMATTER_TAB_SIZE);
boolean useSpaces= getPreferenceStore().getBoolean(SPACES_FOR_TABS);
for (int i= 0; i <= tabWidth; i++) {
StringBuffer prefix= new StringBuffer();
if (useSpaces) {
for (int j= 0; j + i < tabWidth; j++)
prefix.append(' ');
if (i != 0)
prefix.append('\t');
} else {
for (int j= 0; j < i; j++)
prefix.append(' ');
if (i != tabWidth)
prefix.append('\t');
}
vector.add(prefix.toString());
}
vector.add(""); //$NON-NLS-1$
return (String[]) vector.toArray(new String[vector.size()]);
}
/*
* @see SourceViewerConfiguration#getTabWidth(ISourceViewer)
*/
public int getTabWidth(ISourceViewer sourceViewer) {
return getPreferenceStore().getInt(PREFERENCE_TAB_WIDTH);
}
/*
* @see SourceViewerConfiguration#getAnnotationHover(ISourceViewer)
*/
public IAnnotationHover getAnnotationHover(ISourceViewer sourceViewer) {
return new JavaAnnotationHover();
}
public int[] getConfiguredTextHoverStateMasks(ISourceViewer sourceViewer, String contentType) {
return new int[] { ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK, SWT.NONE, SWT.CTRL, SWT.SHIFT, SWT.CTRL | SWT.SHIFT, SWT.CTRL | SWT.ALT, SWT.ALT | SWT.SHIFT | SWT.CTRL | SWT.ALT | SWT.SHIFT };
}
/*
* @see SourceViewerConfiguration#getTextHover(ISourceViewer, String, int)
*/
public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType, int stateMask) {
JavaEditorTextHoverDescriptor descriptor= JavaEditorTextHoverDescriptor.getTextHoverDescriptor(stateMask);
if (stateMask != ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK) {
// Ensure that no additional instance is created for default hover
if ((descriptor == null && JavaEditorTextHoverDescriptor.getDefaultHoverId().equals(PreferenceConstants.EDITOR_NO_HOVER_CONFIGURED_ID)) ||(descriptor != null && descriptor.isDefaultTextHoverDescriptor()))
return null; // use default hover instance
}
return new JavaEditorTextHoverProxy(descriptor, getEditor());
}
/*
* @see SourceViewerConfiguration#getTextHover(ISourceViewer, String)
*/
public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType) {
return getTextHover(sourceViewer, contentType, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK);
}
/*
* @see SourceViewerConfiguration#getConfiguredContentTypes(ISourceViewer)
*/
public String[] getConfiguredContentTypes(ISourceViewer sourceViewer) {
return new String[] {
IDocument.DEFAULT_CONTENT_TYPE,
JavaPartitionScanner.JAVA_DOC,
JavaPartitionScanner.JAVA_MULTI_LINE_COMMENT,
JavaPartitionScanner.JAVA_SINGLE_LINE_COMMENT,
JavaPartitionScanner.JAVA_STRING
};
}
/*
* @see SourceViewerConfiguration#getContentFormatter(ISourceViewer)
*/
public IContentFormatter getContentFormatter(ISourceViewer sourceViewer) {
ContentFormatter formatter= new ContentFormatter();
IFormattingStrategy strategy= new JavaFormattingStrategy(sourceViewer);
formatter.setFormattingStrategy(strategy, IDocument.DEFAULT_CONTENT_TYPE);
formatter.enablePartitionAwareFormatting(false);
formatter.setPartitionManagingPositionCategories(fJavaTextTools.getPartitionManagingPositionCategories());
return formatter;
}
/*
* @see SourceViewerConfiguration#getHoverControlCreator(ISourceViewer)
* @since 2.0
*/
public IInformationControlCreator getInformationControlCreator(ISourceViewer sourceViewer) {
return new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell parent) {
return new DefaultInformationControl(parent, SWT.NONE, new HTMLTextPresenter(true));
// return new HoverBrowserControl(parent);
}
};
}
private IInformationControlCreator getInformationPresenterControlCreator(ISourceViewer sourceViewer) {
return new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell parent) {
int shellStyle= SWT.RESIZE;
int style= SWT.V_SCROLL | SWT.H_SCROLL;
return new DefaultInformationControl(parent, shellStyle, style, new HTMLTextPresenter(false));
// return new HoverBrowserControl(parent);
}
};
}
private IInformationControlCreator getOutlinePresenterControlCreator(ISourceViewer sourceViewer) {
return new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell parent) {
int shellStyle= SWT.RESIZE;
int treeStyle= SWT.V_SCROLL | SWT.H_SCROLL;
return new JavaOutlineInformationControl(parent, shellStyle, treeStyle);
}
};
}
/*
* @see SourceViewerConfiguration#getInformationPresenter(ISourceViewer)
* @since 2.0
*/
public IInformationPresenter getInformationPresenter(ISourceViewer sourceViewer) {
InformationPresenter presenter= new InformationPresenter(getInformationPresenterControlCreator(sourceViewer));
IInformationProvider provider= new JavaInformationProvider(getEditor());
presenter.setInformationProvider(provider, IDocument.DEFAULT_CONTENT_TYPE);
presenter.setInformationProvider(provider, JavaPartitionScanner.JAVA_DOC);
presenter.setSizeConstraints(60, 10, true, true);
return presenter;
}
/**
* Returns the outline presenter which will determine and shown
* information requested for the current cursor position.
*
* @param sourceViewer the source viewer to be configured by this configuration
* @return an information presenter
* @since 2.1
*/
public IInformationPresenter getOutlinePresenter(ISourceViewer sourceViewer, boolean doCodeResolve) {
InformationPresenter presenter= new InformationPresenter(getOutlinePresenterControlCreator(sourceViewer));
IInformationProvider provider= new JavaElementProvider(getEditor(), doCodeResolve);
presenter.setInformationProvider(provider, IDocument.DEFAULT_CONTENT_TYPE);
presenter.setInformationProvider(provider, JavaPartitionScanner.JAVA_DOC);
presenter.setSizeConstraints(30, 20, true, false);
return presenter;
}
}
|
26,546 |
Bug 26546 In/correct quick fix for non-static access to static member [quick fix]
|
I have classes like so: com.me.Common extends org.junit.TestCase and com.me.MyTest extends Common. In my test, I have JUnit assertXXX calls coded like so: this.assertXXX(...); I therefore get warnings for non-static access to static members, which is nice! The quick fix changes this: this.assertXXX(...); to this: MyTest.assertXXX(...); I was expecting: Assert.assertXXX(...); Any thoughts? Aside from the quick fix wouldn't Assert... be "more correct"?
|
resolved fixed
|
e8a8f34
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-26T09:59:20Z | 2002-11-16T18:06:40Z |
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/LocalCorrectionsQuickFixTest.java
|
package org.eclipse.jdt.ui.tests.quickfix;
import java.util.ArrayList;
import java.util.Hashtable;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.testplugin.JavaProjectHelper;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal;
import org.eclipse.jdt.internal.ui.text.correction.CorrectionContext;
import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionProcessor;
public class LocalCorrectionsQuickFixTest extends QuickFixTest {
private static final Class THIS= LocalCorrectionsQuickFixTest.class;
private IJavaProject fJProject1;
private IPackageFragmentRoot fSourceFolder;
public LocalCorrectionsQuickFixTest(String name) {
super(name);
}
public static Test suite() {
if (true) {
return new TestSuite(THIS);
} else {
TestSuite suite= new TestSuite();
suite.addTest(new LocalCorrectionsQuickFixTest("testUncaughtExceptionDuplicate"));
return suite;
}
}
protected void setUp() throws Exception {
Hashtable options= JavaCore.getDefaultOptions();
options.put(JavaCore.FORMATTER_TAB_CHAR, JavaCore.SPACE);
options.put(JavaCore.FORMATTER_TAB_SIZE, "4");
options.put(JavaCore.COMPILER_PB_STATIC_ACCESS_RECEIVER, JavaCore.ERROR);
JavaCore.setOptions(options);
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
store.setValue(PreferenceConstants.CODEGEN__FILE_COMMENTS, false);
store.setValue(PreferenceConstants.CODEGEN__JAVADOC_STUBS, false);
fJProject1= JavaProjectHelper.createJavaProject("TestProject1", "bin");
assertTrue("rt not found", JavaProjectHelper.addRTJar(fJProject1) != null);
fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
}
protected void tearDown() throws Exception {
JavaProjectHelper.delete(fJProject1);
}
public void testFieldAccessToStatic() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.File;\n");
buf.append("public class E {\n");
buf.append(" public char foo() {\n");
buf.append(" return (new File(\"x.txt\")).separatorChar;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.File;\n");
buf.append("public class E {\n");
buf.append(" public char foo() {\n");
buf.append(" return File.separatorChar;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testQualifiedAccessToStatic() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Thread t) {\n");
buf.append(" t.sleep(10);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Thread t) {\n");
buf.append(" Thread.sleep(10);\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testThisAccessToStatic() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public static void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" this.goo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public static void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" E.goo();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testCastMissingInVarDecl() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Object o) {\n");
buf.append(" Thread th= o;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Object o) {\n");
buf.append(" Thread th= (Thread) o;\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Object o) {\n");
buf.append(" Object th= o;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastMissingInVarDecl2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.List;\n");
buf.append("public class Container {\n");
buf.append(" public List[] getLists() {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("Container.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Container c) {\n");
buf.append(" ArrayList[] lists= c.getLists();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Container c) {\n");
buf.append(" ArrayList[] lists= (ArrayList[]) c.getLists();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Container c) {\n");
buf.append(" List[] lists= c.getLists();\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastMissingInFieldDecl() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" int time= System.currentTimeMillis();\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" int time= (int) System.currentTimeMillis();\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" long time= System.currentTimeMillis();\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastMissingInAssignment() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Iterator;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Iterator iter) {\n");
buf.append(" String str;\n");
buf.append(" str= iter.next();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Iterator;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Iterator iter) {\n");
buf.append(" String str;\n");
buf.append(" str= (String) iter.next();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testCastMissingInExpression() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public String[] foo(List list) {\n");
buf.append(" return list.toArray(new List[list.size()]);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public String[] foo(List list) {\n");
buf.append(" return (String[]) list.toArray(new List[list.size()]);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public Object[] foo(List list) {\n");
buf.append(" return list.toArray(new List[list.size()]);\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastOnCastExpression() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public void foo(List list) {\n");
buf.append(" ArrayList a= (Cloneable) list;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public void foo(List list) {\n");
buf.append(" ArrayList a= (ArrayList) list;\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public void foo(List list) {\n");
buf.append(" Cloneable a= (Cloneable) list;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUncaughtException() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUncaughtException2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public String goo() throws IOException {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo().substring(2);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public String goo() throws IOException {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException {\n");
buf.append(" goo().substring(2);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public String goo() throws IOException {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo().substring(2);\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUncaughtExceptionRemoveMoreSpecific() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.net.SocketException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() throws SocketException {\n");
buf.append(" this.goo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.net.SocketException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException {\n");
buf.append(" this.goo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.net.SocketException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() throws SocketException {\n");
buf.append(" try {\n");
buf.append(" this.goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
boolean BUG_25417= true;
public void testUncaughtExceptionDuplicate() throws Exception {
if (BUG_25417) {
return;
}
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class MyException extends Exception {\n");
buf.append("}\n");
pack1.createCompilationUnit("MyException.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void m1() throws IOException {\n");
buf.append(" m2();\n");
buf.append(" }\n");
buf.append(" public void m2() throws IOException, ParseException, MyException {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 2);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void m1() throws IOException, ParseException, MyException {\n");
buf.append(" m2();\n");
buf.append(" }\n");
buf.append(" public void m2() throws IOException, ParseException, MyException {\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void m1() throws IOException {\n");
buf.append(" try {\n");
buf.append(" m2();\n");
buf.append(" } catch (ParseException e) {\n");
buf.append(" } catch (MyException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" public void m2() throws IOException, ParseException, MyException {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testMultipleUncaughtExceptions() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException, ParseException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 2); // 2 uncaught exceptions
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException, ParseException {\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException, ParseException {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException, ParseException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" } catch (ParseException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUnneededCatchBlock() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" } catch (ParseException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnneededCatchBlockSingle() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnneededCatchBlockWithFinally() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" } finally {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } finally {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnimplementedMethods() throws Exception {
IPackageFragment pack2= fSourceFolder.createPackageFragment("test2", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test2;\n");
buf.append("import java.io.IOException;\n");
buf.append("public interface Inter {\n");
buf.append(" int getCount(Object[] o) throws IOException;\n");
buf.append("}\n");
pack2.createCompilationUnit("Inter.java", buf.toString(), false, null);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import test2.Inter;\n");
buf.append("public class E implements Inter{\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import test2.Inter;\n");
buf.append("public abstract class E implements Inter{\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("\n");
buf.append("import test2.Inter;\n");
buf.append("public class E implements Inter{\n");
buf.append(" public int getCount(Object[] o) throws IOException {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUnimplementedMethods2() throws Exception {
IPackageFragment pack2= fSourceFolder.createPackageFragment("test2", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test2;\n");
buf.append("import java.io.IOException;\n");
buf.append("public interface Inter {\n");
buf.append(" int getCount(Object[] o) throws IOException;\n");
buf.append("}\n");
pack2.createCompilationUnit("Inter.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test2;\n");
buf.append("import java.io.IOException;\n");
buf.append("public abstract class InterImpl implements Inter {\n");
buf.append(" protected abstract int[] getMusic() throws IOException;\n");
buf.append("}\n");
pack2.createCompilationUnit("InterImpl.java", buf.toString(), false, null);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import test2.InterImpl;\n");
buf.append("public class E extends InterImpl {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 2);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import test2.InterImpl;\n");
buf.append("public abstract class E extends InterImpl {\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("\n");
buf.append("import test2.InterImpl;\n");
buf.append("public class E extends InterImpl {\n");
buf.append(" protected int[] getMusic() throws IOException {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append(" public int getCount(Object[] o) throws IOException {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
}
|
26,546 |
Bug 26546 In/correct quick fix for non-static access to static member [quick fix]
|
I have classes like so: com.me.Common extends org.junit.TestCase and com.me.MyTest extends Common. In my test, I have JUnit assertXXX calls coded like so: this.assertXXX(...); I therefore get warnings for non-static access to static members, which is nice! The quick fix changes this: this.assertXXX(...); to this: MyTest.assertXXX(...); I was expecting: Assert.assertXXX(...); Any thoughts? Aside from the quick fix wouldn't Assert... be "more correct"?
|
resolved fixed
|
e8a8f34
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-26T09:59:20Z | 2002-11-16T18:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/LocalCorrectionsSubProcessor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Renaud Waldura <[email protected]> - Access to static proposal
******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportEdit;
import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory;
import org.eclipse.jdt.internal.corext.dom.ASTNodes;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
import org.eclipse.jdt.internal.corext.dom.Selection;
import org.eclipse.jdt.internal.corext.refactoring.changes.CompilationUnitChange;
import org.eclipse.jdt.internal.corext.refactoring.nls.NLSRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.nls.NLSUtil;
import org.eclipse.jdt.internal.corext.refactoring.surround.ExceptionAnalyzer;
import org.eclipse.jdt.internal.corext.refactoring.surround.SurroundWithTryCatchRefactoring;
import org.eclipse.jdt.internal.corext.textmanipulation.TextEdit;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter;
import org.eclipse.jdt.internal.ui.refactoring.nls.ExternalizeWizard;
/**
*/
public class LocalCorrectionsSubProcessor {
public static void addCastProposals(ICorrectionContext context, List proposals) throws CoreException {
String[] args= context.getProblemArguments();
if (args.length != 2) {
return;
}
ICompilationUnit cu= context.getCompilationUnit();
String castType= args[1];
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= context.getCoveredNode();
if (!(selectedNode instanceof Expression)) {
return;
}
Expression nodeToCast= (Expression) selectedNode;
int parentNodeType= selectedNode.getParent().getNodeType();
if (parentNodeType == ASTNode.ASSIGNMENT) {
Assignment assign= (Assignment) selectedNode.getParent();
if (selectedNode.equals(assign.getLeftHandSide())) {
nodeToCast= assign.getRightHandSide();
}
} else if (parentNodeType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
VariableDeclarationFragment frag= (VariableDeclarationFragment) selectedNode.getParent();
if (selectedNode.equals(frag.getName())) {
nodeToCast= frag.getInitializer();
}
}
{
ASTRewrite rewrite= new ASTRewrite(nodeToCast.getParent());
String label;
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 1, image);
String simpleCastType= proposal.addImport(castType);
if (nodeToCast.getNodeType() == ASTNode.CAST_EXPRESSION) {
label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changecast.description", castType); //$NON-NLS-1$
CastExpression expression= (CastExpression) nodeToCast;
rewrite.markAsReplaced(expression.getType(), rewrite.createPlaceholder(simpleCastType, ASTRewrite.TYPE));
} else {
label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.addcast.description", castType); //$NON-NLS-1$
Expression expressionCopy= (Expression) rewrite.createCopy(nodeToCast);
Type typeCopy= (Type) rewrite.createPlaceholder(simpleCastType, ASTRewrite.TYPE);
CastExpression castExpression= astRoot.getAST().newCastExpression();
castExpression.setExpression(expressionCopy);
castExpression.setType(typeCopy);
rewrite.markAsReplaced(nodeToCast, castExpression);
}
proposal.setDisplayName(label);
proposal.ensureNoModifications();
proposals.add(proposal);
}
// change method return statement to actual type
if (parentNodeType == ASTNode.RETURN_STATEMENT) {
ITypeBinding binding= nodeToCast.resolveTypeBinding();
BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
if (binding != null && decl instanceof MethodDeclaration) {
MethodDeclaration methodDeclaration= (MethodDeclaration) decl;
ASTRewrite rewrite= new ASTRewrite(methodDeclaration);
Type newReturnType= ASTResolving.getTypeFromTypeBinding(astRoot.getAST(), binding);
rewrite.markAsReplaced(methodDeclaration.getReturnType(), newReturnType);
String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changereturntype.description", binding.getName()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 2, image);
proposal.addImport(binding);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
if (parentNodeType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
VariableDeclarationFragment fragment= (VariableDeclarationFragment) selectedNode.getParent();
ASTNode parent= fragment.getParent();
Type type= null;
if (parent instanceof VariableDeclarationStatement) {
VariableDeclarationStatement stmt= (VariableDeclarationStatement) parent;
if (stmt.fragments().size() == 1) {
type= stmt.getType();
}
} else if (parent instanceof FieldDeclaration) {
FieldDeclaration decl= (FieldDeclaration) parent;
if (decl.fragments().size() == 1) {
type= decl.getType();
}
}
if (type != null) {
ImportEdit edit= new ImportEdit(cu, JavaPreferencesSettings.getCodeGenerationSettings());
String typeName= edit.addImport(args[0]);
String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.addcast_var.description", typeName); //$NON-NLS-1$
ReplaceCorrectionProposal varProposal= new ReplaceCorrectionProposal(label, cu, type.getStartPosition(), type.getLength(), typeName, 1);
varProposal.getRootTextEdit().add(edit);
proposals.add(varProposal);
}
}
}
public static void addUncaughtExceptionProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= context.getCoveredNode();
if (selectedNode == null) {
return;
}
while (selectedNode != null && !(selectedNode instanceof Statement)) {
selectedNode= selectedNode.getParent();
}
if (selectedNode == null) {
return;
}
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
SurroundWithTryCatchRefactoring refactoring= new SurroundWithTryCatchRefactoring(cu, selectedNode.getStartPosition(), selectedNode.getLength(), settings, null);
refactoring.setSaveChanges(false);
if (refactoring.checkActivationBasics(astRoot, null).isOK()) {
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.surroundwith.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
CUCorrectionProposal proposal= new CUCorrectionProposal(label, (CompilationUnitChange) refactoring.createChange(null), 4, image);
proposals.add(proposal);
}
BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
if (decl == null) {
return;
}
ITypeBinding[] uncaughtExceptions= ExceptionAnalyzer.perform(decl, Selection.createFromStartLength(selectedNode.getStartPosition(), selectedNode.getLength()));
TryStatement surroundingTry= (TryStatement) ASTNodes.getParent(selectedNode, ASTNode.TRY_STATEMENT);
if (surroundingTry != null) {
ASTRewrite rewrite= new ASTRewrite(surroundingTry);
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addadditionalcatch.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 5, image);
AST ast= astRoot.getAST();
List catchClauses= surroundingTry.catchClauses();
for (int i= 0; i < uncaughtExceptions.length; i++) {
String imp= proposal.addImport(uncaughtExceptions[i]);
Name name= ASTNodeFactory.newName(ast, imp);
SingleVariableDeclaration var= ast.newSingleVariableDeclaration();
var.setName(ast.newSimpleName("e"));
var.setType(ast.newSimpleType(name));
CatchClause newClause= ast.newCatchClause();
newClause.setException(var);
rewrite.markAsInserted(newClause);
catchClauses.add(newClause);
}
proposal.ensureNoModifications();
proposals.add(proposal);
}
if (decl instanceof MethodDeclaration) {
ASTRewrite rewrite= new ASTRewrite(astRoot);
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addthrows.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 6, image);
AST ast= astRoot.getAST();
MethodDeclaration methodDecl= (MethodDeclaration) decl;
List exceptions= methodDecl.thrownExceptions();
for (int i= 0; i < uncaughtExceptions.length; i++) {
String imp= proposal.addImport(uncaughtExceptions[i]);
Name name= ASTNodeFactory.newName(ast, imp);
rewrite.markAsInserted(name);
exceptions.add(name);
}
for (int i= 0; i < exceptions.size(); i++) {
Name elem= (Name) exceptions.get(i);
if (canRemove(elem.resolveTypeBinding(), uncaughtExceptions)) {
rewrite.markAsRemoved(elem);
}
}
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
private static boolean canRemove(ITypeBinding curr, ITypeBinding[] addedExceptions) {
while (curr != null) {
for (int i= 0; i < addedExceptions.length; i++) {
if (curr == addedExceptions[i]) {
return true;
}
}
curr= curr.getSuperclass();
}
return false;
}
public static void addUnreachableCatchProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= context.getCoveringNode();
if (selectedNode == null) {
return;
}
if (selectedNode.getNodeType() == ASTNode.BLOCK && selectedNode.getParent().getNodeType() == ASTNode.CATCH_CLAUSE ) {
CatchClause clause= (CatchClause) selectedNode.getParent();
TryStatement tryStatement= (TryStatement) clause.getParent();
ASTRewrite rewrite= new ASTRewrite(tryStatement.getParent());
if (tryStatement.catchClauses().size() > 1 || tryStatement.getFinally() != null) {
rewrite.markAsRemoved(clause);
} else {
List statements= tryStatement.getBody().statements();
if (statements.size() > 0) {
ASTNode placeholder= rewrite.createCopy((ASTNode) statements.get(0), (ASTNode) statements.get(statements.size() - 1));
rewrite.markAsReplaced(tryStatement, placeholder);
} else {
rewrite.markAsRemoved(tryStatement);
}
}
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.removecatchclause.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 6, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
public static void addNLSProposals(ICorrectionContext context, List proposals) throws CoreException {
final ICompilationUnit cu= context.getCompilationUnit();
String name= CorrectionMessages.getString("LocalCorrectionsSubProcessor.externalizestrings.description"); //$NON-NLS-1$
ChangeCorrectionProposal proposal= new ChangeCorrectionProposal(name, null, 0) {
public void apply(IDocument document) {
try {
NLSRefactoring refactoring= new NLSRefactoring(cu);
ExternalizeWizard wizard= new ExternalizeWizard(refactoring);
String dialogTitle= CorrectionMessages.getString("LocalCorrectionsSubProcessor.externalizestrings.dialog.title"); //$NON-NLS-1$
new RefactoringStarter().activate(refactoring, wizard, dialogTitle, true);
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
};
proposals.add(proposal);
TextEdit edit= NLSUtil.createNLSEdit(cu, context.getOffset());
if (edit != null) {
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addnon-nls.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_NLS_NEVER_TRANSLATE);
CUCorrectionProposal nlsProposal= new CUCorrectionProposal(label, cu, 6, image);
nlsProposal.getRootTextEdit().add(edit);
proposals.add(nlsProposal);
}
}
/**
* A static field or method is accessed using a non-static reference. E.g.
* <pre>
* File f = new File();
* f.pathSeparator;
* </pre>
* This correction changes <code>f</code> above to <code>File</code>.
*
* @param context
* @param proposals
*/
public static void addInstanceAccessToStaticProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= context.getCoveredNode();
if (selectedNode == null) {
return;
}
Expression qualifier= null;
if (selectedNode instanceof QualifiedName) {
qualifier= ((QualifiedName) selectedNode).getQualifier();
} else if (selectedNode instanceof SimpleName) {
ASTNode parent= selectedNode.getParent();
if (parent instanceof FieldAccess) {
qualifier= ((FieldAccess) parent).getExpression();
}
} else if (selectedNode instanceof MethodInvocation) {
qualifier= ((MethodInvocation) selectedNode).getExpression();
}
if (qualifier != null) {
ITypeBinding typeBinding= ASTResolving.normalizeTypeBinding(qualifier.resolveTypeBinding());
if (typeBinding != null) {
ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent());
rewrite.markAsReplaced(qualifier, astRoot.getAST().newSimpleName(typeBinding.getName()));
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.changeaccesstostatic.description");
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 1, image);
proposal.addImport(typeBinding);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
}
public static void addUnimplementedMethodsProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= context.getCoveringNode();
if (selectedNode == null) {
return;
}
ASTNode typeNode= null;
if (selectedNode.getNodeType() == ASTNode.SIMPLE_NAME && selectedNode.getParent().getNodeType() == ASTNode.TYPE_DECLARATION) {
typeNode= selectedNode.getParent();
} else if (selectedNode.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION) {
ClassInstanceCreation creation= (ClassInstanceCreation) selectedNode;
typeNode= creation.getAnonymousClassDeclaration();
}
if (typeNode != null) {
UnimplementedMethodsCompletionProposal proposal= new UnimplementedMethodsCompletionProposal(cu, typeNode, 0);
proposals.add(proposal);
}
if (typeNode instanceof TypeDeclaration) {
TypeDeclaration typeDeclaration= (TypeDeclaration) typeNode;
ASTRewriteCorrectionProposal proposal= ModifierCorrectionSubProcessor.getMakeTypeStaticProposal(cu, typeDeclaration);
proposals.add(proposal);
}
}
}
|
27,114 |
Bug 27114 something leaks StyleRanges and Lines
|
180K of StyleReanges and 47K of Lines after: -open editor -close editor seems like StyleRange objects are never freed
|
resolved fixed
|
ef8dd97
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-26T10:46:51Z | 2002-11-25T18:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaEditor.java
|
/**********************************************************************
Copyright (c) 2000, 2002 IBM Corp. and others.
All rights reserved. This program and the accompanying materials
are made available under the terms of the Common Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/cpl-v10.html
Contributors:
IBM Corporation - Initial implementation
**********************************************************************/
package org.eclipse.jdt.internal.ui.javaeditor;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BidiSegmentEvent;
import org.eclipse.swt.custom.BidiSegmentListener;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DefaultInformationControl;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.jface.text.IInformationControl;
import org.eclipse.jface.text.IInformationControlCreator;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextHover;
import org.eclipse.jface.text.ITextInputListener;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.ITextViewerExtension2;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.text.information.IInformationProvider;
import org.eclipse.jface.text.information.InformationPresenter;
import org.eclipse.jface.text.source.AnnotationRulerColumn;
import org.eclipse.jface.text.source.CompositeRuler;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.IVerticalRuler;
import org.eclipse.jface.text.source.IVerticalRulerColumn;
import org.eclipse.jface.text.source.LineNumberRulerColumn;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IPartService;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.editors.text.DefaultEncodingSupport;
import org.eclipse.ui.editors.text.IEncodingSupport;
import org.eclipse.ui.part.EditorActionBarContributor;
import org.eclipse.ui.texteditor.AddTaskAction;
import org.eclipse.ui.texteditor.DefaultRangeIndicator;
import org.eclipse.ui.texteditor.IAbstractTextEditorHelpContextIds;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
import org.eclipse.ui.texteditor.ResourceAction;
import org.eclipse.ui.texteditor.StatusTextEditor;
import org.eclipse.ui.texteditor.TextEditorAction;
import org.eclipse.ui.texteditor.TextOperationAction;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICodeAssist;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IPackageDeclaration;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds;
import org.eclipse.jdt.ui.actions.JavaSearchActionGroup;
import org.eclipse.jdt.ui.actions.OpenEditorActionGroup;
import org.eclipse.jdt.ui.actions.OpenViewActionGroup;
import org.eclipse.jdt.ui.actions.ShowActionGroup;
import org.eclipse.jdt.ui.text.IColorManager;
import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.preferences.JavaEditorPreferencePage;
import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter;
import org.eclipse.jdt.internal.ui.text.JavaPartitionScanner;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider;
/**
* Java specific text editor.
*/
public abstract class JavaEditor extends StatusTextEditor implements IViewPartInputProvider {
/**
* "Smart" runnable for updating the outline page's selection.
*/
class OutlinePageSelectionUpdater implements Runnable {
/** Has the runnable already been posted? */
private boolean fPosted= false;
public OutlinePageSelectionUpdater() {
}
/*
* @see Runnable#run()
*/
public void run() {
synchronizeOutlinePageSelection();
fPosted= false;
}
/**
* Posts this runnable into the event queue.
*/
public void post() {
if (fPosted)
return;
Shell shell= getSite().getShell();
if (shell != null & !shell.isDisposed()) {
fPosted= true;
shell.getDisplay().asyncExec(this);
}
}
};
class SelectionChangedListener implements ISelectionChangedListener {
public void selectionChanged(SelectionChangedEvent event) {
doSelectionChanged(event);
}
};
/**
* Link mode.
*/
class MouseClickListener implements KeyListener, MouseListener, MouseMoveListener,
FocusListener, PaintListener, IPropertyChangeListener, IDocumentListener, ITextInputListener {
/** The session is active. */
private boolean fActive;
/** The currently active style range. */
private IRegion fActiveRegion;
/** The hand cursor. */
private Cursor fCursor;
/** The default cursor. */
private Cursor fDefaultCursor;
/** The link color. */
private Color fColor;
public void deactivate() {
if (!fActive)
return;
repairRepresentation();
fActive= false;
}
public void install() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
StyledText text= sourceViewer.getTextWidget();
if (text == null || text.isDisposed())
return;
updateColor(sourceViewer);
sourceViewer.addTextInputListener(this);
IDocument document= sourceViewer.getDocument();
if (document != null)
document.addDocumentListener(this);
text.addKeyListener(this);
text.addMouseListener(this);
text.addMouseMoveListener(this);
text.addFocusListener(this);
text.addPaintListener(this);
IPreferenceStore preferenceStore= getPreferenceStore();
preferenceStore.addPropertyChangeListener(this);
}
public void uninstall() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
StyledText text= sourceViewer.getTextWidget();
if (text == null || text.isDisposed())
return;
sourceViewer.removeTextInputListener(this);
IDocument document= sourceViewer.getDocument();
if (document != null)
document.removeDocumentListener(this);
text.removeKeyListener(this);
text.removeMouseListener(this);
text.removeMouseMoveListener(this);
text.removeFocusListener(this);
text.removePaintListener(this);
IPreferenceStore preferenceStore= getPreferenceStore();
preferenceStore.removePropertyChangeListener(this);
if (fColor != null) {
fColor.dispose();
fColor= null;
}
if (fCursor != null) {
fCursor.dispose();
fCursor= null;
}
}
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(JavaEditor.LINK_COLOR)) {
ISourceViewer viewer= getSourceViewer();
if (viewer != null)
updateColor(viewer);
}
}
private void updateColor(ISourceViewer viewer) {
if (fColor != null)
fColor.dispose();
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
Display display= text.getDisplay();
fColor= createColor(getPreferenceStore(), JavaEditor.LINK_COLOR, display);
}
/**
* Creates a color from the information stored in the given preference store.
* Returns <code>null</code> if there is no such information available.
*/
private Color createColor(IPreferenceStore store, String key, Display display) {
RGB rgb= null;
if (store.contains(key)) {
if (store.isDefault(key))
rgb= PreferenceConverter.getDefaultColor(store, key);
else
rgb= PreferenceConverter.getColor(store, key);
if (rgb != null)
return new Color(display, rgb);
}
return null;
}
private void repairRepresentation() {
if (fActiveRegion == null)
return;
ISourceViewer viewer= getSourceViewer();
if (viewer != null) {
resetCursor(viewer);
int offset= fActiveRegion.getOffset();
int length= fActiveRegion.getLength();
// remove style
if (viewer instanceof ITextViewerExtension2)
((ITextViewerExtension2) viewer).invalidateTextPresentation(offset, length);
else
viewer.invalidateTextPresentation();
// remove underline
offset -= viewer.getVisibleRegion().getOffset();
StyledText text= viewer.getTextWidget();
text.redrawRange(offset, length, true);
}
fActiveRegion= null;
}
private IJavaElement getInput(JavaEditor editor) {
if (editor == null)
return null;
IEditorInput input= editor.getEditorInput();
if (input instanceof IClassFileEditorInput)
return ((IClassFileEditorInput)input).getClassFile();
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
return manager.getWorkingCopy(input);
}
// will eventually be replaced by a method provided by jdt.core
private IRegion selectWord(IDocument document, int anchor) {
try {
int offset= anchor;
char c;
while (offset >= 0) {
c= document.getChar(offset);
if (!Character.isJavaIdentifierPart(c))
break;
--offset;
}
int start= offset;
offset= anchor;
int length= document.getLength();
while (offset < length) {
c= document.getChar(offset);
if (!Character.isJavaIdentifierPart(c))
break;
++offset;
}
int end= offset;
if (start == end)
return new Region(start, 0);
else
return new Region(start + 1, end - start - 1);
} catch (BadLocationException x) {
return null;
}
}
IRegion getCurrentTextRegion(ISourceViewer viewer) {
int offset= getCurrentTextOffset(viewer);
if (offset == -1)
return null;
IJavaElement input= SelectionConverter.getInput(JavaEditor.this);
if (input == null)
return null;
try {
IJavaElement[] elements= ((ICodeAssist) input).codeSelect(offset, 0);
if (elements == null || elements.length == 0)
return null;
return selectWord(viewer.getDocument(), offset);
} catch (JavaModelException e) {
return null;
}
}
private int getCurrentTextOffset(ISourceViewer viewer) {
try {
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return -1;
Display display= text.getDisplay();
Point absolutePosition= display.getCursorLocation();
Point relativePosition= text.toControl(absolutePosition);
return text.getOffsetAtLocation(relativePosition) + viewer.getVisibleRegion().getOffset();
} catch (IllegalArgumentException e) {
return -1;
}
}
private void highlightRegion(ISourceViewer viewer, IRegion region) {
if (region.equals(fActiveRegion))
return;
repairRepresentation();
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
// highlight region
int offset= region.getOffset() - viewer.getVisibleRegion().getOffset();
int length= region.getLength();
StyleRange oldStyleRange= text.getStyleRangeAtOffset(offset);
Color foregroundColor= fColor;
Color backgroundColor= oldStyleRange == null ? text.getBackground() : oldStyleRange.background;
StyleRange styleRange= new StyleRange(offset, length, foregroundColor, backgroundColor);
text.setStyleRange(styleRange);
// underline
text.redrawRange(offset, length, true);
fActiveRegion= region;
}
private void activateCursor(ISourceViewer viewer) {
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
Display display= text.getDisplay();
if (fCursor == null)
fCursor= new Cursor(display, SWT.CURSOR_HAND);
text.setCursor(fCursor);
}
private void resetCursor(ISourceViewer viewer) {
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
Display display= text.getDisplay();
if (fDefaultCursor == null)
fDefaultCursor= new Cursor(display, SWT.CURSOR_IBEAM);
text.setCursor(fDefaultCursor);
if (fCursor != null) {
fCursor.dispose();
fCursor= null;
}
}
/*
* @see org.eclipse.swt.events.KeyListener#keyPressed(org.eclipse.swt.events.KeyEvent)
*/
public void keyPressed(KeyEvent event) {
if (fActive) {
deactivate();
return;
}
if (event.keyCode != SWT.CTRL) {
deactivate();
return;
}
fActive= true;
ISourceViewer viewer= getSourceViewer();
if (viewer == null)
return;
IRegion region= getCurrentTextRegion(viewer);
if (region == null)
return;
// removed for #25871
// highlightRegion(viewer, region);
// activateCursor(viewer);
}
/*
* @see org.eclipse.swt.events.KeyListener#keyReleased(org.eclipse.swt.events.KeyEvent)
*/
public void keyReleased(KeyEvent event) {
if (!fActive)
return;
deactivate();
}
/*
* @see org.eclipse.swt.events.MouseListener#mouseDoubleClick(org.eclipse.swt.events.MouseEvent)
*/
public void mouseDoubleClick(MouseEvent e) {}
/*
* @see org.eclipse.swt.events.MouseListener#mouseDown(org.eclipse.swt.events.MouseEvent)
*/
public void mouseDown(MouseEvent event) {
if (!fActive)
return;
if (event.stateMask != SWT.CTRL) {
deactivate();
return;
}
if (event.button != 1) {
deactivate();
return;
}
}
/*
* @see org.eclipse.swt.events.MouseListener#mouseUp(org.eclipse.swt.events.MouseEvent)
*/
public void mouseUp(MouseEvent e) {
if (!fActive)
return;
if (e.button != 1) {
deactivate();
return;
}
deactivate();
IAction action= getAction("OpenEditor"); //$NON-NLS-1$
if (action == null)
return;
action.run();
}
/*
* @see org.eclipse.swt.events.MouseMoveListener#mouseMove(org.eclipse.swt.events.MouseEvent)
*/
public void mouseMove(MouseEvent event) {
if (event.widget instanceof Control && !((Control) event.widget).isFocusControl()) {
deactivate();
return;
}
if (!fActive) {
if (event.stateMask != SWT.CTRL)
return;
// Ctrl was already pressed
fActive= true;
}
ISourceViewer viewer= getSourceViewer();
if (viewer == null) {
deactivate();
return;
}
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed()) {
deactivate();
return;
}
if ((event.stateMask & SWT.BUTTON1) != 0 && text.getSelectionCount() != 0) {
deactivate();
return;
}
IRegion region= getCurrentTextRegion(viewer);
if (region == null || 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) {
}
/*
* @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent)
*/
public void documentChanged(DocumentEvent event) {
deactivate();
}
/*
* @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
*/
public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) {
if (oldInput == null)
return;
deactivate();
oldInput.removeDocumentListener(this);
}
/*
* @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
*/
public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
if (newInput == null)
return;
newInput.addDocumentListener(this);
}
/*
* @see PaintListener#paintControl(PaintEvent)
*/
public void paintControl(PaintEvent event) {
if (fActiveRegion == null)
return;
ISourceViewer viewer= getSourceViewer();
if (viewer == null)
return;
IRegion region= viewer.getVisibleRegion();
if (!includes(region, fActiveRegion))
return;
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
int offset= fActiveRegion.getOffset() - region.getOffset();
int length= fActiveRegion.getLength();
// support for bidi
Point minLocation= getMinimumLocation(text, offset, length);
Point maxLocation= getMaximumLocation(text, offset, length);
int x1= minLocation.x;
int x2= minLocation.x + maxLocation.x - minLocation.x - 1;
int y= minLocation.y + text.getLineHeight() - 1;
GC gc= event.gc;
if (fColor != null && !fColor.isDisposed())
gc.setForeground(fColor);
gc.drawLine(x1, y, x2, y);
}
private boolean includes(IRegion region, IRegion position) {
return
position.getOffset() >= region.getOffset() &&
position.getOffset() + position.getLength() <= region.getOffset() + region.getLength();
}
private Point getMinimumLocation(StyledText text, int offset, int length) {
Point minLocation= new Point(Integer.MAX_VALUE, Integer.MAX_VALUE);
for (int i= 0; i <= length; i++) {
Point location= text.getLocationAtOffset(offset + i);
if (location.x < minLocation.x)
minLocation.x= location.x;
if (location.y < minLocation.y)
minLocation.y= location.y;
}
return minLocation;
}
private Point getMaximumLocation(StyledText text, int offset, int length) {
Point maxLocation= new Point(Integer.MIN_VALUE, Integer.MIN_VALUE);
for (int i= 0; i <= length; i++) {
Point location= text.getLocationAtOffset(offset + i);
if (location.x > maxLocation.x)
maxLocation.x= location.x;
if (location.y > maxLocation.y)
maxLocation.y= location.y;
}
return maxLocation;
}
}
/**
* This action dispatches into two behaviours: If there is no current text
* hover, the javadoc is displayed using information presenter. If there is
* a current text hover, it is converted into a information presenter in
* order to make it sticky.
*/
class InformationDispatchAction extends TextEditorAction {
/** The wrapped text operation action. */
private final TextOperationAction fTextOperationAction;
/**
* Creates a dispatch action.
*/
public InformationDispatchAction(ResourceBundle resourceBundle, String prefix, final TextOperationAction textOperationAction) {
super(resourceBundle, prefix, JavaEditor.this);
if (textOperationAction == null)
throw new IllegalArgumentException();
fTextOperationAction= textOperationAction;
}
/*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null) {
fTextOperationAction.run();
return;
}
if (! (sourceViewer instanceof ITextViewerExtension2)) {
fTextOperationAction.run();
return;
}
ITextViewerExtension2 textViewerExtension2= (ITextViewerExtension2) sourceViewer;
// does a text hover exist?
ITextHover textHover= textViewerExtension2.getCurrentTextHover();
if (textHover == null) {
fTextOperationAction.run();
return;
}
Point hoverEventLocation= textViewerExtension2.getHoverEventLocation();
int offset= computeOffsetAtLocation(sourceViewer, hoverEventLocation.x, hoverEventLocation.y);
if (offset == -1) {
fTextOperationAction.run();
return;
}
try {
// get the text hover content
IDocument document= sourceViewer.getDocument();
String contentType= document.getContentType(offset);
final IRegion hoverRegion= textHover.getHoverRegion(sourceViewer, offset);
if (hoverRegion == null)
return;
final String hoverInfo= textHover.getHoverInfo(sourceViewer, hoverRegion);
// with information provider
IInformationProvider informationProvider= new IInformationProvider() {
/*
* @see org.eclipse.jface.text.information.IInformationProvider#getSubject(org.eclipse.jface.text.ITextViewer, int)
*/
public IRegion getSubject(ITextViewer textViewer, int offset) {
return hoverRegion;
}
/*
* @see org.eclipse.jface.text.information.IInformationProvider#getInformation(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion)
*/
public String getInformation(ITextViewer textViewer, IRegion subject) {
return hoverInfo;
}
};
fInformationPresenter.setOffset(offset);
fInformationPresenter.setInformationProvider(informationProvider, contentType);
fInformationPresenter.showInformation();
} catch (BadLocationException e) {
}
}
// modified version from TextViewer
private int computeOffsetAtLocation(ITextViewer textViewer, int x, int y) {
StyledText styledText= textViewer.getTextWidget();
IDocument document= textViewer.getDocument();
IRegion visibleRegion= textViewer.getVisibleRegion();
if (document == null)
return -1;
try {
return styledText.getOffsetAtLocation(new Point(x, y)) + visibleRegion.getOffset();
} catch (IllegalArgumentException e) {
return -1;
}
}
}
/** Preference key for showing the line number ruler */
private final static String LINE_NUMBER_RULER= PreferenceConstants.EDITOR_LINE_NUMBER_RULER;
/** Preference key for the foreground color of the line numbers */
private final static String LINE_NUMBER_COLOR= PreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR;
/** Preference key for the link color */
private final static String LINK_COLOR= PreferenceConstants.EDITOR_LINK_COLOR;
// /** Preference key for the default hover */
// private static final String DEFAULT_HOVER= PreferenceConstants.EDITOR_DEFAULT_HOVER;
// /** Preference key for hover while no modifier is pressed */
// private static final String NONE_HOVER= PreferenceConstants.EDITOR_NONE_HOVER;
// /** Preference key for hover while Ctrl modifier is pressed */
// private static final String CTRL_HOVER= PreferenceConstants.EDITOR_CTRL_HOVER;
// /** Preference key for hover while Shift modifier is pressed */
// private static final String SHIFT_HOVER= PreferenceConstants.EDITOR_SHIFT_HOVER;
// /** Preference key for hover while Ctrl+Alt modifiers are pressed */
// private static final String CTRL_ALT_HOVER= PreferenceConstants.EDITOR_CTRL_ALT_HOVER;
// /** Preference key for hover while Ctrl+Alt+Shift modifiers are pressed */
// private static final String CTRL_ALT_SHIFT_HOVER= PreferenceConstants.EDITOR_CTRL_ALT_SHIFT_HOVER;
// /** Preference key for hover while Ctrl+Shift modifiers are pressed */
// private static final String CTRL_SHIFT_HOVER= PreferenceConstants.EDITOR_CTRL_SHIFT_HOVER;
// /** Preference key for hover while Alt+Shift modifiers are pressed */
// private static final String ALT_SHIFT_HOVER= PreferenceConstants.EDITOR_ALT_SHIFT_HOVER;
// /** Id indicating no hover is configured */
// private static final String NO_HOVER_CONFIGURED_ID= PreferenceConstants.EDITOR_NO_HOVER_CONFIGURED_ID;
// /** Hover id indicating the default hover */
// private static final String DEFAULT_HOVER_CONFIGURED_ID= PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID;
/** The outline page */
protected JavaOutlinePage fOutlinePage;
/** Outliner context menu Id */
protected String fOutlinerContextMenuId;
/** The selection changed listener */
protected ISelectionChangedListener fSelectionChangedListener= new SelectionChangedListener();
/** The outline page selection updater */
private OutlinePageSelectionUpdater fUpdater;
/** Indicates whether this editor should react on outline page selection changes */
private int fIgnoreOutlinePageSelection;
/** The line number ruler column */
private LineNumberRulerColumn fLineNumberRulerColumn;
/** This editor's encoding support */
private DefaultEncodingSupport fEncodingSupport;
/** The mouse listener */
private MouseClickListener fMouseListener;
/** The information presenter. */
private InformationPresenter fInformationPresenter;
protected CompositeActionGroup fActionGroups;
private CompositeActionGroup fContextMenuGroup;
/**
* Returns the most narrow java element including the given offset
*
* @param offset the offset inside of the requested element
*/
abstract protected IJavaElement getElementAt(int offset);
/**
* Returns the java element of this editor's input corresponding to the given IJavaElement
*/
abstract protected IJavaElement getCorrespondingElement(IJavaElement element);
/**
* Sets the input of the editor's outline page.
*/
abstract protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input);
/**
* Default constructor.
*/
public JavaEditor() {
super();
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
setSourceViewerConfiguration(new JavaSourceViewerConfiguration(textTools, this));
setRangeIndicator(new DefaultRangeIndicator());
setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
if (JavaEditorPreferencePage.synchronizeOutlineOnCursorMove())
fUpdater= new OutlinePageSelectionUpdater();
}
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected final ISourceViewer createSourceViewer(Composite parent, IVerticalRuler ruler, int styles) {
ISourceViewer viewer= createJavaSourceViewer(parent, ruler, styles);
StyledText text= viewer.getTextWidget();
text.addBidiSegmentListener(new BidiSegmentListener() {
public void lineGetSegments(BidiSegmentEvent event) {
event.segments= getBidiLineSegments(event.lineOffset, event.lineText);
}
});
JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR);
return viewer;
}
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler ruler, int styles) {
return super.createSourceViewer(parent, ruler, styles);
}
/*
* @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent)
*/
protected boolean affectsTextPresentation(PropertyChangeEvent event) {
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
return textTools.affectsBehavior(event);
}
/**
* Sets the outliner's context menu ID.
*/
protected void setOutlinerContextMenuId(String menuId) {
fOutlinerContextMenuId= menuId;
}
/**
* Returns the standard action group of this editor.
*/
protected ActionGroup getActionGroup() {
return fActionGroups;
}
/*
* @see AbstractTextEditor#editorContextMenuAboutToShow
*/
public void editorContextMenuAboutToShow(IMenuManager menu) {
super.editorContextMenuAboutToShow(menu);
menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, new Separator(IContextMenuConstants.GROUP_OPEN));
menu.insertAfter(IContextMenuConstants.GROUP_OPEN, new GroupMarker(IContextMenuConstants.GROUP_SHOW));
ActionContext context= new ActionContext(getSelectionProvider().getSelection());
fContextMenuGroup.setContext(context);
fContextMenuGroup.fillContextMenu(menu);
fContextMenuGroup.setContext(null);
}
/**
* Creates the outline page used with this editor.
*/
protected JavaOutlinePage createOutlinePage() {
JavaOutlinePage page= new JavaOutlinePage(fOutlinerContextMenuId, this);
page.addSelectionChangedListener(fSelectionChangedListener);
setOutlinePageInput(page, getEditorInput());
return page;
}
/**
* Informs the editor that its outliner has been closed.
*/
public void outlinePageClosed() {
if (fOutlinePage != null) {
fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener);
fOutlinePage= null;
resetHighlightRange();
}
}
/**
* Synchronizes the outliner selection with the actual cursor
* position in the editor.
*/
public void synchronizeOutlinePageSelection() {
if (isEditingScriptRunning())
return;
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null || fOutlinePage == null)
return;
StyledText styledText= sourceViewer.getTextWidget();
if (styledText == null)
return;
int offset= sourceViewer.getVisibleRegion().getOffset();
int caret= offset + styledText.getCaretOffset();
IJavaElement element= getElementAt(caret);
if (element instanceof ISourceReference) {
fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener);
fOutlinePage.select((ISourceReference) element);
fOutlinePage.addSelectionChangedListener(fSelectionChangedListener);
}
}
/*
* Get the desktop's StatusLineManager
*/
protected IStatusLineManager getStatusLineManager() {
IEditorActionBarContributor contributor= getEditorSite().getActionBarContributor();
if (contributor instanceof EditorActionBarContributor) {
return ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager();
}
return null;
}
/*
* @see AbstractTextEditor#getAdapter(Class)
*/
public Object getAdapter(Class required) {
if (IContentOutlinePage.class.equals(required)) {
if (fOutlinePage == null)
fOutlinePage= createOutlinePage();
return fOutlinePage;
}
if (IEncodingSupport.class.equals(required))
return fEncodingSupport;
return super.getAdapter(required);
}
protected void setSelection(ISourceReference reference, boolean moveCursor) {
ISelection selection= getSelectionProvider().getSelection();
if (selection instanceof TextSelection) {
TextSelection textSelection= (TextSelection) selection;
if (textSelection.getOffset() != 0 || textSelection.getLength() != 0)
markInNavigationHistory();
}
if (reference != null) {
StyledText textWidget= null;
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null)
textWidget= sourceViewer.getTextWidget();
if (textWidget == null)
return;
try {
ISourceRange range= reference.getSourceRange();
if (range == null)
return;
int offset= range.getOffset();
int length= range.getLength();
if (offset < 0 || length < 0)
return;
textWidget.setRedraw(false);
setHighlightRange(offset, length, moveCursor);
if (!moveCursor)
return;
offset= -1;
length= -1;
if (reference instanceof IMember) {
range= ((IMember) reference).getNameRange();
if (range != null) {
offset= range.getOffset();
length= range.getLength();
}
} else if (reference instanceof IImportDeclaration) {
String name= ((IImportDeclaration) reference).getElementName();
if (name != null && name.length() > 0) {
String content= reference.getSource();
offset= range.getOffset() + content.indexOf(name);
length= name.length();
}
} else if (reference instanceof IPackageDeclaration) {
String name= ((IPackageDeclaration) reference).getElementName();
if (name != null && name.length() > 0) {
String content= reference.getSource();
offset= range.getOffset() + content.indexOf(name);
length= name.length();
}
}
if (offset > -1 && length > 0) {
sourceViewer.revealRange(offset, length);
sourceViewer.setSelectedRange(offset, length);
}
} catch (JavaModelException x) {
} catch (IllegalArgumentException x) {
} finally {
if (textWidget != null)
textWidget.setRedraw(true);
}
} else if (moveCursor) {
resetHighlightRange();
}
markInNavigationHistory();
}
public void setSelection(IJavaElement element) {
if (element == null || element instanceof ICompilationUnit || element instanceof IClassFile) {
/*
* If the element is an ICompilationUnit this unit is either the input
* of this editor or not being displayed. In both cases, nothing should
* happened. (http://dev.eclipse.org/bugs/show_bug.cgi?id=5128)
*/
return;
}
IJavaElement corresponding= getCorrespondingElement(element);
if (corresponding instanceof ISourceReference) {
ISourceReference reference= (ISourceReference) corresponding;
// set hightlight range
setSelection(reference, true);
// set outliner selection
if (fOutlinePage != null) {
fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener);
fOutlinePage.select(reference);
fOutlinePage.addSelectionChangedListener(fSelectionChangedListener);
}
}
}
public synchronized void editingScriptStarted() {
++ fIgnoreOutlinePageSelection;
}
public synchronized void editingScriptEnded() {
-- fIgnoreOutlinePageSelection;
}
public synchronized boolean isEditingScriptRunning() {
return (fIgnoreOutlinePageSelection > 0);
}
protected void doSelectionChanged(SelectionChangedEvent event) {
ISourceReference reference= null;
ISelection selection= event.getSelection();
Iterator iter= ((IStructuredSelection) selection).iterator();
while (iter.hasNext()) {
Object o= iter.next();
if (o instanceof ISourceReference) {
reference= (ISourceReference) o;
break;
}
}
if (!isActivePart() && JavaPlugin.getActivePage() != null)
JavaPlugin.getActivePage().bringToTop(this);
try {
editingScriptStarted();
setSelection(reference, !isActivePart());
} finally {
editingScriptEnded();
}
}
/*
* @see AbstractTextEditor#adjustHighlightRange(int, int)
*/
protected void adjustHighlightRange(int offset, int length) {
try {
IJavaElement element= getElementAt(offset);
while (element instanceof ISourceReference) {
ISourceRange range= ((ISourceReference) element).getSourceRange();
if (offset < range.getOffset() + range.getLength() && range.getOffset() < offset + length) {
setHighlightRange(range.getOffset(), range.getLength(), true);
if (fOutlinePage != null) {
fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener);
fOutlinePage.select((ISourceReference) element);
fOutlinePage.addSelectionChangedListener(fSelectionChangedListener);
}
return;
}
element= element.getParent();
}
} catch (JavaModelException x) {
JavaPlugin.log(x.getStatus());
}
resetHighlightRange();
}
protected boolean isActivePart() {
IWorkbenchWindow window= getSite().getWorkbenchWindow();
IPartService service= window.getPartService();
IWorkbenchPart part= service.getActivePart();
return part != null && part.equals(this);
}
/*
* @see StatusTextEditor#getStatusHeader(IStatus)
*/
protected String getStatusHeader(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusHeader(status);
if (message != null)
return message;
}
return super.getStatusHeader(status);
}
/*
* @see StatusTextEditor#getStatusBanner(IStatus)
*/
protected String getStatusBanner(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusBanner(status);
if (message != null)
return message;
}
return super.getStatusBanner(status);
}
/*
* @see StatusTextEditor#getStatusMessage(IStatus)
*/
protected String getStatusMessage(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusMessage(status);
if (message != null)
return message;
}
return super.getStatusMessage(status);
}
/*
* @see AbstractTextEditor#doSetInput
*/
protected void doSetInput(IEditorInput input) throws CoreException {
super.doSetInput(input);
if (fEncodingSupport != null)
fEncodingSupport.reset();
setOutlinePageInput(fOutlinePage, input);
}
/*
* @see IWorkbenchPart#dispose()
*/
public void dispose() {
if (fMouseListener != null) {
fMouseListener.uninstall();
fMouseListener= null;
}
if (fEncodingSupport != null) {
fEncodingSupport.dispose();
fEncodingSupport= null;
}
super.dispose();
}
protected void createActions() {
super.createActions();
ResourceAction action= new AddTaskAction(JavaEditorMessages.getResourceBundle(), "AddTask.", this); //$NON-NLS-1$
action.setHelpContextId(IAbstractTextEditorHelpContextIds.ADD_TASK_ACTION);
action.setActionDefinitionId(ITextEditorActionDefinitionIds.ADD_TASK);
setAction(ITextEditorActionConstants.ADD_TASK, action);
ActionGroup oeg, ovg, sg, jsg;
fActionGroups= new CompositeActionGroup(new ActionGroup[] {
oeg= new OpenEditorActionGroup(this),
ovg= new OpenViewActionGroup(this),
sg= new ShowActionGroup(this),
jsg= new JavaSearchActionGroup(this)
});
fContextMenuGroup= new CompositeActionGroup(new ActionGroup[] {oeg, ovg, sg, jsg});
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", this, ISourceViewer.INFORMATION, true); //$NON-NLS-1$
action= new InformationDispatchAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", (TextOperationAction) action); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_JAVADOC);
setAction("ShowJavaDoc", action); //$NON-NLS-1$
fEncodingSupport= new DefaultEncodingSupport();
fEncodingSupport.initialize(this);
if (fMouseListener == null) {
fMouseListener= new MouseClickListener();
fMouseListener.install();
}
}
private boolean isTextSelectionEmpty() {
ISelection selection= getSelectionProvider().getSelection();
if (!(selection instanceof ITextSelection))
return true;
return ((ITextSelection)selection).getLength() == 0;
}
public void updatedTitleImage(Image image) {
setTitleImage(image);
}
/*
* @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
*/
protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
try {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
String property= event.getProperty();
if (PreferenceConstants.EDITOR_TAB_WIDTH.equals(property)) {
Object value= event.getNewValue();
if (value instanceof Integer) {
sourceViewer.getTextWidget().setTabs(((Integer) value).intValue());
} else if (value instanceof String) {
sourceViewer.getTextWidget().setTabs(Integer.parseInt((String) value));
}
return;
}
if (LINE_NUMBER_RULER.equals(property)) {
if (isLineNumberRulerVisible())
showLineNumberRuler();
else
hideLineNumberRuler();
return;
}
if (fLineNumberRulerColumn != null &&
(LINE_NUMBER_COLOR.equals(property) ||
PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT.equals(property) ||
PREFERENCE_COLOR_BACKGROUND.equals(property))) {
initializeLineNumberRulerColumn(fLineNumberRulerColumn);
}
if (isJavaEditorHoverProperty(property)) {
updateHoverBehavior();
}
} finally {
super.handlePreferenceStoreChanged(event);
}
}
private boolean isJavaEditorHoverProperty(String property) {
return PreferenceConstants.EDITOR_DEFAULT_HOVER.equals(property)
|| PreferenceConstants.EDITOR_NONE_HOVER.equals(property)
|| PreferenceConstants.EDITOR_CTRL_HOVER.equals(property)
|| PreferenceConstants.EDITOR_SHIFT_HOVER.equals(property)
|| PreferenceConstants.EDITOR_CTRL_ALT_HOVER.equals(property)
|| PreferenceConstants.EDITOR_CTRL_SHIFT_HOVER.equals(property)
|| PreferenceConstants.EDITOR_CTRL_ALT_SHIFT_HOVER.equals(property)
|| PreferenceConstants.EDITOR_ALT_SHIFT_HOVER.equals(property);
}
/**
* Shows the line number ruler column.
*/
private void showLineNumberRuler() {
IVerticalRuler v= getVerticalRuler();
if (v instanceof CompositeRuler) {
CompositeRuler c= (CompositeRuler) v;
c.addDecorator(1, createLineNumberRulerColumn());
}
}
/**
* Hides the line number ruler column.
*/
private void hideLineNumberRuler() {
IVerticalRuler v= getVerticalRuler();
if (v instanceof CompositeRuler) {
CompositeRuler c= (CompositeRuler) v;
c.removeDecorator(1);
}
}
/**
* Return whether the line number ruler column should be
* visible according to the preference store settings.
* @return <code>true</code> if the line numbers should be visible
*/
private boolean isLineNumberRulerVisible() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(LINE_NUMBER_RULER);
}
/**
* Returns a segmentation of the line of the given document appropriate for bidi rendering.
* The default implementation returns only the string literals of a java code line as segments.
*
* @param document the document
* @param lineOffset the offset of the line
* @return the line's bidi segmentation
* @throws BadLocationException in case lineOffset is not valid in document
*/
public static int[] getBidiLineSegments(IDocument document, int lineOffset) throws BadLocationException {
IRegion line= document.getLineInformationOfOffset(lineOffset);
ITypedRegion[] linePartitioning= document.computePartitioning(lineOffset, line.getLength());
List segmentation= new ArrayList();
for (int i= 0; i < linePartitioning.length; i++) {
if (JavaPartitionScanner.JAVA_STRING.equals(linePartitioning[i].getType()))
segmentation.add(linePartitioning[i]);
}
if (segmentation.size() == 0)
return null;
int size= segmentation.size();
int[] segments= new int[size * 2 + 1];
int j= 0;
for (int i= 0; i < size; i++) {
ITypedRegion segment= (ITypedRegion) segmentation.get(i);
if (i == 0)
segments[j++]= 0;
int offset= segment.getOffset() - lineOffset;
if (offset > segments[j - 1])
segments[j++]= offset;
if (offset + segment.getLength() >= line.getLength())
break;
segments[j++]= offset + segment.getLength();
}
if (j < segments.length) {
int[] result= new int[j];
System.arraycopy(segments, 0, result, 0, j);
segments= result;
}
return segments;
}
/**
* Returns a segmentation of the given line appropriate for bidi rendering. The default
* implementation returns only the string literals of a java code line as segments.
*
* @param lineOffset the offset of the line
* @param line the content of the line
* @return the line's bidi segmentation
*/
protected int[] getBidiLineSegments(int lineOffset, String line) {
IDocumentProvider provider= getDocumentProvider();
if (provider != null && line != null && line.length() > 0) {
IDocument document= provider.getDocument(getEditorInput());
if (document != null)
try {
return getBidiLineSegments(document, lineOffset);
} catch (BadLocationException x) {
// ignore
}
}
return null;
}
/*
* @see AbstractTextEditor#handleCursorPositionChanged()
*/
protected void handleCursorPositionChanged() {
super.handleCursorPositionChanged();
if (!isEditingScriptRunning() && fUpdater != null)
fUpdater.post();
}
/**
* Initializes the given line number ruler column from the preference store.
* @param rulerColumn the ruler column to be initialized
*/
protected void initializeLineNumberRulerColumn(LineNumberRulerColumn rulerColumn) {
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
IColorManager manager= textTools.getColorManager();
IPreferenceStore store= getPreferenceStore();
if (store != null) {
RGB rgb= null;
// foreground color
if (store.contains(LINE_NUMBER_COLOR)) {
if (store.isDefault(LINE_NUMBER_COLOR))
rgb= PreferenceConverter.getDefaultColor(store, LINE_NUMBER_COLOR);
else
rgb= PreferenceConverter.getColor(store, LINE_NUMBER_COLOR);
}
rulerColumn.setForeground(manager.getColor(rgb));
rgb= null;
// background color
if (!store.getBoolean(PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)) {
if (store.contains(PREFERENCE_COLOR_BACKGROUND)) {
if (store.isDefault(PREFERENCE_COLOR_BACKGROUND))
rgb= PreferenceConverter.getDefaultColor(store, PREFERENCE_COLOR_BACKGROUND);
else
rgb= PreferenceConverter.getColor(store, PREFERENCE_COLOR_BACKGROUND);
}
}
rulerColumn.setBackground(manager.getColor(rgb));
}
}
/**
* Creates a new line number ruler column that is appropriately initialized.
*/
protected IVerticalRulerColumn createLineNumberRulerColumn() {
fLineNumberRulerColumn= new LineNumberRulerColumn();
initializeLineNumberRulerColumn(fLineNumberRulerColumn);
return fLineNumberRulerColumn;
}
/*
* @see AbstractTextEditor#createVerticalRuler()
*/
protected IVerticalRuler createVerticalRuler() {
CompositeRuler ruler= new CompositeRuler();
ruler.addDecorator(0, new AnnotationRulerColumn(VERTICAL_RULER_WIDTH));
if (isLineNumberRulerVisible())
ruler.addDecorator(1, createLineNumberRulerColumn());
return ruler;
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#updatePropertyDependentActions()
*/
protected void updatePropertyDependentActions() {
super.updatePropertyDependentActions();
if (fEncodingSupport != null)
fEncodingSupport.reset();
}
/*
* Update the hovering behavior depending on the preferences.
*/
private void updateHoverBehavior() {
SourceViewerConfiguration configuration= getSourceViewerConfiguration();
String[] types= configuration.getConfiguredContentTypes(getSourceViewer());
for (int i= 0; i < types.length; i++) {
String t= types[i];
int[] stateMasks= configuration.getConfiguredTextHoverStateMasks(getSourceViewer(), t);
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer instanceof ITextViewerExtension2) {
if (stateMasks != null) {
for (int j= 0; j < stateMasks.length; j++) {
int stateMask= stateMasks[j];
ITextHover textHover= configuration.getTextHover(sourceViewer, t, stateMask);
((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, stateMask);
}
} else {
ITextHover textHover= configuration.getTextHover(sourceViewer, t);
((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK);
}
} else
sourceViewer.setTextHover(configuration.getTextHover(sourceViewer, t), t);
}
}
/*
* @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
*/
public Object getViewPartInput() {
return getEditorInput().getAdapter(IJavaElement.class);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetSelection(ISelection)
*/
protected void doSetSelection(ISelection selection) {
super.doSetSelection(selection);
synchronizeOutlinePageSelection();
}
/*
* @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.
* widgets.Composite)
*/
public void createPartControl(Composite parent) {
super.createPartControl(parent);
ISourceViewer sourceViewer= getSourceViewer();
SourceViewerConfiguration sourceViewerConfiguration= getSourceViewerConfiguration();
IInformationControlCreator informationControlCreator= new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell parent) {
boolean cutDown= false;
int style= cutDown ? SWT.NONE : (SWT.V_SCROLL | SWT.H_SCROLL);
return new DefaultInformationControl(parent, SWT.RESIZE, style, new HTMLTextPresenter(cutDown));
}
};
fInformationPresenter= new InformationPresenter(informationControlCreator);
fInformationPresenter.setSizeConstraints(60, 10, true, true);
fInformationPresenter.install(sourceViewer);
}
}
|
25,098 |
Bug 25098 Quickfix for The local variable may not have been initialized.. [quick fix]
|
Often I write code like this: String name; try { name = "Good value"; int val = name.indexOf(42); } catch(Exception e) { throw new RuntimeException("Something went wrong with " + name); } The declaration of name is placed outside the try clause to provide access to it inside the catch. Here eclipse (as it should) complains that "The local variable name may not have been initialized". How about providing a QuickFix that assigned null to the uninitialized variable (e.g. "String name = null")
|
resolved fixed
|
e554c60
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-26T10:49:36Z | 2002-10-19T15:06:40Z |
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/LocalCorrectionsQuickFixTest.java
|
package org.eclipse.jdt.ui.tests.quickfix;
import java.util.ArrayList;
import java.util.Hashtable;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.testplugin.JavaProjectHelper;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal;
import org.eclipse.jdt.internal.ui.text.correction.CorrectionContext;
import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionProcessor;
public class LocalCorrectionsQuickFixTest extends QuickFixTest {
private static final Class THIS= LocalCorrectionsQuickFixTest.class;
private IJavaProject fJProject1;
private IPackageFragmentRoot fSourceFolder;
public LocalCorrectionsQuickFixTest(String name) {
super(name);
}
public static Test suite() {
if (true) {
return new TestSuite(THIS);
} else {
TestSuite suite= new TestSuite();
suite.addTest(new LocalCorrectionsQuickFixTest("testUncaughtExceptionDuplicate"));
return suite;
}
}
protected void setUp() throws Exception {
Hashtable options= JavaCore.getDefaultOptions();
options.put(JavaCore.FORMATTER_TAB_CHAR, JavaCore.SPACE);
options.put(JavaCore.FORMATTER_TAB_SIZE, "4");
options.put(JavaCore.COMPILER_PB_STATIC_ACCESS_RECEIVER, JavaCore.ERROR);
JavaCore.setOptions(options);
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
store.setValue(PreferenceConstants.CODEGEN__FILE_COMMENTS, false);
store.setValue(PreferenceConstants.CODEGEN__JAVADOC_STUBS, false);
fJProject1= JavaProjectHelper.createJavaProject("TestProject1", "bin");
assertTrue("rt not found", JavaProjectHelper.addRTJar(fJProject1) != null);
fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
}
protected void tearDown() throws Exception {
JavaProjectHelper.delete(fJProject1);
}
public void testFieldAccessToStatic() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.File;\n");
buf.append("public class E {\n");
buf.append(" public char foo() {\n");
buf.append(" return (new File(\"x.txt\")).separatorChar;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.File;\n");
buf.append("public class E {\n");
buf.append(" public char foo() {\n");
buf.append(" return File.separatorChar;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testInheritedAccessOnStatic() throws Exception {
IPackageFragment pack0= fSourceFolder.createPackageFragment("pack", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class A {\n");
buf.append(" public static void foo() {\n");
buf.append(" }\n");
buf.append("}\n");
pack0.createCompilationUnit("A.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class B extends A {\n");
buf.append("}\n");
pack0.createCompilationUnit("B.java", buf.toString(), false, null);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import pack.B;\n");
buf.append("public class E {\n");
buf.append(" public void foo(B b) {\n");
buf.append(" b.foo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import pack.B;\n");
buf.append("public class E {\n");
buf.append(" public void foo(B b) {\n");
buf.append(" B.foo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import pack.A;\n");
buf.append("import pack.B;\n");
buf.append("public class E {\n");
buf.append(" public void foo(B b) {\n");
buf.append(" A.foo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testQualifiedAccessToStatic() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Thread t) {\n");
buf.append(" t.sleep(10);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Thread t) {\n");
buf.append(" Thread.sleep(10);\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testThisAccessToStatic() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public static void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" this.goo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public static void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" E.goo();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testCastMissingInVarDecl() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Object o) {\n");
buf.append(" Thread th= o;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Object o) {\n");
buf.append(" Thread th= (Thread) o;\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Object o) {\n");
buf.append(" Object th= o;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastMissingInVarDecl2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.List;\n");
buf.append("public class Container {\n");
buf.append(" public List[] getLists() {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("Container.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Container c) {\n");
buf.append(" ArrayList[] lists= c.getLists();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Container c) {\n");
buf.append(" ArrayList[] lists= (ArrayList[]) c.getLists();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Container c) {\n");
buf.append(" List[] lists= c.getLists();\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastMissingInFieldDecl() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" int time= System.currentTimeMillis();\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" int time= (int) System.currentTimeMillis();\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" long time= System.currentTimeMillis();\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastMissingInAssignment() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Iterator;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Iterator iter) {\n");
buf.append(" String str;\n");
buf.append(" str= iter.next();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Iterator;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Iterator iter) {\n");
buf.append(" String str;\n");
buf.append(" str= (String) iter.next();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testCastMissingInExpression() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public String[] foo(List list) {\n");
buf.append(" return list.toArray(new List[list.size()]);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public String[] foo(List list) {\n");
buf.append(" return (String[]) list.toArray(new List[list.size()]);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public Object[] foo(List list) {\n");
buf.append(" return list.toArray(new List[list.size()]);\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastOnCastExpression() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public void foo(List list) {\n");
buf.append(" ArrayList a= (Cloneable) list;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public void foo(List list) {\n");
buf.append(" ArrayList a= (ArrayList) list;\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public void foo(List list) {\n");
buf.append(" Cloneable a= (Cloneable) list;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUncaughtException() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUncaughtException2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public String goo() throws IOException {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo().substring(2);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public String goo() throws IOException {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException {\n");
buf.append(" goo().substring(2);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public String goo() throws IOException {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo().substring(2);\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUncaughtExceptionRemoveMoreSpecific() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.net.SocketException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() throws SocketException {\n");
buf.append(" this.goo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.net.SocketException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException {\n");
buf.append(" this.goo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.net.SocketException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() throws SocketException {\n");
buf.append(" try {\n");
buf.append(" this.goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
boolean BUG_25417= true;
public void testUncaughtExceptionDuplicate() throws Exception {
if (BUG_25417) {
return;
}
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class MyException extends Exception {\n");
buf.append("}\n");
pack1.createCompilationUnit("MyException.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void m1() throws IOException {\n");
buf.append(" m2();\n");
buf.append(" }\n");
buf.append(" public void m2() throws IOException, ParseException, MyException {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 2);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void m1() throws IOException, ParseException, MyException {\n");
buf.append(" m2();\n");
buf.append(" }\n");
buf.append(" public void m2() throws IOException, ParseException, MyException {\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void m1() throws IOException {\n");
buf.append(" try {\n");
buf.append(" m2();\n");
buf.append(" } catch (ParseException e) {\n");
buf.append(" } catch (MyException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" public void m2() throws IOException, ParseException, MyException {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testMultipleUncaughtExceptions() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException, ParseException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 2); // 2 uncaught exceptions
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException, ParseException {\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException, ParseException {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException, ParseException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" } catch (ParseException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUnneededCatchBlock() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" } catch (ParseException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnneededCatchBlockSingle() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnneededCatchBlockWithFinally() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" } finally {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } finally {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnimplementedMethods() throws Exception {
IPackageFragment pack2= fSourceFolder.createPackageFragment("test2", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test2;\n");
buf.append("import java.io.IOException;\n");
buf.append("public interface Inter {\n");
buf.append(" int getCount(Object[] o) throws IOException;\n");
buf.append("}\n");
pack2.createCompilationUnit("Inter.java", buf.toString(), false, null);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import test2.Inter;\n");
buf.append("public class E implements Inter{\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import test2.Inter;\n");
buf.append("public abstract class E implements Inter{\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("\n");
buf.append("import test2.Inter;\n");
buf.append("public class E implements Inter{\n");
buf.append(" public int getCount(Object[] o) throws IOException {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUnimplementedMethods2() throws Exception {
IPackageFragment pack2= fSourceFolder.createPackageFragment("test2", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test2;\n");
buf.append("import java.io.IOException;\n");
buf.append("public interface Inter {\n");
buf.append(" int getCount(Object[] o) throws IOException;\n");
buf.append("}\n");
pack2.createCompilationUnit("Inter.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test2;\n");
buf.append("import java.io.IOException;\n");
buf.append("public abstract class InterImpl implements Inter {\n");
buf.append(" protected abstract int[] getMusic() throws IOException;\n");
buf.append("}\n");
pack2.createCompilationUnit("InterImpl.java", buf.toString(), false, null);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import test2.InterImpl;\n");
buf.append("public class E extends InterImpl {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 2);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import test2.InterImpl;\n");
buf.append("public abstract class E extends InterImpl {\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("\n");
buf.append("import test2.InterImpl;\n");
buf.append("public class E extends InterImpl {\n");
buf.append(" protected int[] getMusic() throws IOException {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append(" public int getCount(Object[] o) throws IOException {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
}
|
25,098 |
Bug 25098 Quickfix for The local variable may not have been initialized.. [quick fix]
|
Often I write code like this: String name; try { name = "Good value"; int val = name.indexOf(42); } catch(Exception e) { throw new RuntimeException("Something went wrong with " + name); } The declaration of name is placed outside the try clause to provide access to it inside the catch. Here eclipse (as it should) complains that "The local variable name may not have been initialized". How about providing a QuickFix that assigned null to the uninitialized variable (e.g. "String name = null")
|
resolved fixed
|
e554c60
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-26T10:49:36Z | 2002-10-19T15:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ASTResolving.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.jdt.core.IBuffer;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.compiler.IScanner;
import org.eclipse.jdt.core.compiler.ITerminalSymbols;
import org.eclipse.jdt.core.compiler.InvalidInputException;
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jdt.internal.corext.dom.ASTNodes;
import org.eclipse.jdt.internal.corext.dom.Binding2JavaModel;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
public class ASTResolving {
public static ITypeBinding normalizeTypeBinding(ITypeBinding binding) {
if (binding != null && !binding.isNullType() && !"void".equals(binding.getName())) {
if (binding.isAnonymous()) {
ITypeBinding[] baseBindings= binding.getInterfaces();
if (baseBindings.length > 0) {
return baseBindings[0];
}
return binding.getSuperclass();
}
return binding;
}
return null;
}
public static ITypeBinding guessBindingForReference(ASTNode node) {
return normalizeTypeBinding(getPossibleReferenceBinding(node));
}
private static ITypeBinding getPossibleReferenceBinding(ASTNode node) {
ASTNode parent= node.getParent();
switch (parent.getNodeType()) {
case ASTNode.ASSIGNMENT:
Assignment assignment= (Assignment) parent;
if (node.equals(assignment.getLeftHandSide())) {
// field write access: xx= expression
return assignment.getRightHandSide().resolveTypeBinding();
}
// read access
return assignment.getLeftHandSide().resolveTypeBinding();
case ASTNode.INFIX_EXPRESSION:
InfixExpression infix= (InfixExpression) parent;
if (node.equals(infix.getLeftOperand())) {
// xx == expression
return infix.getRightOperand().resolveTypeBinding();
}
// expression == xx
InfixExpression.Operator op= infix.getOperator();
if (op == InfixExpression.Operator.LEFT_SHIFT || op == InfixExpression.Operator.RIGHT_SHIFT_UNSIGNED
|| op == InfixExpression.Operator.RIGHT_SHIFT_SIGNED) {
return infix.getAST().resolveWellKnownType("int"); //$NON-NLS-1$
}
return infix.getLeftOperand().resolveTypeBinding();
case ASTNode.INSTANCEOF_EXPRESSION:
InstanceofExpression instanceofExpression= (InstanceofExpression) parent;
return instanceofExpression.getRightOperand().resolveBinding();
case ASTNode.VARIABLE_DECLARATION_FRAGMENT:
VariableDeclarationFragment frag= (VariableDeclarationFragment) parent;
if (frag.getInitializer().equals(node)) {
ASTNode declaration= frag.getParent();
if (declaration instanceof VariableDeclarationStatement) {
return ((VariableDeclarationStatement)declaration).getType().resolveBinding();
} else if (declaration instanceof FieldDeclaration) {
return ((FieldDeclaration)declaration).getType().resolveBinding();
}
}
break;
case ASTNode.SUPER_METHOD_INVOCATION:
SuperMethodInvocation superMethodInvocation= (SuperMethodInvocation) parent;
IMethodBinding superMethodBinding= ASTNodes.getMethodBinding(superMethodInvocation.getName());
if (superMethodBinding != null) {
return getParameterTypeBinding(node, superMethodInvocation.arguments(), superMethodBinding);
}
break;
case ASTNode.METHOD_INVOCATION:
MethodInvocation methodInvocation= (MethodInvocation) parent;
IMethodBinding methodBinding= ASTNodes.getMethodBinding(methodInvocation.getName());
if (methodBinding != null) {
return getParameterTypeBinding(node, methodInvocation.arguments(), methodBinding);
}
break;
case ASTNode.SUPER_CONSTRUCTOR_INVOCATION:
SuperConstructorInvocation superInvocation= (SuperConstructorInvocation) parent;
IMethodBinding superBinding= superInvocation.resolveConstructorBinding();
if (superBinding != null) {
return getParameterTypeBinding(node, superInvocation.arguments(), superBinding);
}
break;
case ASTNode.CONSTRUCTOR_INVOCATION:
ConstructorInvocation constrInvocation= (ConstructorInvocation) parent;
IMethodBinding constrBinding= constrInvocation.resolveConstructorBinding();
if (constrBinding != null) {
return getParameterTypeBinding(node, constrInvocation.arguments(), constrBinding);
}
break;
case ASTNode.CLASS_INSTANCE_CREATION:
ClassInstanceCreation creation= (ClassInstanceCreation) parent;
IMethodBinding creationBinding= creation.resolveConstructorBinding();
if (creationBinding != null) {
return getParameterTypeBinding(node, creation.arguments(), creationBinding);
}
break;
case ASTNode.PARENTHESIZED_EXPRESSION:
return guessBindingForReference(parent);
case ASTNode.ARRAY_ACCESS:
if (((ArrayAccess) parent).getIndex().equals(node)) {
return parent.getAST().resolveWellKnownType("int"); //$NON-NLS-1$
}
break;
case ASTNode.ARRAY_CREATION:
if (((ArrayCreation) parent).dimensions().contains(node)) {
return parent.getAST().resolveWellKnownType("int"); //$NON-NLS-1$
}
break;
case ASTNode.ARRAY_INITIALIZER:
ASTNode initializerParent= parent.getParent();
if (initializerParent instanceof ArrayCreation) {
return ((ArrayCreation) initializerParent).getType().getElementType().resolveBinding();
}
break;
case ASTNode.CONDITIONAL_EXPRESSION:
ConditionalExpression expression= (ConditionalExpression) parent;
if (node.equals(expression.getExpression())) {
return parent.getAST().resolveWellKnownType("boolean"); //$NON-NLS-1$
}
if (node.equals(expression.getElseExpression())) {
return expression.getThenExpression().resolveTypeBinding();
}
return expression.getElseExpression().resolveTypeBinding();
case ASTNode.POSTFIX_EXPRESSION:
return parent.getAST().resolveWellKnownType("int"); //$NON-NLS-1$
case ASTNode.PREFIX_EXPRESSION:
if (((PrefixExpression) parent).getOperator() == PrefixExpression.Operator.NOT) {
return parent.getAST().resolveWellKnownType("boolean"); //$NON-NLS-1$
}
return parent.getAST().resolveWellKnownType("int"); //$NON-NLS-1$
case ASTNode.IF_STATEMENT:
case ASTNode.WHILE_STATEMENT:
case ASTNode.DO_STATEMENT:
if (node instanceof Expression) {
return parent.getAST().resolveWellKnownType("boolean"); //$NON-NLS-1$
}
break;
case ASTNode.SWITCH_STATEMENT:
if (((SwitchStatement) parent).getExpression().equals(node)) {
return parent.getAST().resolveWellKnownType("int"); //$NON-NLS-1$
}
break;
case ASTNode.RETURN_STATEMENT:
MethodDeclaration decl= findParentMethodDeclaration(parent);
if (decl != null) {
return decl.getReturnType().resolveBinding();
}
break;
case ASTNode.CAST_EXPRESSION:
return ((CastExpression) parent).getType().resolveBinding();
case ASTNode.THROW_STATEMENT:
case ASTNode.CATCH_CLAUSE:
return parent.getAST().resolveWellKnownType("java.lang.Exception"); //$NON-NLS-1$
case ASTNode.FIELD_ACCESS:
if (node.equals(((FieldAccess) parent).getName())) {
return getPossibleReferenceBinding(parent);
}
break;
case ASTNode.QUALIFIED_NAME:
if (node.equals(((QualifiedName) parent).getName())) {
return getPossibleReferenceBinding(parent);
}
break;
}
return null;
}
private static ITypeBinding getParameterTypeBinding(ASTNode node, List args, IMethodBinding binding) {
ITypeBinding[] paramTypes= binding.getParameterTypes();
int index= args.indexOf(node);
if (index >= 0 && index < paramTypes.length) {
return paramTypes[index];
}
return null;
}
public static ITypeBinding guessBindingForTypeReference(ASTNode node) {
return normalizeTypeBinding(getPossibleTypeBinding(node));
}
private static ITypeBinding getPossibleTypeBinding(ASTNode node) {
ASTNode parent= node.getParent();
while (parent instanceof Type) {
parent= parent.getParent();
}
switch (parent.getNodeType()) {
case ASTNode.VARIABLE_DECLARATION_STATEMENT:
return guessVariableType(((VariableDeclarationStatement) parent).fragments());
case ASTNode.FIELD_DECLARATION:
return guessVariableType(((FieldDeclaration) parent).fragments());
case ASTNode.VARIABLE_DECLARATION_EXPRESSION:
return guessVariableType(((VariableDeclarationExpression) parent).fragments());
case ASTNode.SINGLE_VARIABLE_DECLARATION:
SingleVariableDeclaration varDecl= (SingleVariableDeclaration) parent;
if (varDecl.getInitializer() != null) {
return varDecl.getInitializer().resolveTypeBinding();
}
break;
case ASTNode.ARRAY_CREATION:
ArrayCreation creation= (ArrayCreation) parent;
if (creation.getInitializer() != null) {
return creation.getInitializer().resolveTypeBinding();
}
return getPossibleReferenceBinding(parent);
case ASTNode.TYPE_LITERAL:
case ASTNode.CLASS_INSTANCE_CREATION:
return getPossibleReferenceBinding(parent);
}
return null;
}
private static ITypeBinding guessVariableType(List fragments) {
for (Iterator iter= fragments.iterator(); iter.hasNext();) {
VariableDeclarationFragment frag= (VariableDeclarationFragment) iter.next();
if (frag.getInitializer() != null) {
return frag.getInitializer().resolveTypeBinding();
}
}
return null;
}
public static MethodDeclaration findParentMethodDeclaration(ASTNode node) {
while ((node != null) && (node.getNodeType() != ASTNode.METHOD_DECLARATION)) {
node= node.getParent();
}
return (MethodDeclaration) node;
}
public static BodyDeclaration findParentBodyDeclaration(ASTNode node) {
while ((node != null) && (!(node instanceof BodyDeclaration))) {
node= node.getParent();
}
return (BodyDeclaration) node;
}
public static CompilationUnit findParentCompilationUnit(ASTNode node) {
return (CompilationUnit) findAncestor(node, ASTNode.COMPILATION_UNIT);
}
/**
* Returns either a TypeDeclaration or an AnonymousTypeDeclaration
* @param node
* @return CompilationUnit
*/
public static ASTNode findParentType(ASTNode node) {
while ((node != null) && (node.getNodeType() != ASTNode.TYPE_DECLARATION) && (node.getNodeType() != ASTNode.ANONYMOUS_CLASS_DECLARATION)) {
node= node.getParent();
}
return node;
}
public static ASTNode findAncestor(ASTNode node, int nodeType) {
while ((node != null) && (node.getNodeType() != nodeType)) {
node= node.getParent();
}
return node;
}
/**
* Returns the type binding of the node's parent type declararation
* @param node
* @return CompilationUnit
*/
public static ITypeBinding getBindingOfParentType(ASTNode node) {
while (node != null) {
if (node instanceof TypeDeclaration) {
return ((TypeDeclaration) node).resolveBinding();
} else if (node instanceof AnonymousClassDeclaration) {
return ((AnonymousClassDeclaration) node).resolveBinding();
}
node= node.getParent();
}
return null;
}
public static Statement findParentStatement(ASTNode node) {
while ((node != null) && (!(node instanceof Statement))) {
node= node.getParent();
}
return (Statement) node;
}
public static boolean isInStaticContext(ASTNode selectedNode) {
BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
if (decl instanceof MethodDeclaration) {
return Modifier.isStatic(((MethodDeclaration)decl).getModifiers());
} else if (decl instanceof Initializer) {
return Modifier.isStatic(((Initializer)decl).getModifiers());
} else if (decl instanceof FieldDeclaration) {
return Modifier.isStatic(((FieldDeclaration)decl).getModifiers());
}
return false;
}
public static IScanner createScanner(ICompilationUnit cu, int pos) throws InvalidInputException, JavaModelException {
IScanner scanner= ToolFactory.createScanner(false, false, false, false);
IBuffer buf= cu.getBuffer();
scanner.setSource(buf.getCharacters());
scanner.resetTo(pos, buf.getLength());
return scanner;
}
public static void overreadToken(IScanner scanner, int[] prevTokens) throws InvalidInputException {
boolean found;
do {
found= false;
int curr= scanner.getNextToken();
if (curr == ITerminalSymbols.TokenNameEOF) {
throw new InvalidInputException("End of File");
}
for (int i= 0; i < prevTokens.length; i++) {
if (prevTokens[i] == curr) {
found= true;
break;
}
}
} while (found);
}
public static void readToToken(IScanner scanner, int tok) throws InvalidInputException {
int curr= 0;
do {
curr= scanner.getNextToken();
if (curr == ITerminalSymbols.TokenNameEOF) {
throw new InvalidInputException("End of File");
}
} while (curr != tok);
}
public static int getPositionAfter(IScanner scanner, int token) throws InvalidInputException {
readToToken(scanner, token);
return scanner.getCurrentTokenEndPosition() + 1;
}
public static int getPositionBefore(IScanner scanner, int token) throws InvalidInputException {
readToToken(scanner, token);
return scanner.getCurrentTokenStartPosition();
}
public static int getPositionAfter(IScanner scanner, int defaultPos, int[] tokens) throws InvalidInputException {
int pos= defaultPos;
loop: while(true) {
int curr= scanner.getNextToken();
if (curr == ITerminalSymbols.TokenNameEOF) {
return pos;
}
for (int i= 0; i < tokens.length; i++) {
if (tokens[i] == curr) {
pos= scanner.getCurrentTokenEndPosition() + 1;
continue loop;
}
}
return pos;
}
}
public static Type getTypeFromTypeBinding(AST ast, ITypeBinding binding) {
if (binding.isArray()) {
int dim= binding.getDimensions();
return ast.newArrayType(getTypeFromTypeBinding(ast, binding.getElementType()), dim);
} else if (binding.isPrimitive()) {
String name= binding.getName();
return ast.newPrimitiveType(PrimitiveType.toCode(name));
} else if (!binding.isNullType() && !binding.isAnonymous()) {
return ast.newSimpleType(ast.newSimpleName(binding.getName()));
}
return null;
}
public static Expression getInitExpression(Type type, int extraDimensions) {
if (extraDimensions == 0 && type.isPrimitiveType()) {
PrimitiveType primitiveType= (PrimitiveType) type;
if (primitiveType.getPrimitiveTypeCode() == PrimitiveType.BOOLEAN) {
return type.getAST().newBooleanLiteral(false);
} else if (primitiveType.getPrimitiveTypeCode() == PrimitiveType.VOID) {
return null;
} else {
return type.getAST().newNumberLiteral("0");
}
}
return type.getAST().newNullLiteral();
}
private static class NodeFoundException extends RuntimeException {
public ASTNode node;
}
public static ASTNode findClonedNode(ASTNode cloneRoot, final ASTNode node) {
try {
cloneRoot.accept(new ASTVisitor() {
public void preVisit(ASTNode curr) {
if (curr.getNodeType() == node.getNodeType() && curr.getStartPosition() == node.getStartPosition() && curr.getLength() == node.getLength()) {
NodeFoundException exc= new NodeFoundException();
exc.node= curr;
throw exc;
}
}
});
} catch (NodeFoundException e) {
return e.node;
}
return null;
}
private static TypeDeclaration findTypeDeclaration(List decls, String name) {
for (Iterator iter= decls.iterator(); iter.hasNext();) {
ASTNode elem= (ASTNode) iter.next();
if (elem instanceof TypeDeclaration) {
TypeDeclaration decl= (TypeDeclaration) elem;
if (name.equals(decl.getName().getIdentifier())) {
return decl;
}
}
}
return null;
}
public static TypeDeclaration findTypeDeclaration(CompilationUnit root, ITypeBinding binding) {
ArrayList names= new ArrayList(5);
while (binding != null) {
names.add(binding.getName());
binding= binding.getDeclaringClass();
}
List types= root.types();
for (int i= names.size() - 1; i >= 0; i--) {
String name= (String) names.get(i);
TypeDeclaration decl= findTypeDeclaration(types, name);
if (decl == null || i == 0) {
return decl;
}
types= decl.bodyDeclarations();
}
return null;
}
public static String getFullName(Name name) {
return ASTNodes.asString(name);
}
public static String getQualifier(Name name) {
if (name.isQualifiedName()) {
return getFullName(((QualifiedName) name).getQualifier());
}
return "";
}
public static String getSimpleName(Name name) {
if (name.isQualifiedName()) {
return ((QualifiedName) name).getName().getIdentifier();
} else {
return ((SimpleName) name).getIdentifier();
}
}
public static ICompilationUnit findCompilationUnitForBinding(ICompilationUnit cu, CompilationUnit astRoot, ITypeBinding binding) throws JavaModelException {
if (binding != null && binding.isFromSource() && astRoot.findDeclaringNode(binding) == null) {
ICompilationUnit targetCU= Binding2JavaModel.findCompilationUnit(binding, cu.getJavaProject());
if (targetCU != null) {
return JavaModelUtil.toWorkingCopy(targetCU);
}
return null;
}
return cu;
}
}
|
25,098 |
Bug 25098 Quickfix for The local variable may not have been initialized.. [quick fix]
|
Often I write code like this: String name; try { name = "Good value"; int val = name.indexOf(42); } catch(Exception e) { throw new RuntimeException("Something went wrong with " + name); } The declaration of name is placed outside the try clause to provide access to it inside the catch. Here eclipse (as it should) complains that "The local variable name may not have been initialized". How about providing a QuickFix that assigned null to the uninitialized variable (e.g. "String name = null")
|
resolved fixed
|
e554c60
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-26T10:49:36Z | 2002-10-19T15:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/LocalCorrectionsSubProcessor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Renaud Waldura <[email protected]> - Access to static proposal
******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportEdit;
import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory;
import org.eclipse.jdt.internal.corext.dom.ASTNodes;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
import org.eclipse.jdt.internal.corext.dom.Selection;
import org.eclipse.jdt.internal.corext.refactoring.changes.CompilationUnitChange;
import org.eclipse.jdt.internal.corext.refactoring.nls.NLSRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.nls.NLSUtil;
import org.eclipse.jdt.internal.corext.refactoring.surround.ExceptionAnalyzer;
import org.eclipse.jdt.internal.corext.refactoring.surround.SurroundWithTryCatchRefactoring;
import org.eclipse.jdt.internal.corext.textmanipulation.TextEdit;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter;
import org.eclipse.jdt.internal.ui.refactoring.nls.ExternalizeWizard;
/**
*/
public class LocalCorrectionsSubProcessor {
public static void addCastProposals(ICorrectionContext context, List proposals) throws CoreException {
String[] args= context.getProblemArguments();
if (args.length != 2) {
return;
}
ICompilationUnit cu= context.getCompilationUnit();
String castType= args[1];
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= context.getCoveredNode();
if (!(selectedNode instanceof Expression)) {
return;
}
Expression nodeToCast= (Expression) selectedNode;
int parentNodeType= selectedNode.getParent().getNodeType();
if (parentNodeType == ASTNode.ASSIGNMENT) {
Assignment assign= (Assignment) selectedNode.getParent();
if (selectedNode.equals(assign.getLeftHandSide())) {
nodeToCast= assign.getRightHandSide();
}
} else if (parentNodeType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
VariableDeclarationFragment frag= (VariableDeclarationFragment) selectedNode.getParent();
if (selectedNode.equals(frag.getName())) {
nodeToCast= frag.getInitializer();
}
}
{
ASTRewrite rewrite= new ASTRewrite(nodeToCast.getParent());
String label;
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 1, image);
String simpleCastType= proposal.addImport(castType);
if (nodeToCast.getNodeType() == ASTNode.CAST_EXPRESSION) {
label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changecast.description", castType); //$NON-NLS-1$
CastExpression expression= (CastExpression) nodeToCast;
rewrite.markAsReplaced(expression.getType(), rewrite.createPlaceholder(simpleCastType, ASTRewrite.TYPE));
} else {
label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.addcast.description", castType); //$NON-NLS-1$
Expression expressionCopy= (Expression) rewrite.createCopy(nodeToCast);
Type typeCopy= (Type) rewrite.createPlaceholder(simpleCastType, ASTRewrite.TYPE);
CastExpression castExpression= astRoot.getAST().newCastExpression();
castExpression.setExpression(expressionCopy);
castExpression.setType(typeCopy);
rewrite.markAsReplaced(nodeToCast, castExpression);
}
proposal.setDisplayName(label);
proposal.ensureNoModifications();
proposals.add(proposal);
}
// change method return statement to actual type
if (parentNodeType == ASTNode.RETURN_STATEMENT) {
ITypeBinding binding= nodeToCast.resolveTypeBinding();
BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
if (binding != null && decl instanceof MethodDeclaration) {
MethodDeclaration methodDeclaration= (MethodDeclaration) decl;
ASTRewrite rewrite= new ASTRewrite(methodDeclaration);
Type newReturnType= ASTResolving.getTypeFromTypeBinding(astRoot.getAST(), binding);
rewrite.markAsReplaced(methodDeclaration.getReturnType(), newReturnType);
String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changereturntype.description", binding.getName()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 2, image);
proposal.addImport(binding);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
if (parentNodeType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
VariableDeclarationFragment fragment= (VariableDeclarationFragment) selectedNode.getParent();
ASTNode parent= fragment.getParent();
Type type= null;
if (parent instanceof VariableDeclarationStatement) {
VariableDeclarationStatement stmt= (VariableDeclarationStatement) parent;
if (stmt.fragments().size() == 1) {
type= stmt.getType();
}
} else if (parent instanceof FieldDeclaration) {
FieldDeclaration decl= (FieldDeclaration) parent;
if (decl.fragments().size() == 1) {
type= decl.getType();
}
}
if (type != null) {
ImportEdit edit= new ImportEdit(cu, JavaPreferencesSettings.getCodeGenerationSettings());
String typeName= edit.addImport(args[0]);
String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.addcast_var.description", typeName); //$NON-NLS-1$
ReplaceCorrectionProposal varProposal= new ReplaceCorrectionProposal(label, cu, type.getStartPosition(), type.getLength(), typeName, 1);
varProposal.getRootTextEdit().add(edit);
proposals.add(varProposal);
}
}
}
public static void addUncaughtExceptionProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= context.getCoveredNode();
if (selectedNode == null) {
return;
}
while (selectedNode != null && !(selectedNode instanceof Statement)) {
selectedNode= selectedNode.getParent();
}
if (selectedNode == null) {
return;
}
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
SurroundWithTryCatchRefactoring refactoring= new SurroundWithTryCatchRefactoring(cu, selectedNode.getStartPosition(), selectedNode.getLength(), settings, null);
refactoring.setSaveChanges(false);
if (refactoring.checkActivationBasics(astRoot, null).isOK()) {
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.surroundwith.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
CUCorrectionProposal proposal= new CUCorrectionProposal(label, (CompilationUnitChange) refactoring.createChange(null), 4, image);
proposals.add(proposal);
}
BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
if (decl == null) {
return;
}
ITypeBinding[] uncaughtExceptions= ExceptionAnalyzer.perform(decl, Selection.createFromStartLength(selectedNode.getStartPosition(), selectedNode.getLength()));
TryStatement surroundingTry= (TryStatement) ASTNodes.getParent(selectedNode, ASTNode.TRY_STATEMENT);
if (surroundingTry != null) {
ASTRewrite rewrite= new ASTRewrite(surroundingTry);
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addadditionalcatch.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 5, image);
AST ast= astRoot.getAST();
List catchClauses= surroundingTry.catchClauses();
for (int i= 0; i < uncaughtExceptions.length; i++) {
String imp= proposal.addImport(uncaughtExceptions[i]);
Name name= ASTNodeFactory.newName(ast, imp);
SingleVariableDeclaration var= ast.newSingleVariableDeclaration();
var.setName(ast.newSimpleName("e"));
var.setType(ast.newSimpleType(name));
CatchClause newClause= ast.newCatchClause();
newClause.setException(var);
rewrite.markAsInserted(newClause);
catchClauses.add(newClause);
}
proposal.ensureNoModifications();
proposals.add(proposal);
}
if (decl instanceof MethodDeclaration) {
ASTRewrite rewrite= new ASTRewrite(astRoot);
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addthrows.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 6, image);
AST ast= astRoot.getAST();
MethodDeclaration methodDecl= (MethodDeclaration) decl;
List exceptions= methodDecl.thrownExceptions();
for (int i= 0; i < uncaughtExceptions.length; i++) {
String imp= proposal.addImport(uncaughtExceptions[i]);
Name name= ASTNodeFactory.newName(ast, imp);
rewrite.markAsInserted(name);
exceptions.add(name);
}
for (int i= 0; i < exceptions.size(); i++) {
Name elem= (Name) exceptions.get(i);
if (canRemove(elem.resolveTypeBinding(), uncaughtExceptions)) {
rewrite.markAsRemoved(elem);
}
}
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
private static boolean canRemove(ITypeBinding curr, ITypeBinding[] addedExceptions) {
while (curr != null) {
for (int i= 0; i < addedExceptions.length; i++) {
if (curr == addedExceptions[i]) {
return true;
}
}
curr= curr.getSuperclass();
}
return false;
}
public static void addUnreachableCatchProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= context.getCoveringNode();
if (selectedNode == null) {
return;
}
if (selectedNode.getNodeType() == ASTNode.BLOCK && selectedNode.getParent().getNodeType() == ASTNode.CATCH_CLAUSE ) {
CatchClause clause= (CatchClause) selectedNode.getParent();
TryStatement tryStatement= (TryStatement) clause.getParent();
ASTRewrite rewrite= new ASTRewrite(tryStatement.getParent());
if (tryStatement.catchClauses().size() > 1 || tryStatement.getFinally() != null) {
rewrite.markAsRemoved(clause);
} else {
List statements= tryStatement.getBody().statements();
if (statements.size() > 0) {
ASTNode placeholder= rewrite.createCopy((ASTNode) statements.get(0), (ASTNode) statements.get(statements.size() - 1));
rewrite.markAsReplaced(tryStatement, placeholder);
} else {
rewrite.markAsRemoved(tryStatement);
}
}
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.removecatchclause.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 6, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
public static void addNLSProposals(ICorrectionContext context, List proposals) throws CoreException {
final ICompilationUnit cu= context.getCompilationUnit();
String name= CorrectionMessages.getString("LocalCorrectionsSubProcessor.externalizestrings.description"); //$NON-NLS-1$
ChangeCorrectionProposal proposal= new ChangeCorrectionProposal(name, null, 0) {
public void apply(IDocument document) {
try {
NLSRefactoring refactoring= new NLSRefactoring(cu);
ExternalizeWizard wizard= new ExternalizeWizard(refactoring);
String dialogTitle= CorrectionMessages.getString("LocalCorrectionsSubProcessor.externalizestrings.dialog.title"); //$NON-NLS-1$
new RefactoringStarter().activate(refactoring, wizard, dialogTitle, true);
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
};
proposals.add(proposal);
TextEdit edit= NLSUtil.createNLSEdit(cu, context.getOffset());
if (edit != null) {
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addnon-nls.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_NLS_NEVER_TRANSLATE);
CUCorrectionProposal nlsProposal= new CUCorrectionProposal(label, cu, 6, image);
nlsProposal.getRootTextEdit().add(edit);
proposals.add(nlsProposal);
}
}
/**
* A static field or method is accessed using a non-static reference. E.g.
* <pre>
* File f = new File();
* f.pathSeparator;
* </pre>
* This correction changes <code>f</code> above to <code>File</code>.
*
* @param context
* @param proposals
*/
public static void addInstanceAccessToStaticProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= context.getCoveredNode();
if (selectedNode == null) {
return;
}
Expression qualifier= null;
IBinding accessBinding= null;
if (selectedNode instanceof QualifiedName) {
QualifiedName name= (QualifiedName) selectedNode;
qualifier= name.getQualifier();
accessBinding= name.resolveBinding();
} else if (selectedNode instanceof SimpleName) {
ASTNode parent= selectedNode.getParent();
if (parent instanceof FieldAccess) {
FieldAccess fieldAccess= (FieldAccess) parent;
qualifier= fieldAccess.getExpression();
accessBinding= fieldAccess.getName().resolveBinding();
}
} else if (selectedNode instanceof MethodInvocation) {
MethodInvocation methodInvocation= (MethodInvocation) selectedNode;
qualifier= methodInvocation.getExpression();
accessBinding= methodInvocation.getName().resolveBinding();
}
ITypeBinding declaringTypeBinding= null;
if (accessBinding != null) {
if (accessBinding instanceof IMethodBinding) {
declaringTypeBinding= ((IMethodBinding) accessBinding).getDeclaringClass();
} else if (accessBinding instanceof IVariableBinding) {
declaringTypeBinding= ((IVariableBinding) accessBinding).getDeclaringClass();
}
if (declaringTypeBinding != null) {
ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent());
rewrite.markAsReplaced(qualifier, astRoot.getAST().newSimpleName(declaringTypeBinding.getName()));
String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changeaccesstostaticdefining.description", declaringTypeBinding.getName());
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 2, image);
proposal.addImport(declaringTypeBinding);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
if (qualifier != null) {
ITypeBinding instanceTypeBinding= ASTResolving.normalizeTypeBinding(qualifier.resolveTypeBinding());
if (instanceTypeBinding != null && instanceTypeBinding != declaringTypeBinding) {
ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent());
rewrite.markAsReplaced(qualifier, astRoot.getAST().newSimpleName(instanceTypeBinding.getName()));
String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changeaccesstostatic.description", instanceTypeBinding.getName());
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 1, image);
proposal.addImport(instanceTypeBinding);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
}
public static void addUnimplementedMethodsProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= context.getCoveringNode();
if (selectedNode == null) {
return;
}
ASTNode typeNode= null;
if (selectedNode.getNodeType() == ASTNode.SIMPLE_NAME && selectedNode.getParent().getNodeType() == ASTNode.TYPE_DECLARATION) {
typeNode= selectedNode.getParent();
} else if (selectedNode.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION) {
ClassInstanceCreation creation= (ClassInstanceCreation) selectedNode;
typeNode= creation.getAnonymousClassDeclaration();
}
if (typeNode != null) {
UnimplementedMethodsCompletionProposal proposal= new UnimplementedMethodsCompletionProposal(cu, typeNode, 0);
proposals.add(proposal);
}
if (typeNode instanceof TypeDeclaration) {
TypeDeclaration typeDeclaration= (TypeDeclaration) typeNode;
ASTRewriteCorrectionProposal proposal= ModifierCorrectionSubProcessor.getMakeTypeStaticProposal(cu, typeDeclaration);
proposals.add(proposal);
}
}
}
|
25,098 |
Bug 25098 Quickfix for The local variable may not have been initialized.. [quick fix]
|
Often I write code like this: String name; try { name = "Good value"; int val = name.indexOf(42); } catch(Exception e) { throw new RuntimeException("Something went wrong with " + name); } The declaration of name is placed outside the try clause to provide access to it inside the catch. Here eclipse (as it should) complains that "The local variable name may not have been initialized". How about providing a QuickFix that assigned null to the uninitialized variable (e.g. "String name = null")
|
resolved fixed
|
e554c60
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-26T10:49:36Z | 2002-10-19T15:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/QuickFixProcessor.java
|
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.compiler.IProblem;
/**
*/
public class QuickFixProcessor implements ICorrectionProcessor {
public static boolean hasCorrections(int problemId) {
switch (problemId) {
case IProblem.UnterminatedString:
case IProblem.UnusedImport:
case IProblem.DuplicateImport:
case IProblem.CannotImportPackage:
case IProblem.ConflictingImport:
case IProblem.UndefinedMethod:
case IProblem.UndefinedConstructor:
case IProblem.ParameterMismatch:
case IProblem.MethodButWithConstructorName:
case IProblem.UndefinedField:
case IProblem.UndefinedName:
case IProblem.PublicClassMustMatchFileName:
case IProblem.PackageIsNotExpectedPackage:
case IProblem.UndefinedType:
case IProblem.FieldTypeNotFound:
case IProblem.ArgumentTypeNotFound:
case IProblem.ReturnTypeNotFound:
case IProblem.SuperclassNotFound:
case IProblem.ExceptionTypeNotFound:
case IProblem.InterfaceNotFound:
case IProblem.TypeMismatch:
case IProblem.UnhandledException:
case IProblem.UnreachableCatch:
case IProblem.VoidMethodReturnsValue:
case IProblem.ShouldReturnValue:
case IProblem.MissingReturnType:
case IProblem.NonExternalizedStringLiteral:
case IProblem.NonStaticAccessToStaticField:
case IProblem.NonStaticAccessToStaticMethod:
case IProblem.StaticMethodRequested:
case IProblem.NonStaticFieldFromStaticInvocation:
case IProblem.InstanceMethodDuringConstructorInvocation:
case IProblem.InstanceFieldDuringConstructorInvocation:
case IProblem.NotVisibleMethod:
case IProblem.NotVisibleConstructor:
case IProblem.NotVisibleType:
case IProblem.SuperclassNotVisible:
case IProblem.InterfaceNotVisible:
case IProblem.FieldTypeNotVisible:
case IProblem.ArgumentTypeNotVisible:
case IProblem.ReturnTypeNotVisible:
case IProblem.ExceptionTypeNotVisible:
case IProblem.NotVisibleField:
case IProblem.ImportNotVisible:
case IProblem.BodyForAbstractMethod:
case IProblem.AbstractMethodInAbstractClass:
case IProblem.AbstractMethodMustBeImplemented:
case IProblem.BodyForNativeMethod:
case IProblem.OuterLocalMustBeFinal:
return true;
default:
return false;
}
}
public void process(ICorrectionContext context, List proposals) throws CoreException {
int id= context.getProblemId();
if (id == 0) { // no proposals for none-problem locations
return;
}
switch (id) {
case IProblem.UnterminatedString:
String quoteLabel= CorrectionMessages.getString("JavaCorrectionProcessor.addquote.description"); //$NON-NLS-1$
int pos= InsertCorrectionProposal.moveBack(context.getOffset() + context.getLength(), context.getOffset(), "\n\r", context.getCompilationUnit()); //$NON-NLS-1$
proposals.add(new InsertCorrectionProposal(quoteLabel, context.getCompilationUnit(), pos, "\"", 0)); //$NON-NLS-1$
break;
case IProblem.UnusedImport:
case IProblem.DuplicateImport:
case IProblem.CannotImportPackage:
case IProblem.ConflictingImport:
ReorgCorrectionsSubProcessor.removeImportStatementProposals(context, proposals);
break;
case IProblem.UndefinedMethod:
UnresolvedElementsSubProcessor.getMethodProposals(context, false, proposals);
break;
case IProblem.UndefinedConstructor:
UnresolvedElementsSubProcessor.getConstructorProposals(context, proposals);
break;
case IProblem.ParameterMismatch:
UnresolvedElementsSubProcessor.getMethodProposals(context, true, proposals);
break;
case IProblem.MethodButWithConstructorName:
ReturnTypeSubProcessor.addMethodWithConstrNameProposals(context, proposals);
break;
case IProblem.UndefinedField:
case IProblem.UndefinedName:
UnresolvedElementsSubProcessor.getVariableProposals(context, proposals);
break;
case IProblem.PublicClassMustMatchFileName:
ReorgCorrectionsSubProcessor.getWrongTypeNameProposals(context, proposals);
break;
case IProblem.PackageIsNotExpectedPackage:
ReorgCorrectionsSubProcessor.getWrongPackageDeclNameProposals(context, proposals);
break;
case IProblem.UndefinedType:
case IProblem.FieldTypeNotFound:
case IProblem.ArgumentTypeNotFound:
case IProblem.ReturnTypeNotFound:
case IProblem.SuperclassNotFound:
case IProblem.ExceptionTypeNotFound:
case IProblem.InterfaceNotFound:
UnresolvedElementsSubProcessor.getTypeProposals(context, proposals);
break;
case IProblem.TypeMismatch:
LocalCorrectionsSubProcessor.addCastProposals(context, proposals);
break;
case IProblem.UnhandledException:
LocalCorrectionsSubProcessor.addUncaughtExceptionProposals(context, proposals);
break;
case IProblem.UnreachableCatch:
LocalCorrectionsSubProcessor.addUnreachableCatchProposals(context, proposals);
break;
case IProblem.VoidMethodReturnsValue:
ReturnTypeSubProcessor.addVoidMethodReturnsProposals(context, proposals);
break;
case IProblem.MissingReturnType:
ReturnTypeSubProcessor.addMissingReturnTypeProposals(context, proposals);
break;
case IProblem.ShouldReturnValue:
ReturnTypeSubProcessor.addMissingReturnStatementProposals(context, proposals);
break;
case IProblem.NonExternalizedStringLiteral:
LocalCorrectionsSubProcessor.addNLSProposals(context, proposals);
break;
case IProblem.NonStaticAccessToStaticField:
case IProblem.NonStaticAccessToStaticMethod:
LocalCorrectionsSubProcessor.addInstanceAccessToStaticProposals(context, proposals);
break;
case IProblem.StaticMethodRequested:
case IProblem.NonStaticFieldFromStaticInvocation:
case IProblem.InstanceMethodDuringConstructorInvocation:
case IProblem.InstanceFieldDuringConstructorInvocation:
ModifierCorrectionSubProcessor.addNonAccessibleMemberProposal(context, proposals, false);
break;
case IProblem.NotVisibleMethod:
case IProblem.NotVisibleConstructor:
case IProblem.NotVisibleType:
case IProblem.SuperclassNotVisible:
case IProblem.InterfaceNotVisible:
case IProblem.FieldTypeNotVisible:
case IProblem.ArgumentTypeNotVisible:
case IProblem.ReturnTypeNotVisible:
case IProblem.ExceptionTypeNotVisible:
case IProblem.NotVisibleField:
case IProblem.ImportNotVisible:
ModifierCorrectionSubProcessor.addNonAccessibleMemberProposal(context, proposals, true);
break;
case IProblem.BodyForAbstractMethod:
case IProblem.AbstractMethodInAbstractClass:
ModifierCorrectionSubProcessor.addAbstractMethodProposals(context, proposals);
break;
case IProblem.AbstractMethodMustBeImplemented:
LocalCorrectionsSubProcessor.addUnimplementedMethodsProposals(context, proposals);
break;
case IProblem.BodyForNativeMethod:
ModifierCorrectionSubProcessor.addNativeMethodProposals(context, proposals);
break;
case IProblem.OuterLocalMustBeFinal:
ModifierCorrectionSubProcessor.addNonFinalLocalProposal(context, proposals);
break;
default:
}
}
}
|
27,223 |
Bug 27223 Search: NPE in goto marker action
|
!ENTRY org.eclipse.ui 4 4 Nov 27, 2002 11:44:06.250 !MESSAGE Unhandled exception caught in event loop. !ENTRY org.eclipse.ui 4 0 Nov 27, 2002 11:44:06.265 !MESSAGE Argument not valid !STACK 0 java.lang.IllegalArgumentException: Argument not valid at org.eclipse.swt.SWT.error(SWT.java:2166) at org.eclipse.swt.SWT.error(SWT.java:2110) at org.eclipse.swt.custom.StyledText.setCaretOffset(StyledText.java:6880) at org.eclipse.jface.text.TextViewer.handleVerifyEvent(TextViewer.java:2651) at org.eclipse.jface.text.TextViewer$TextVerifyListener.verifyText(TextViewer.java:317) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:187) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:825) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:850) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:834) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:641) at org.eclipse.swt.custom.StyledText.modifyContent(StyledText.java:5597) at org.eclipse.swt.custom.StyledText.sendKeyEvent(StyledText.java:6577) at org.eclipse.swt.custom.StyledText.doContent(StyledText.java:2663) at org.eclipse.swt.custom.StyledText.handleKey(StyledText.java:5023) at org.eclipse.swt.custom.StyledText.handleKeyDown(StyledText.java:5046) at org.eclipse.swt.custom.StyledText$8.handleEvent(StyledText.java:4811) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:825) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1370) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1353) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:841) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539)
|
resolved fixed
|
70c1e44
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-28T13:22:04Z | 2002-11-27T09:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/GotoMarkerAction.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.search;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.search.ui.ISearchResultView;
import org.eclipse.search.ui.ISearchResultViewEntry;
import org.eclipse.search.ui.SearchUI;
import org.eclipse.search.internal.ui.SearchPlugin;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.ui.IPackagesViewPart;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.javaeditor.InternalClassFileEditorInput;
import org.eclipse.jdt.internal.ui.util.SelectionUtil;
public class GotoMarkerAction extends Action {
private IEditorPart fEditor;
public GotoMarkerAction(){
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.GOTO_MARKER_ACTION);
}
public void run() {
ISearchResultView view= SearchUI.getSearchResultView();
Object element= SelectionUtil.getSingleElement(view.getSelection());
if (element instanceof ISearchResultViewEntry) {
ISearchResultViewEntry entry= (ISearchResultViewEntry)element;
show(entry.getSelectedMarker());
}
}
private void show(IMarker marker) {
IResource resource= marker.getResource();
if (resource == null || !resource.exists())
return;
IWorkbenchPage wbPage= JavaPlugin.getActivePage();
IJavaElement javaElement= SearchUtil.getJavaElement(marker);
if (javaElement.getElementType() == IJavaElement.PACKAGE_FRAGMENT)
gotoPackagesView(javaElement, wbPage);
else {
if (SearchUI.reuseEditor())
showWithReuse(marker, resource, javaElement, wbPage);
else
showWithoutReuse(marker, javaElement, wbPage);
}
}
private void showWithoutReuse(IMarker marker, IJavaElement javaElement, IWorkbenchPage wbPage) {
IEditorPart editor= null;
try {
Object objectToOpen= javaElement;
if (objectToOpen == null)
objectToOpen= marker.getResource();
editor= EditorUtility.openInEditor(objectToOpen, false);
} catch (CoreException ex) {
MessageDialog.openError(SearchPlugin.getActiveWorkbenchShell(), SearchMessages.getString("Search.Error.openEditor.title"), SearchMessages.getString("Search.Error.openEditor.message")); //$NON-NLS-2$ //$NON-NLS-1$
}
if (editor != null)
editor.gotoMarker(marker);
}
private void showWithReuse(IMarker marker, IResource resource, IJavaElement javaElement, IWorkbenchPage wbPage) {
if (javaElement == null || !isBinary(javaElement)) {
if (resource instanceof IFile)
showInEditor(marker, wbPage, new FileEditorInput((IFile)resource), JavaUI.ID_CU_EDITOR);
}
else {
IClassFile cf= getClassFile(javaElement);
if (cf != null)
showInEditor(marker, wbPage, new InternalClassFileEditorInput(cf), JavaUI.ID_CF_EDITOR);
}
}
private boolean isPinned(IEditorPart editor) {
if (editor == null)
return false;
IEditorReference[] editorRefs= editor.getEditorSite().getPage().getEditorReferences();
int i= 0;
while (i < editorRefs.length) {
if (editor.equals(editorRefs[i].getEditor(false)))
return editorRefs[i].isPinned();
i++;
}
return false;
}
private void showInEditor(IMarker marker, IWorkbenchPage page, IEditorInput input, String editorId) {
IEditorPart editor= page.findEditor(input);
if (editor == null) {
if (fEditor != null && !fEditor.isDirty() && !isPinned(fEditor))
page.closeEditor(fEditor, false);
try {
editor= page.openEditor(input, editorId, false);
} catch (PartInitException ex) {
MessageDialog.openError(SearchPlugin.getActiveWorkbenchShell(), SearchMessages.getString("Search.Error.openEditor.title"), SearchMessages.getString("Search.Error.openEditor.message")); //$NON-NLS-2$ //$NON-NLS-1$
return;
}
} else {
page.bringToTop(editor);
}
if (editor != null) {
editor.gotoMarker(marker);
fEditor = editor;
}
}
private void gotoPackagesView(IJavaElement javaElement, IWorkbenchPage wbPage) {
try {
IViewPart view= wbPage.showView(JavaUI.ID_PACKAGES);
if (view instanceof IPackagesViewPart)
((IPackagesViewPart)view).selectAndReveal(javaElement);
} catch (PartInitException ex) {
MessageDialog.openError(SearchPlugin.getActiveWorkbenchShell(), SearchMessages.getString("Search.Error.openEditor.title"), SearchMessages.getString("Search.Error.openEditor.message")); //$NON-NLS-2$ //$NON-NLS-1$
}
}
private IClassFile getClassFile(IJavaElement jElement) {
if (jElement instanceof IMember)
return ((IMember)jElement).getClassFile();
return null;
}
private boolean isBinary(IJavaElement jElement) {
if (jElement instanceof IMember)
return ((IMember)jElement).isBinary();
return false;
}
private void beep() {
Shell shell= JavaPlugin.getActiveWorkbenchShell();
if (shell != null && shell.getDisplay() != null)
shell.getDisplay().beep();
}
}
|
27,264 |
Bug 27264 opening/closing java files in presence of hiearchical package explorer is slow
|
will attach profiles
|
resolved fixed
|
0e4efd7
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-28T15:21:01Z | 2002-11-27T18:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/PackageExplorerContentProvider.java
|
/*
* (c) Copyright IBM Corp. 2000, 2002.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.packageview;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.swt.widgets.Control;
import org.eclipse.jface.viewers.IBasicPropertyConstants;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jdt.core.ElementChangedEvent;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IElementChangedListener;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaElementDelta;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IWorkingCopy;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.StandardJavaElementContentProvider;
import org.eclipse.jdt.internal.ui.JavaPlugin;
/**
* Content provider for the PackageExplorer.
*
* <p>
* Since 2.1 this content provider can provide the children for flat or hierarchical
* layout. The hierarchical layout is done by delegating to the <code>PackageFragmentProvider</code>.
* </p>
*
* @see org.eclipse.jdt.ui.StandardJavaElementContentProvider
* @see org.eclipse.jdt.internal.ui.packageview.PackageFragmentProvider
*/
class PackageExplorerContentProvider extends StandardJavaElementContentProvider implements ITreeContentProvider, IElementChangedListener {
protected TreeViewer fViewer;
protected Object fInput;
private boolean fIsFlatLayout;
private PackageFragmentProvider fPackageFragmentProvider= new PackageFragmentProvider();
/**
* Creates a new content provider for Java elements.
*/
public PackageExplorerContentProvider() {
}
/**
* Creates a new content provider for Java elements.
*/
public PackageExplorerContentProvider(boolean provideMembers, boolean provideWorkingCopy) {
super(provideMembers, provideWorkingCopy);
}
/* (non-Javadoc)
* Method declared on IElementChangedListener.
*/
public void elementChanged(final ElementChangedEvent event) {
try {
processDelta(event.getDelta());
} catch(JavaModelException e) {
JavaPlugin.log(e);
}
}
/* (non-Javadoc)
* Method declared on IContentProvider.
*/
public void dispose() {
super.dispose();
JavaCore.removeElementChangedListener(this);
fPackageFragmentProvider.dispose();
}
// ------ Code which delegates to PackageFragmentProvider ------
private boolean needsToDelegate(Object element) {
int type= -1;
if (element instanceof IJavaElement)
type= ((IJavaElement)element).getElementType();
return (!fIsFlatLayout && (type == IJavaElement.PACKAGE_FRAGMENT || type == IJavaElement.PACKAGE_FRAGMENT_ROOT || type == IJavaElement.JAVA_PROJECT));
}
public Object[] getChildren(Object parentElement) {
if (needsToDelegate(parentElement)) {
Object[] packageFragments= fPackageFragmentProvider.getChildren(parentElement);
return getWithParentsResources(packageFragments, parentElement);
} else
return super.getChildren(parentElement);
}
public Object getParent(Object child) {
if (needsToDelegate(child)) {
return fPackageFragmentProvider.getParent(child);
} else
return super.getParent(child);
}
/**
* Returns the given objects with the resources of the parent.
*/
private Object[] getWithParentsResources(Object[] existingObject, Object parent) {
Object[] objects= super.getChildren(parent);
List list= new ArrayList();
// Add everything that is not a PackageFragment
for (int i= 0; i < objects.length; i++) {
Object object= objects[i];
if (!(object instanceof IPackageFragment)) {
list.add(object);
}
}
if (existingObject != null)
list.addAll(Arrays.asList(existingObject));
return list.toArray();
}
/* (non-Javadoc)
* Method declared on IContentProvider.
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
super.inputChanged(viewer, oldInput, newInput);
fPackageFragmentProvider.inputChanged(viewer, oldInput, newInput);
fViewer= (TreeViewer)viewer;
if (oldInput == null && newInput != null) {
JavaCore.addElementChangedListener(this);
} else if (oldInput != null && newInput == null) {
JavaCore.removeElementChangedListener(this);
}
fInput= newInput;
}
// ------ delta processing ------
/**
* Processes a delta recursively. When more than two children are affected the
* tree is fully refreshed starting at this node. The delta is processed in the
* current thread but the viewer updates are posted to the UI thread.
*/
public void processDelta(IJavaElementDelta delta) throws JavaModelException {
int kind= delta.getKind();
int flags= delta.getFlags();
IJavaElement element= delta.getElement();
if(element.getElementType()!= IJavaElement.JAVA_MODEL && element.getElementType()!= IJavaElement.JAVA_PROJECT){
IJavaProject proj= element.getJavaProject();
if (proj == null || !proj.getProject().isOpen())
return;
}
if (!fIsFlatLayout && element.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
fPackageFragmentProvider.processDelta(delta);
IJavaElementDelta[] affectedChildren= delta.getAffectedChildren();
if(affectedChildren.length > 1)
postRefresh(element);
else
processAffectedChildren(affectedChildren);
return;
}
if (!getProvideWorkingCopy() && isWorkingCopy(element))
return;
if (element != null && element.getElementType() == IJavaElement.COMPILATION_UNIT && !isOnClassPath((ICompilationUnit)element))
return;
// handle open and closing of a solution or project
if (((flags & IJavaElementDelta.F_CLOSED) != 0) || ((flags & IJavaElementDelta.F_OPENED) != 0)) {
postRefresh(element);
return;
}
if (kind == IJavaElementDelta.REMOVED) {
// when a working copy is removed all we have to do
// is to refresh the compilation unit
if (isWorkingCopy(element)) {
refreshWorkingCopy((IWorkingCopy)element);
return;
}
Object parent= internalGetParent(element);
postRemove(element);
if (parent instanceof IPackageFragment)
postUpdateIcon((IPackageFragment)parent);
// we are filtering out empty subpackages, so we
// a package becomes empty we remove it from the viewer.
if (isPackageFragmentEmpty(element.getParent())) {
if (fViewer.testFindItem(parent) != null)
postRefresh(internalGetParent(parent));
}
return;
}
if (kind == IJavaElementDelta.ADDED) {
// when a working copy is added all we have to do
// is to refresh the compilation unit
if (isWorkingCopy(element)) {
refreshWorkingCopy((IWorkingCopy)element);
return;
}
Object parent= internalGetParent(element);
// we are filtering out empty subpackages, so we
// have to handle additions to them specially.
if (parent instanceof IPackageFragment) {
Object grandparent= internalGetParent(parent);
// 1GE8SI6: ITPJUI:WIN98 - Rename is not shown in Packages View
// avoid posting a refresh to an unvisible parent
if (parent.equals(fInput)) {
postRefresh(parent);
} else {
// refresh from grandparent if parent isn't visible yet
if (fViewer.testFindItem(parent) == null)
postRefresh(grandparent);
else {
postRefresh(parent);
}
}
return;
} else {
postAdd(parent, element);
}
}
if (element instanceof ICompilationUnit) {
if (getProvideWorkingCopy()) {
IJavaElement original= ((IWorkingCopy)element).getOriginalElement();
if (original != null)
element= original;
}
if (kind == IJavaElementDelta.CHANGED) {
postRefresh(element);
updateSelection(delta);
return;
}
}
// we don't show the contents of a compilation or IClassFile, so don't go any deeper
if ((element instanceof ICompilationUnit) || (element instanceof IClassFile))
return;
// the contents of an external JAR has changed
if (element instanceof IPackageFragmentRoot && ((flags & IJavaElementDelta.F_ARCHIVE_CONTENT_CHANGED) != 0)) {
postRefresh(element);
return;
}
// the source attachment of a JAR has changed
if (element instanceof IPackageFragmentRoot && (((flags & IJavaElementDelta.F_SOURCEATTACHED) != 0 || ((flags & IJavaElementDelta.F_SOURCEDETACHED)) != 0)))
postUpdateIcon(element);
if (isClassPathChange(delta)) {
// throw the towel and do a full refresh of the affected java project.
postRefresh(element.getJavaProject());
return;
}
if (processResourceDeltas(delta.getResourceDeltas(), element))
return;
handleAffectedChildren(delta, element);
}
private void handleAffectedChildren(IJavaElementDelta delta, IJavaElement element) throws JavaModelException {
IJavaElementDelta[] affectedChildren= delta.getAffectedChildren();
if (affectedChildren.length > 1) {
// a package fragment might become non empty refresh from the parent
if (element instanceof IPackageFragment) {
IJavaElement parent= (IJavaElement)internalGetParent(element);
// 1GE8SI6: ITPJUI:WIN98 - Rename is not shown in Packages View
// avoid posting a refresh to an unvisible parent
if (element.equals(fInput)) {
postRefresh(element);
} else {
postRefresh(parent);
}
return;
}
// more than one child changed, refresh from here downwards
if (element instanceof IPackageFragmentRoot)
postRefresh(skipProjectPackageFragmentRoot((IPackageFragmentRoot)element));
else
postRefresh(element);
return;
}
processAffectedChildren(affectedChildren);
}
protected void processAffectedChildren(IJavaElementDelta[] affectedChildren) throws JavaModelException {
for (int i= 0; i < affectedChildren.length; i++) {
processDelta(affectedChildren[i]);
}
}
private boolean isOnClassPath(ICompilationUnit element) throws JavaModelException {
IJavaProject project= element.getJavaProject();
if (project == null || !project.exists())
return false;
return project.isOnClasspath(element);
}
/**
* Updates the selection. It finds newly added elements
* and selects them.
*/
private void updateSelection(IJavaElementDelta delta) {
final IJavaElement addedElement= findAddedElement(delta);
if (addedElement != null) {
final StructuredSelection selection= new StructuredSelection(addedElement);
postRunnable(new Runnable() {
public void run() {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
// 19431
// if the item is already visible then select it
if (fViewer.testFindItem(addedElement) != null)
fViewer.setSelection(selection);
}
}
});
}
}
private IJavaElement findAddedElement(IJavaElementDelta delta) {
if (delta.getKind() == IJavaElementDelta.ADDED)
return delta.getElement();
IJavaElementDelta[] affectedChildren= delta.getAffectedChildren();
for (int i= 0; i < affectedChildren.length; i++)
return findAddedElement(affectedChildren[i]);
return null;
}
/**
* Refreshes the Compilation unit corresponding to the workging copy
* @param iWorkingCopy
*/
private void refreshWorkingCopy(IWorkingCopy workingCopy) {
IJavaElement original= workingCopy.getOriginalElement();
if (original != null)
postRefresh(original);
}
private boolean isWorkingCopy(IJavaElement element) {
return (element instanceof IWorkingCopy) && ((IWorkingCopy)element).isWorkingCopy();
}
/**
* Updates the package icon
*/
private void postUpdateIcon(final IJavaElement element) {
postRunnable(new Runnable() {
public void run() {
// 1GF87WR: ITPUI:ALL - SWTEx + NPE closing a workbench window.
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed())
fViewer.update(element, new String[]{IBasicPropertyConstants.P_IMAGE});
}
});
}
/**
1 * Process a resource delta.
*
* @return true if the parent got refreshed
*/
private boolean processResourceDelta(IResourceDelta delta, Object parent) {
int status= delta.getKind();
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);
}
processResourceDeltas(delta.getAffectedChildren(), resource);
return false;
}
/**
* 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(final Object root) {
postRunnable(new Runnable() {
public void run() {
// 1GF87WR: ITPUI:ALL - SWTEx + NPE closing a workbench window.
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()){
fViewer.refresh(root);
}
}
});
}
private void postAdd(final Object parent, final Object element) {
postRunnable(new Runnable() {
public void run() {
// 1GF87WR: ITPUI:ALL - SWTEx + NPE closing a workbench window.
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()){
fViewer.add(parent, element);
}
}
});
}
private void postRemove(final Object element) {
postRunnable(new Runnable() {
public void run() {
// 1GF87WR: ITPUI:ALL - SWTEx + NPE closing a workbench window.
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
fViewer.remove(element);
}
}
});
}
private void postRunnable(final Runnable r) {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
ctrl.getDisplay().asyncExec(r);
}
}
void setIsFlatLayout(boolean state) {
fIsFlatLayout= state;
}
}
|
27,264 |
Bug 27264 opening/closing java files in presence of hiearchical package explorer is slow
|
will attach profiles
|
resolved fixed
|
0e4efd7
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-11-28T15:21:01Z | 2002-11-27T18:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/PackageFragmentProvider.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.internal.ui.packageview;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jdt.core.ElementChangedEvent;
import org.eclipse.jdt.core.IElementChangedListener;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaElementDelta;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
import org.eclipse.jdt.internal.ui.JavaPlugin;
/**
* Content provider which provides package fragments for hierarchical
* Package Explorer layout.
*
* @since 2.1
*/
public class PackageFragmentProvider implements IPropertyChangeListener, ITreeContentProvider, IElementChangedListener{
private TreeViewer fViewer;
private boolean fFoldPackages;
public PackageFragmentProvider() {
fFoldPackages= arePackagesFoldedInHierarchicalLayout();
JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this);
}
/*
* @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(Object)
*/
public Object[] getChildren(Object parentElement) {
try {
if (parentElement instanceof IJavaElement) {
IJavaElement iJavaElement= (IJavaElement) parentElement;
int type= iJavaElement.getElementType();
switch (type) {
case IJavaElement.JAVA_PROJECT: {
IJavaProject project= (IJavaProject)iJavaElement;
IProject proj= project.getProject();
List children= new ArrayList();
IPackageFragmentRoot defaultroot= project.getPackageFragmentRoot(proj);
if(defaultroot.exists()){
IJavaElement[] els= defaultroot.getChildren();
children= getTopLevelChildrenByElementName(els);
}
return filter(children.toArray());
}
case IJavaElement.PACKAGE_FRAGMENT_ROOT :
{
IPackageFragmentRoot root = (IPackageFragmentRoot) parentElement;
if (root.exists()) {
IResource resource = root.getUnderlyingResource();
if (root.isArchive()) {
IJavaElement[] els = root.getChildren();
return filter(getTopLevelChildrenByElementName(els).toArray());
} else if (resource instanceof IFolder) {
IFolder folder = (IFolder) resource;
IResource[] reses = folder.members();
List children = getFolders(reses);
IPackageFragment defaultPackage= root.getPackageFragment(""); //$NON-NLS-1$
if(defaultPackage.exists())
children.add(defaultPackage);
return filter(children.toArray());
}
}
break;
}
case IJavaElement.PACKAGE_FRAGMENT :
{
IPackageFragment packageFragment = (IPackageFragment) parentElement;
if (!packageFragment.isDefaultPackage()) {
IResource resource = packageFragment.getUnderlyingResource();
if (resource != null && resource instanceof IFolder) {
IFolder folder = (IFolder) resource;
IResource[] reses = folder.members();
Object[] children = getFolders(reses).toArray();
return filter(children);
//if the resource is null, maybe member of an archive
} else {
IJavaElement parent = packageFragment.getParent();
if (parent instanceof IPackageFragmentRoot) {
IPackageFragmentRoot root = (IPackageFragmentRoot) parent;
Object[] children = findNextLevelChildrenByElementName(root, packageFragment);
return filter(children);
}
}
}
break;
}
default :
// do nothing
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
} catch (CoreException e) {
JavaPlugin.log(e);
}
return new Object[0];
}
private Object[] filter(Object[] children) {
if (fFoldPackages) {
for (int i = 0; i < children.length; i++) {
if (children[i] instanceof IPackageFragment) {
IPackageFragment fragment = (IPackageFragment) children[i];
if(!fragment.isDefaultPackage())
children[i] = getBottomPackage(fragment);
}
}
}
return children;
}
private Object getBottomPackage(IPackageFragment iPackageFragment) {
try {
if(isEmpty(iPackageFragment))
return findChildrenToBeCompounded(iPackageFragment);
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
return iPackageFragment;
}
private IPackageFragment findChildrenToBeCompounded(IPackageFragment fragment) throws JavaModelException {
Object[] children = getChildren(fragment);
if ((children.length == 1) && (children[0] instanceof IPackageFragment)) {
if (isEmpty((IPackageFragment) children[0]))
return findChildrenToBeCompounded((IPackageFragment) children[0]);
else return (IPackageFragment)children[0];
}
return fragment;
}
private boolean isEmpty(IPackageFragment fragment) throws JavaModelException {
return (!fragment.containsJavaResources()) && (fragment.getNonJavaResources().length==0);
}
private Object[] findNextLevelChildrenByElementName(IPackageFragmentRoot parent, IPackageFragment fragment) {
List list= new ArrayList();
try {
IJavaElement[] children= parent.getChildren();
String fragmentname= fragment.getElementName();
for (int i= 0; i < children.length; i++) {
IJavaElement element= children[i];
if (element instanceof IPackageFragment) {
IPackageFragment frag= (IPackageFragment) element;
String name= element.getElementName();
if (!"".equals(fragmentname) && name.startsWith(fragmentname) && !name.equals(fragmentname)) { //$NON-NLS-1$
String tail= name.substring(fragmentname.length() + 1);
if (!"".equals(tail) && (tail.indexOf(".") == -1)) {//$NON-NLS-1$ //$NON-NLS-2$
list.add(frag);
}
}
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
return list.toArray();
}
private List getTopLevelChildrenByElementName(IJavaElement[] elements){
List topLevelElements= new ArrayList();
for (int i= 0; i < elements.length; i++) {
IJavaElement iJavaElement= elements[i];
//if the name of the PackageFragment is the top level package it will contain no "." separators
if((iJavaElement.getElementName().indexOf(".")==-1) && (iJavaElement instanceof IPackageFragment)){ //$NON-NLS-1$
topLevelElements.add(iJavaElement);
}
}
return topLevelElements;
}
private List getFolders(IResource[] resources) throws JavaModelException {
List list= new ArrayList();
for (int i= 0; i < resources.length; i++) {
IResource resource= resources[i];
if (resource instanceof IFolder) {
IFolder folder= (IFolder) resource;
IJavaElement element= JavaCore.create(folder);
if (element instanceof IPackageFragment) {
list.add(element);
}
}
}
return list;
}
/*
* @see org.eclipse.jface.viewers.ITreeContentProvider#getParent(Object)
*/
public Object getParent(Object element) {
if (element instanceof IPackageFragment) {
IPackageFragment frag = (IPackageFragment) element;
//@Changed: a fix, before: if(frag.exists() && isEmpty(frag))
return filterParent(getActualParent(frag));
}
return null;
}
public Object getActualParent(IPackageFragment fragment) {
try {
if (fragment.exists()) {
IJavaElement parent = fragment.getParent();
if ((parent instanceof IPackageFragmentRoot) && parent.exists()) {
IPackageFragmentRoot root = (IPackageFragmentRoot) parent;
if (root.isArchive()) {
return findNextLevelChildrenByElementName(fragment, root);
} else {
IResource resource = fragment.getUnderlyingResource();
if ((resource != null) && (resource instanceof IFolder)) {
IFolder folder = (IFolder) resource;
IResource res = folder.getParent();
IJavaElement el = JavaCore.create(res);
return el;
}
}
return parent;
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
return null;
}
private Object filterParent(Object parent) {
if (fFoldPackages && (parent!=null)) {
try {
if (parent instanceof IPackageFragment) {
IPackageFragment fragment = (IPackageFragment) parent;
if (isEmpty(fragment) && hasSingleChild(fragment)) {
return filterParent(getActualParent(fragment));
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
return parent;
}
private boolean hasSingleChild(IPackageFragment fragment) {
return getChildren(fragment).length==1;
}
private Object findNextLevelChildrenByElementName(IJavaElement child, IJavaElement parent) {
String name= child.getElementName();
if(name.indexOf(".")==-1) //$NON-NLS-1$
return parent;
try {
String realParentName= child.getElementName().substring(0,name.lastIndexOf(".")); //$NON-NLS-1$
IJavaElement[] children= new IJavaElement[0];
if(parent instanceof IPackageFragmentRoot){
IPackageFragmentRoot root = (IPackageFragmentRoot) parent;
children= root.getChildren();
} else if (parent instanceof IJavaProject) {
IJavaProject project = (IJavaProject) parent;
children= project.getPackageFragments();
}
for (int i= 0; i < children.length; i++) {
IJavaElement element= children[i];
if(element.getElementName().equals(realParentName))
return element;
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
return parent;
}
/*
* @see org.eclipse.jface.viewers.ITreeContentProvider#hasChildren(Object)
*/
public boolean hasChildren(Object element) {
if (element instanceof IPackageFragment) {
IPackageFragment fragment= (IPackageFragment) element;
if(fragment.isDefaultPackage())
return false;
}
return getChildren(element).length > 0;
}
/*
* @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(Object)
*/
public Object[] getElements(Object inputElement) {
return getChildren(inputElement);
}
/*
* @see org.eclipse.jface.viewers.IContentProvider#dispose()
*/
public void dispose() {
JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this);
}
/**
* Called when the view is closed and opened.
*
* @see org.eclipse.jface.viewers.IContentProvider#inputChanged(Viewer, Object, Object)
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
fViewer= (TreeViewer)viewer;
}
/*
* @see org.eclipse.jdt.core.IElementChangedListener#elementChanged(org.eclipse.jdt.core.ElementChangedEvent)
*/
public void elementChanged(ElementChangedEvent event) {
processDelta(event.getDelta());
}
public void processDelta(IJavaElementDelta delta) {
int kind = delta.getKind();
final IJavaElement element = delta.getElement();
if (element instanceof IPackageFragment) {
if (kind == IJavaElementDelta.REMOVED) {
postRunnable(new Runnable() {
public void run() {
Control ctrl = fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
if (!fFoldPackages)
((TreeViewer) fViewer).remove(element);
else
refreshGrandParent(element);
}
}
});
return;
} else if (kind == IJavaElementDelta.ADDED) {
final Object parent = getParent(element);
if (parent != null) {
postRunnable(new Runnable() {
public void run() {
Control ctrl = fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
if (!fFoldPackages)
((TreeViewer) fViewer).add(parent, element);
else
refreshGrandParent(element);
}
}
});
}
return;
} else if (kind == IJavaElementDelta.CHANGED) {
postRunnable(new Runnable() {
public void run() {
Control ctrl = fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
if (!fFoldPackages)
fViewer.refresh(element);
else refreshGrandParent(element);
}
}
});
return;
}
}
IJavaElementDelta[] affectedChildren = delta.getAffectedChildren();
processAffectedChildren(affectedChildren);
}
// XXX: needs to be revisited - might be a performance issue
private void refreshGrandParent(final IJavaElement element) {
if (element instanceof IPackageFragment) {
Object gp= getGrandParent((IPackageFragment)element);
if (gp instanceof IJavaElement) {
IJavaElement el = (IJavaElement) gp;
if(el.exists())
fViewer.refresh(gp);
}
}
}
private Object getGrandParent(IPackageFragment element) {
Object parent= findNextLevelChildrenByElementName(element, element.getParent());
if (parent instanceof IPackageFragmentRoot) {
IPackageFragmentRoot root= (IPackageFragmentRoot) parent;
if(isRootProject(root))
return root.getJavaProject();
else return root;
}
Object grandParent= getParent(parent);
if(grandParent==null){
return parent;
}
return grandParent;
}
private boolean isRootProject(IPackageFragmentRoot root) {
if (IPackageFragmentRoot.DEFAULT_PACKAGEROOT_PATH.equals(root.getElementName()))
return true;
return false;
}
protected void processAffectedChildren(IJavaElementDelta[] affectedChildren) {
for (int i= 0; i < affectedChildren.length; i++) {
if (!(affectedChildren[i] instanceof ICompilationUnit)) {
processDelta(affectedChildren[i]);
}
}
}
private void postRunnable(final Runnable r) {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
Display currentDisplay= Display.getCurrent();
if (currentDisplay != null && currentDisplay.equals(ctrl.getDisplay()))
ctrl.getDisplay().syncExec(r);
else
ctrl.getDisplay().asyncExec(r);
}
}
/*
* @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if(arePackagesFoldedInHierarchicalLayout() != fFoldPackages){
fFoldPackages= arePackagesFoldedInHierarchicalLayout();
fViewer.getControl().setRedraw(false);
Object[] expandedObjects= fViewer.getExpandedElements();
fViewer.refresh();
fViewer.setExpandedElements(expandedObjects);
fViewer.getControl().setRedraw(true);
}
}
private boolean arePackagesFoldedInHierarchicalLayout(){
return PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.APPEARANCE_FOLD_PACKAGES_IN_PACKAGE_EXPLORER);
}
}
|
27,483 |
Bug 27483 Early plugin activation of J9 launcher
|
1) empty workspace 2) switch to Java perspectiv ->the J9 launcher plugin is activated
|
resolved fixed
|
c2388a0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-02T13:43:50Z | 2002-12-02T11:53:20Z |
org.eclipse.jdt.ui/core
| |
27,483 |
Bug 27483 Early plugin activation of J9 launcher
|
1) empty workspace 2) switch to Java perspectiv ->the J9 launcher plugin is activated
|
resolved fixed
|
c2388a0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-02T13:43:50Z | 2002-12-02T11:53:20Z |
extension/org/eclipse/jdt/internal/corext/javadoc/JavaDocLocations.java
| |
27,483 |
Bug 27483 Early plugin activation of J9 launcher
|
1) empty workspace 2) switch to Java perspectiv ->the J9 launcher plugin is activated
|
resolved fixed
|
c2388a0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-02T13:43:50Z | 2002-12-02T11:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/JavaPlugin.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdapterManager;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IPluginDescriptor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.corext.javadoc.JavaDocLocations;
import org.eclipse.jdt.internal.corext.javadoc.JavaDocVMInstallListener;
import org.eclipse.jdt.internal.ui.javaeditor.ClassFileDocumentProvider;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitDocumentProvider;
import org.eclipse.jdt.internal.ui.viewsupport.ImageDescriptorRegistry;
import org.eclipse.jdt.internal.ui.viewsupport.ProblemMarkerManager;
/**
* Represents the java plugin. It provides a series of convenience methods such as
* access to the workbench, keeps track of elements shared by all editors and viewers
* of the plugin such as document providers and find-replace-dialogs.
*/
public class JavaPlugin extends AbstractUIPlugin {
// TODO: Evaluate if we should move these ID's to JavaUI
/**
* 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$
private static JavaPlugin fgJavaPlugin;
private CompilationUnitDocumentProvider fCompilationUnitDocumentProvider;
private ClassFileDocumentProvider fClassFileDocumentProvider;
private JavaTextTools fJavaTextTools;
private ProblemMarkerManager fProblemMarkerManager;
private ImageDescriptorRegistry fImageDescriptorRegistry;
private JavaDocVMInstallListener fVMInstallListener;
private JavaElementAdapterFactory fJavaElementAdapterFactory;
private MarkerAdapterFactory fMarkerAdapterFactory;
private EditorInputAdapterFactory fEditorInputAdapterFactory;
private ResourceAdapterFactory fResourceAdapterFactory;
public static JavaPlugin getDefault() {
return fgJavaPlugin;
}
public static IWorkspace getWorkspace() {
return ResourcesPlugin.getWorkspace();
}
public static IWorkbenchPage getActivePage() {
return getDefault().internalGetActivePage();
}
public static IWorkbenchWindow getActiveWorkbenchWindow() {
return getDefault().getWorkbench().getActiveWorkbenchWindow();
}
public static Shell getActiveWorkbenchShell() {
return getActiveWorkbenchWindow().getShell();
}
/**
* Returns an array of all editors that have an unsaved content. If the identical content is
* presented in more than one editor, only one of those editor parts is part of the result.
*
* @return an array of all dirty editor parts.
*/
public static IEditorPart[] getDirtyEditors() {
Set inputs= new HashSet();
List result= new ArrayList(0);
IWorkbench workbench= getDefault().getWorkbench();
IWorkbenchWindow[] windows= workbench.getWorkbenchWindows();
for (int i= 0; i < windows.length; i++) {
IWorkbenchPage[] pages= windows[i].getPages();
for (int x= 0; x < pages.length; x++) {
IEditorPart[] editors= pages[x].getDirtyEditors();
for (int z= 0; z < editors.length; z++) {
IEditorPart ep= editors[z];
IEditorInput input= ep.getEditorInput();
if (!inputs.contains(input)) {
inputs.add(input);
result.add(ep);
}
}
}
}
return (IEditorPart[])result.toArray(new IEditorPart[result.size()]);
}
public static String getPluginId() {
return getDefault().getDescriptor().getUniqueIdentifier();
}
public static void log(IStatus status) {
getDefault().getLog().log(status);
}
public static void logErrorMessage(String message) {
log(new Status(IStatus.ERROR, getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, null));
}
public static void logErrorStatus(String message, IStatus status) {
if (status == null) {
logErrorMessage(message);
return;
}
MultiStatus multi= new MultiStatus(getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, null);
multi.add(status);
log(multi);
}
public static void log(Throwable e) {
log(new Status(IStatus.ERROR, getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, JavaUIMessages.getString("JavaPlugin.internal_error"), e)); //$NON-NLS-1$
}
public static boolean isDebug() {
return getDefault().isDebugging();
}
/* package */ static IPath getInstallLocation() {
return new Path(getDefault().getDescriptor().getInstallURL().getFile());
}
public static ImageDescriptorRegistry getImageDescriptorRegistry() {
return getDefault().internalGetImageDescriptorRegistry();
}
public JavaPlugin(IPluginDescriptor descriptor) {
super(descriptor);
fgJavaPlugin= this;
}
/* (non - Javadoc)
* Method declared in Plugin
*/
public void startup() throws CoreException {
super.startup();
registerAdapters();
try {
JavaDocLocations.loadJavadocLocations();
fVMInstallListener= new JavaDocVMInstallListener();
fVMInstallListener.init();
} catch (CoreException e) {
log(e);
}
}
/* (non - Javadoc)
* Method declared in AbstractUIPlugin
*/
protected ImageRegistry createImageRegistry() {
return JavaPluginImages.getImageRegistry();
}
/* (non - Javadoc)
* Method declared in Plugin
*/
public void shutdown() throws CoreException {
if (fImageDescriptorRegistry != null)
fImageDescriptorRegistry.dispose();
unregisterAdapters();
super.shutdown();
if (fCompilationUnitDocumentProvider != null) {
fCompilationUnitDocumentProvider.shutdown();
fCompilationUnitDocumentProvider= null;
}
if (fJavaTextTools != null) {
fJavaTextTools.dispose();
fJavaTextTools= null;
}
JavaDocLocations.saveJavadocLocations();
if (fVMInstallListener != null) {
fVMInstallListener.remove();
fVMInstallListener= null;
}
}
private IWorkbenchPage internalGetActivePage() {
IWorkbenchWindow window= getWorkbench().getActiveWorkbenchWindow();
if (window == null)
return null;
return getWorkbench().getActiveWorkbenchWindow().getActivePage();
}
public CompilationUnitDocumentProvider getCompilationUnitDocumentProvider() {
if (fCompilationUnitDocumentProvider == null)
fCompilationUnitDocumentProvider= new CompilationUnitDocumentProvider();
return fCompilationUnitDocumentProvider;
}
public ClassFileDocumentProvider getClassFileDocumentProvider() {
if (fClassFileDocumentProvider == null)
fClassFileDocumentProvider= new ClassFileDocumentProvider();
return fClassFileDocumentProvider;
}
public IWorkingCopyManager getWorkingCopyManager() {
return getCompilationUnitDocumentProvider();
}
public ProblemMarkerManager getProblemMarkerManager() {
if (fProblemMarkerManager == null)
fProblemMarkerManager= new ProblemMarkerManager();
return fProblemMarkerManager;
}
public JavaTextTools getJavaTextTools() {
if (fJavaTextTools == null)
fJavaTextTools= new JavaTextTools(getPreferenceStore());
return fJavaTextTools;
}
/**
* Creates the Java plugin standard groups in a context menu.
*/
public static void createStandardGroups(IMenuManager menu) {
if (!menu.isEmpty())
return;
menu.add(new Separator(IContextMenuConstants.GROUP_NEW));
menu.add(new GroupMarker(IContextMenuConstants.GROUP_GOTO));
menu.add(new Separator(IContextMenuConstants.GROUP_OPEN));
menu.add(new GroupMarker(IContextMenuConstants.GROUP_SHOW));
menu.add(new Separator(IContextMenuConstants.GROUP_REORGANIZE));
menu.add(new Separator(IContextMenuConstants.GROUP_GENERATE));
menu.add(new Separator(IContextMenuConstants.GROUP_SEARCH));
menu.add(new Separator(IContextMenuConstants.GROUP_BUILD));
menu.add(new Separator(IContextMenuConstants.GROUP_ADDITIONS));
menu.add(new Separator(IContextMenuConstants.GROUP_VIEWER_SETUP));
menu.add(new Separator(IContextMenuConstants.GROUP_PROPERTIES));
}
/**
* @see AbstractUIPlugin#initializeDefaultPreferences
*/
protected void initializeDefaultPreferences(IPreferenceStore store) {
super.initializeDefaultPreferences(store);
PreferenceConstants.initializeDefaultValues(store);
}
private ImageDescriptorRegistry internalGetImageDescriptorRegistry() {
if (fImageDescriptorRegistry == null)
fImageDescriptorRegistry= new ImageDescriptorRegistry();
return fImageDescriptorRegistry;
}
private void registerAdapters() {
fJavaElementAdapterFactory= new JavaElementAdapterFactory();
fMarkerAdapterFactory= new MarkerAdapterFactory();
fEditorInputAdapterFactory= new EditorInputAdapterFactory();
fResourceAdapterFactory= new ResourceAdapterFactory();
IAdapterManager manager= Platform.getAdapterManager();
manager.registerAdapters(fJavaElementAdapterFactory, IJavaElement.class);
manager.registerAdapters(fMarkerAdapterFactory, IMarker.class);
manager.registerAdapters(fEditorInputAdapterFactory, IEditorInput.class);
manager.registerAdapters(fResourceAdapterFactory, IResource.class);
}
private void unregisterAdapters() {
IAdapterManager manager= Platform.getAdapterManager();
manager.unregisterAdapters(fJavaElementAdapterFactory);
manager.unregisterAdapters(fMarkerAdapterFactory);
manager.unregisterAdapters(fEditorInputAdapterFactory);
manager.unregisterAdapters(fResourceAdapterFactory);
}
}
|
26,223 |
Bug 26223 [Action sets] Resouce Navigation should be enabled on JavaPerspectives by default.
|
Build id: 200211130841 Resouce Navigation action set should be enabled on java perspectives by default.
|
resolved fixed
|
efe02b5
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-03T10:36:28Z | 2002-11-13T20:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/JavaPerspectiveFactory.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui;
import org.eclipse.ui.IFolderLayout;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPerspectiveFactory;
import org.eclipse.search.ui.SearchUI;
import org.eclipse.debug.ui.IDebugUIConstants;
import org.eclipse.jdt.ui.JavaUI;
public class JavaPerspectiveFactory implements IPerspectiveFactory {
/**
* Constructs a new Default layout engine.
*/
public JavaPerspectiveFactory() {
super();
}
public void createInitialLayout(IPageLayout layout) {
String editorArea = layout.getEditorArea();
IFolderLayout folder= layout.createFolder("left", IPageLayout.LEFT, (float)0.25, editorArea); //$NON-NLS-1$
folder.addView(JavaUI.ID_PACKAGES);
folder.addView(JavaUI.ID_TYPE_HIERARCHY);
folder.addPlaceholder(IPageLayout.ID_RES_NAV);
IFolderLayout outputfolder= layout.createFolder("bottom", IPageLayout.BOTTOM, (float)0.75, editorArea); //$NON-NLS-1$
outputfolder.addView(IPageLayout.ID_TASK_LIST);
outputfolder.addPlaceholder(SearchUI.SEARCH_RESULT_VIEW_ID);
outputfolder.addPlaceholder(IDebugUIConstants.ID_CONSOLE_VIEW);
outputfolder.addPlaceholder(IPageLayout.ID_BOOKMARKS);
layout.addView(IPageLayout.ID_OUTLINE, IPageLayout.RIGHT, (float)0.75, editorArea);
layout.addActionSet(IDebugUIConstants.LAUNCH_ACTION_SET);
layout.addActionSet(JavaUI.ID_ACTION_SET);
layout.addActionSet(JavaUI.ID_ELEMENT_CREATION_ACTION_SET);
// views - java
layout.addShowViewShortcut(JavaUI.ID_PACKAGES);
layout.addShowViewShortcut(JavaUI.ID_TYPE_HIERARCHY);
layout.addShowViewShortcut(SearchUI.SEARCH_RESULT_VIEW_ID);
// views - debugging
layout.addShowViewShortcut(IDebugUIConstants.ID_CONSOLE_VIEW);
// views - standard workbench
layout.addShowViewShortcut(IPageLayout.ID_OUTLINE);
layout.addShowViewShortcut(IPageLayout.ID_TASK_LIST);
layout.addShowViewShortcut(IPageLayout.ID_RES_NAV);
// new actions - Java project creation wizard
layout.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewPackageCreationWizard"); //$NON-NLS-1$
layout.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewClassCreationWizard"); //$NON-NLS-1$
layout.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewInterfaceCreationWizard"); //$NON-NLS-1$
layout.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewSourceFolderCreationWizard"); //$NON-NLS-1$
layout.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewSnippetFileCreationWizard"); //$NON-NLS-1$
layout.addNewWizardShortcut("org.eclipse.ui.wizards.new.folder");//$NON-NLS-1$
layout.addNewWizardShortcut("org.eclipse.ui.wizards.new.file");//$NON-NLS-1$
}
}
|
26,223 |
Bug 26223 [Action sets] Resouce Navigation should be enabled on JavaPerspectives by default.
|
Build id: 200211130841 Resouce Navigation action set should be enabled on java perspectives by default.
|
resolved fixed
|
efe02b5
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-03T10:36:28Z | 2002-11-13T20:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/GotoResourceAction.java
| |
26,223 |
Bug 26223 [Action sets] Resouce Navigation should be enabled on JavaPerspectives by default.
|
Build id: 200211130841 Resouce Navigation action set should be enabled on java perspectives by default.
|
resolved fixed
|
efe02b5
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-03T10:36:28Z | 2002-11-13T20:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/PackageExplorerActionGroup.java
|
/*******************************************************************************
* Copyright (c) 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.internal.ui.packageview;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IResource;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.OpenStrategy;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.OpenEvent;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.IWorkingSet;
import org.eclipse.ui.IWorkingSetManager;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.actions.MoveResourceAction;
import org.eclipse.ui.actions.OpenInNewWindowAction;
import org.eclipse.ui.actions.RenameResourceAction;
import org.eclipse.ui.views.framelist.BackAction;
import org.eclipse.ui.views.framelist.ForwardAction;
import org.eclipse.ui.views.framelist.FrameList;
import org.eclipse.ui.views.framelist.GoIntoAction;
import org.eclipse.ui.views.framelist.UpAction;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IOpenable;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.actions.BuildActionGroup;
import org.eclipse.jdt.ui.actions.CCPActionGroup;
import org.eclipse.jdt.ui.actions.CustomFiltersActionGroup;
import org.eclipse.jdt.ui.actions.GenerateActionGroup;
import org.eclipse.jdt.ui.actions.ImportActionGroup;
import org.eclipse.jdt.ui.actions.JavaSearchActionGroup;
import org.eclipse.jdt.ui.actions.JdtActionConstants;
import org.eclipse.jdt.ui.actions.MemberFilterActionGroup;
import org.eclipse.jdt.ui.actions.NavigateActionGroup;
import org.eclipse.jdt.ui.actions.ProjectActionGroup;
import org.eclipse.jdt.ui.actions.RefactorActionGroup;
import org.eclipse.jdt.ui.actions.ShowActionGroup;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.actions.NewWizardsActionGroup;
import org.eclipse.jdt.internal.ui.workingsets.WorkingSetFilterActionGroup;
class PackageExplorerActionGroup extends CompositeActionGroup implements ISelectionChangedListener {
private PackageExplorerPart fPart;
private GoIntoAction fZoomInAction;
private BackAction fBackAction;
private ForwardAction fForwardAction;
private UpAction fUpAction;
private GotoTypeAction fGotoTypeAction;
private GotoPackageAction fGotoPackageAction;
private CollapseAllAction fCollapseAllAction;
private RenameResourceAction fRenameResourceAction;
private MoveResourceAction fMoveResourceAction;
private NavigateActionGroup fNavigateActionGroup;
private BuildActionGroup fBuildActionGroup;
private CCPActionGroup fCCPActionGroup;
private WorkingSetFilterActionGroup fWorkingSetFilterActionGroup;
private MemberFilterActionGroup fMemberFilterActionGroup;
private CustomFiltersActionGroup fCustomFiltersActionGroup;
public PackageExplorerActionGroup(PackageExplorerPart part) {
super();
fPart= part;
IWorkbenchPartSite site = fPart.getSite();
Shell shell= site.getShell();
ISelectionProvider provider= site.getSelectionProvider();
IStructuredSelection selection= (IStructuredSelection) provider.getSelection();
setGroups(new ActionGroup[] {
new NewWizardsActionGroup(site),
fNavigateActionGroup= new NavigateActionGroup(fPart),
new ShowActionGroup(fPart),
fCCPActionGroup= new CCPActionGroup(fPart),
new RefactorActionGroup(fPart),
new ImportActionGroup(fPart),
new GenerateActionGroup(fPart),
fBuildActionGroup= new BuildActionGroup(fPart),
new JavaSearchActionGroup(fPart),
new ProjectActionGroup(fPart),
fWorkingSetFilterActionGroup= new WorkingSetFilterActionGroup(part.getViewer(), JavaUI.ID_PACKAGES, shell, createTitleUpdater()),
new LayoutActionGroup(part)});
PackagesFrameSource frameSource= new PackagesFrameSource(fPart);
FrameList frameList= new FrameList(frameSource);
frameSource.connectTo(frameList);
fZoomInAction= new GoIntoAction(frameList);
fBackAction= new BackAction(frameList);
fForwardAction= new ForwardAction(frameList);
fUpAction= new UpAction(frameList);
fRenameResourceAction= new RenameResourceAction(shell);
fMoveResourceAction= new MoveResourceAction(shell);
fGotoTypeAction= new GotoTypeAction(fPart);
fGotoPackageAction= new GotoPackageAction(fPart);
fCollapseAllAction= new CollapseAllAction(fPart);
fMemberFilterActionGroup= new MemberFilterActionGroup(fPart.getViewer(), "PackageView"); //$NON-NLS-1$
fCustomFiltersActionGroup= new CustomFiltersActionGroup(fPart, fPart.getViewer());
provider.addSelectionChangedListener(this);
update(selection);
}
public void dispose() {
if (fMemberFilterActionGroup != null) {
fMemberFilterActionGroup.dispose();
fMemberFilterActionGroup= null;
}
if (fCustomFiltersActionGroup != null) {
fCustomFiltersActionGroup.dispose();
fCustomFiltersActionGroup= null;
}
ISelectionProvider provider= fPart.getSite().getSelectionProvider();
provider.removeSelectionChangedListener(this);
super.dispose();
}
//---- Selection changed listener ---------------------------------------------------------
public void selectionChanged(SelectionChangedEvent event) {
fRenameResourceAction.selectionChanged(event);
fMoveResourceAction.selectionChanged(event);
IStructuredSelection selection= (IStructuredSelection)event.getSelection();
update(selection);
}
private void update(IStructuredSelection selection) {
int size= selection.size();
Object element= selection.getFirstElement();
IActionBars actionBars= fPart.getViewSite().getActionBars();
if (size == 1 && element instanceof IResource) {
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.RENAME, fRenameResourceAction);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.MOVE, fMoveResourceAction);
} else {
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.RENAME, null);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.MOVE, null);
}
actionBars.updateActionBars();
}
//---- Persistent state -----------------------------------------------------------------------
/* package */ void restoreState(IMemento memento) {
fMemberFilterActionGroup.restoreState(memento);
fWorkingSetFilterActionGroup.restoreState(memento);
fCustomFiltersActionGroup.restoreState(memento);
fPart.getViewer().getControl().setRedraw(false);
fPart.getViewer().refresh();
fPart.getViewer().getControl().setRedraw(true);
}
/* package */ void saveState(IMemento memento) {
fMemberFilterActionGroup.saveState(memento);
fWorkingSetFilterActionGroup.saveState(memento);
fCustomFiltersActionGroup.saveState(memento);
}
//---- Action Bars ----------------------------------------------------------------------------
public void fillActionBars(IActionBars actionBars) {
super.fillActionBars(actionBars);
setGlobalActionHandlers(actionBars);
fillToolBar(actionBars.getToolBarManager());
fillViewMenu(actionBars.getMenuManager());
fCustomFiltersActionGroup.fillActionBars(actionBars);
}
private void setGlobalActionHandlers(IActionBars actionBars) {
// Navigate Go Into and Go To actions.
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.GO_INTO, fZoomInAction);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.BACK, fBackAction);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.FORWARD, fForwardAction);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.UP, fUpAction);
actionBars.setGlobalActionHandler(JdtActionConstants.GOTO_TYPE, fGotoTypeAction);
actionBars.setGlobalActionHandler(JdtActionConstants.GOTO_PACKAGE, fGotoPackageAction);
}
/* package */ void fillToolBar(IToolBarManager toolBar) {
toolBar.removeAll();
toolBar.add(fBackAction);
toolBar.add(fForwardAction);
toolBar.add(fUpAction);
if (showCompilationUnitChildren()) {
toolBar.add(new Separator());
fMemberFilterActionGroup.contributeToToolBar(toolBar);
}
toolBar.add(new Separator());
toolBar.add(fCollapseAllAction);
}
/* package */ void fillViewMenu(IMenuManager menu) {
menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS+"-end"));//$NON-NLS-1$
}
/* package */ void handleSelectionChanged(SelectionChangedEvent event) {
fZoomInAction.update();
}
//---- Context menu -------------------------------------------------------------------------
public void fillContextMenu(IMenuManager menu) {
IStructuredSelection selection= (IStructuredSelection)getContext().getSelection();
int size= selection.size();
Object element= selection.getFirstElement();
addGotoMenu(menu, element, size);
addOpenNewWindowAction(menu, element);
super.fillContextMenu(menu);
}
private void addGotoMenu(IMenuManager menu, Object element, int size) {
if (size == 1 && fPart.getViewer().isExpandable(element) && (isGoIntoTarget(element) || element instanceof IContainer))
menu.appendToGroup(IContextMenuConstants.GROUP_GOTO, fZoomInAction);
}
private boolean isNewTarget(IJavaElement element) {
if (element == null)
return false;
int type= element.getElementType();
return type == IJavaElement.JAVA_PROJECT ||
type == IJavaElement.PACKAGE_FRAGMENT_ROOT ||
type == IJavaElement.PACKAGE_FRAGMENT ||
type == IJavaElement.COMPILATION_UNIT ||
type == IJavaElement.TYPE;
}
private boolean isGoIntoTarget(Object element) {
if (element == null)
return false;
if (element instanceof IJavaElement) {
int type= ((IJavaElement)element).getElementType();
return type == IJavaElement.JAVA_PROJECT ||
type == IJavaElement.PACKAGE_FRAGMENT_ROOT ||
type == IJavaElement.PACKAGE_FRAGMENT;
}
return false;
}
private void addOpenNewWindowAction(IMenuManager menu, Object element) {
if (element instanceof IJavaElement) {
element= ((IJavaElement)element).getResource();
}
if (!(element instanceof IContainer))
return;
menu.appendToGroup(
IContextMenuConstants.GROUP_OPEN,
new OpenInNewWindowAction(fPart.getSite().getWorkbenchWindow(), (IContainer)element));
}
//---- Key board and mouse handling ------------------------------------------------------------
/* package*/ void handleDoubleClick(DoubleClickEvent event) {
TreeViewer viewer= fPart.getViewer();
Object element= ((IStructuredSelection)event.getSelection()).getFirstElement();
if (viewer.isExpandable(element)) {
if (doubleClickGoesInto()) {
// don't zoom into compilation units and class files
if (element instanceof IOpenable &&
!(element instanceof ICompilationUnit) &&
!(element instanceof IClassFile)) {
fZoomInAction.run();
}
} else {
if (element instanceof ICompilationUnit && OpenStrategy.getOpenMethod() == OpenStrategy.DOUBLE_CLICK)
return;
viewer.setExpandedState(element, !viewer.getExpandedState(element));
}
}
}
/* package */ void handleOpen(OpenEvent event) {
IAction openAction= fNavigateActionGroup.getOpenAction();
if (openAction != null && openAction.isEnabled()) {
openAction.run();
return;
}
}
/* package */ void handleKeyEvent(KeyEvent event) {
if (event.stateMask != 0)
return;
if (event.keyCode == SWT.F5) {
IAction refreshAction= fBuildActionGroup.getRefreshAction();
if (refreshAction != null && refreshAction.isEnabled())
refreshAction.run();
} else if (event.character == SWT.DEL) {
IAction delete= fCCPActionGroup.getDeleteAction();
if (delete != null && delete.isEnabled())
delete.run();
}
else if (event.keyCode == SWT.BS) {
if (fUpAction != null && fUpAction.isEnabled())
fUpAction.run();
}
}
private IPropertyChangeListener createTitleUpdater() {
return new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
String property= event.getProperty();
if (IWorkingSetManager.CHANGE_WORKING_SET_NAME_CHANGE.equals(property)) {
IWorkingSet workingSet= (IWorkingSet)event.getNewValue();
String workingSetName= null;
if (workingSet != null)
workingSetName= workingSet.getName();
fPart.setWorkingSetName(workingSetName);
fPart.updateTitle();
}
}
};
}
private boolean showCompilationUnitChildren() {
return PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.SHOW_CU_CHILDREN);
}
private boolean doubleClickGoesInto() {
return PreferenceConstants.DOUBLE_CLICK_GOES_INTO.equals(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.DOUBLE_CLICK));
}
}
|
27,462 |
Bug 27462 [startup] SearchPlugin is loaded when Java plug-in gets loaded
|
The Java UI plugin eagerly activates the Search plugin. There are 2 reason: 1) ISearchPageScore adapter that is registered 2) fSearchResultViewEntryAdapterFactory we should investigate whether we can reduce this plugin activation.
|
resolved fixed
|
58624b6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-03T15:28:28Z | 2002-11-30T23:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/EditorInputAdapterFactory.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui;
import org.eclipse.core.runtime.IAdapterFactory;
import org.eclipse.search.ui.ISearchPageScoreComputer;
import org.eclipse.jdt.internal.ui.search.JavaSearchPageScoreComputer;
/**
* Adapter factory to support basic UI operations for for editor inputs.
*/
public class EditorInputAdapterFactory implements IAdapterFactory {
private static Class[] PROPERTIES= new Class[] {
ISearchPageScoreComputer.class
};
private ISearchPageScoreComputer fSearchPageScoreComputer;
public Class[] getAdapterList() {
return PROPERTIES;
}
public Object getAdapter(Object element, Class key) {
if (ISearchPageScoreComputer.class.equals(key))
return getSearchPageScoreComputer();
return null;
}
private ISearchPageScoreComputer getSearchPageScoreComputer() {
if (fSearchPageScoreComputer == null)
fSearchPageScoreComputer= new JavaSearchPageScoreComputer();
return fSearchPageScoreComputer;
}
}
|
27,462 |
Bug 27462 [startup] SearchPlugin is loaded when Java plug-in gets loaded
|
The Java UI plugin eagerly activates the Search plugin. There are 2 reason: 1) ISearchPageScore adapter that is registered 2) fSearchResultViewEntryAdapterFactory we should investigate whether we can reduce this plugin activation.
|
resolved fixed
|
58624b6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-03T15:28:28Z | 2002-11-30T23:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/JavaElementAdapterFactory.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IAdapterFactory;
import org.eclipse.ui.IContributorResourceAdapter;
import org.eclipse.ui.IPersistableElement;
import org.eclipse.ui.model.IWorkbenchAdapter;
import org.eclipse.ui.views.properties.FilePropertySource;
import org.eclipse.ui.views.properties.IPropertySource;
import org.eclipse.ui.views.properties.ResourcePropertySource;
import org.eclipse.ui.views.tasklist.ITaskListResourceAdapter;
import org.eclipse.search.ui.ISearchPageScoreComputer;
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.internal.ui.search.JavaSearchPageScoreComputer;
/**
* Implements basic UI support for Java elements.
* Implements handle to persistent support for Java elements.
*/
public class JavaElementAdapterFactory implements IAdapterFactory, IContributorResourceAdapter{
private static Class[] PROPERTIES= new Class[] {
IPropertySource.class,
IResource.class,
ISearchPageScoreComputer.class,
IWorkbenchAdapter.class,
IResourceLocator.class,
IPersistableElement.class,
IProject.class,
IContributorResourceAdapter.class,
ITaskListResourceAdapter.class
};
private ISearchPageScoreComputer fSearchPageScoreComputer= new JavaSearchPageScoreComputer();
private static IResourceLocator fgResourceLocator= new ResourceLocator();
private static JavaWorkbenchAdapter fgJavaWorkbenchAdapter= new JavaWorkbenchAdapter();
private static ITaskListResourceAdapter fgTaskListAdapter= new JavaTaskListAdapter();
public Class[] getAdapterList() {
return PROPERTIES;
}
public Object getAdapter(Object element, Class key) {
IJavaElement java= (IJavaElement) element;
if (IPropertySource.class.equals(key)) {
return getProperties(java);
} if (IResource.class.equals(key)) {
return getResource(java);
} if (IProject.class.equals(key)) {
return getProject(java);
} if (ISearchPageScoreComputer.class.equals(key)) {
return fSearchPageScoreComputer;
} if (IWorkbenchAdapter.class.equals(key)) {
return fgJavaWorkbenchAdapter;
} if (IResourceLocator.class.equals(key)) {
return fgResourceLocator;
} if (IPersistableElement.class.equals(key)) {
return new PersistableJavaElementFactory(java);
} if (IContributorResourceAdapter.class.equals(key)) {
return this;
} if (ITaskListResourceAdapter.class.equals(key)) {
return fgTaskListAdapter;
}
return null;
}
private IResource getResource(IJavaElement element) {
/*
* Map a type to the corresponding CU.
*/
if (element instanceof IType) {
IType type= (IType)element;
IJavaElement parent= type.getParent();
if (parent instanceof ICompilationUnit) {
ICompilationUnit cu= (ICompilationUnit)parent;
if (cu.isWorkingCopy())
element= cu.getOriginalElement();
else
element= cu;
}
}
try {
return element.getCorrespondingResource();
} catch (JavaModelException e) {
if (element instanceof ICompilationUnit)
return element.getResource(); //handles compilation units outside of the classpath
else
return null;
}
}
/*
* @see org.eclipse.ui.IContributorResourceAdapter#getAdaptedResource(org.eclipse.core.runtime.IAdaptable)
*/
public IResource getAdaptedResource(IAdaptable adaptable) {
return getResource((IJavaElement)adaptable);
}
private IResource getProject(IJavaElement element) {
return element.getJavaProject().getProject();
}
private IPropertySource getProperties(IJavaElement element) {
IResource resource= getResource(element);
if (resource == null)
return new JavaElementProperties(element);
if (resource.getType() == IResource.FILE)
return new FilePropertySource((IFile) resource);
return new ResourcePropertySource((IResource) resource);
}
}
|
27,462 |
Bug 27462 [startup] SearchPlugin is loaded when Java plug-in gets loaded
|
The Java UI plugin eagerly activates the Search plugin. There are 2 reason: 1) ISearchPageScore adapter that is registered 2) fSearchResultViewEntryAdapterFactory we should investigate whether we can reduce this plugin activation.
|
resolved fixed
|
58624b6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-03T15:28:28Z | 2002-11-30T23:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/MarkerAdapterFactory.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui;
import org.eclipse.core.runtime.IAdapterFactory;
import org.eclipse.search.ui.ISearchPageScoreComputer;
import org.eclipse.jdt.internal.ui.search.JavaSearchPageScoreComputer;
/**
* Adapter factory to support basic UI operations for markers.
*/
public class MarkerAdapterFactory implements IAdapterFactory {
private static Class[] PROPERTIES= new Class[] {
ISearchPageScoreComputer.class
};
private ISearchPageScoreComputer fSearchPageScoreComputer;
public Class[] getAdapterList() {
return PROPERTIES;
}
public Object getAdapter(Object element, Class key) {
if (ISearchPageScoreComputer.class.equals(key))
return getSearchPageScoreComputer();
return null;
}
private ISearchPageScoreComputer getSearchPageScoreComputer() {
if (fSearchPageScoreComputer == null)
fSearchPageScoreComputer= new JavaSearchPageScoreComputer();
return fSearchPageScoreComputer;
}
}
|
27,491 |
Bug 27491 Cannot add classpath variable to project
|
build id : 200212020010 The buttons OK and extend... are always disabled in the add variable dialog
|
resolved fixed
|
ab59e23
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-04T08:10:46Z | 2002-12-02T14:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/dialogfields/ListDialogField.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.wizards.dialogfields;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
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.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.ColumnLayoutData;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.jdt.internal.ui.util.PixelConverter;
import org.eclipse.jdt.internal.ui.util.SWTUtil;
/**
* A list with a button bar.
* Typical buttons are 'Add', 'Remove', 'Up' and 'Down'.
* List model is independend of widget creation.
* DialogFields controls are: Label, List and Composite containing buttons.
*/
public class ListDialogField extends DialogField {
public static class ColumnsDescription {
private ColumnLayoutData[] columns;
private String[] headers;
private boolean drawLines;
public ColumnsDescription(ColumnLayoutData[] columns, String[] headers, boolean drawLines) {
this.columns= columns;
this.headers= headers;
this.drawLines= drawLines;
}
public ColumnsDescription(String[] headers, boolean drawLines) {
this(createColumnWeightData(headers.length), headers, drawLines);
}
public ColumnsDescription(int nColumns, boolean drawLines) {
this(createColumnWeightData(nColumns), null, drawLines);
}
private static ColumnLayoutData[] createColumnWeightData(int nColumns) {
ColumnLayoutData[] data= new ColumnLayoutData[nColumns];
for (int i= 0; i < nColumns; i++) {
data[i]= new ColumnWeightData(1);
}
return data;
}
}
protected TableViewer fTable;
protected ILabelProvider fLabelProvider;
protected ListViewerAdapter fListViewerAdapter;
protected List fElements;
protected ViewerSorter fViewerSorter;
protected String[] fButtonLabels;
private Button[] fButtonControls;
private boolean[] fButtonsEnabled;
private int fRemoveButtonIndex;
private int fUpButtonIndex;
private int fDownButtonIndex;
private Label fLastSeparator;
private Table fTableControl;
private Composite fButtonsControl;
private ISelection fSelectionWhenEnabled;
private IListAdapter fListAdapter;
private Object fParentElement;
private ColumnsDescription fTableColumns;
/**
* Creates the <code>ListDialogField</code>.
* @param adapter A listener for button invocation, selection changes.
* @param buttonLabels The labels of all buttons: <code>null</code> is a valid array entry and
* marks a separator.
* @param lprovider The label provider to render the table entries
*/
public ListDialogField(IListAdapter adapter, String[] buttonLabels, ILabelProvider lprovider) {
super();
fListAdapter= adapter;
fLabelProvider= lprovider;
fListViewerAdapter= new ListViewerAdapter();
fParentElement= this;
fElements= new ArrayList(10);
fButtonLabels= buttonLabels;
if (fButtonLabels != null) {
int nButtons= fButtonLabels.length;
fButtonsEnabled= new boolean[nButtons];
for (int i= 0; i < nButtons; i++) {
fButtonsEnabled[i]= true;
}
}
fTable= null;
fTableControl= null;
fButtonsControl= null;
fTableColumns= null;
fRemoveButtonIndex= -1;
fUpButtonIndex= -1;
fDownButtonIndex= -1;
}
/**
* Sets the index of the 'remove' button in the button label array passed in the constructor.
* The behaviour of the button marked as the 'remove' button will then be handled internally.
* (enable state, button invocation behaviour)
*/
public void setRemoveButtonIndex(int removeButtonIndex) {
Assert.isTrue(removeButtonIndex < fButtonLabels.length);
fRemoveButtonIndex= removeButtonIndex;
}
/**
* Sets the index of the 'up' button in the button label array passed in the constructor.
* The behaviour of the button marked as the 'up' button will then be handled internally.
* (enable state, button invocation behaviour)
*/
public void setUpButtonIndex(int upButtonIndex) {
Assert.isTrue(upButtonIndex < fButtonLabels.length);
fUpButtonIndex= upButtonIndex;
}
/**
* Sets the index of the 'down' button in the button label array passed in the constructor.
* The behaviour of the button marked as the 'down' button will then be handled internally.
* (enable state, button invocation behaviour)
*/
public void setDownButtonIndex(int downButtonIndex) {
Assert.isTrue(downButtonIndex < fButtonLabels.length);
fDownButtonIndex= downButtonIndex;
}
/**
* Sets the viewerSorter.
* @param viewerSorter The viewerSorter to set
*/
public void setViewerSorter(ViewerSorter viewerSorter) {
fViewerSorter= viewerSorter;
}
public void setTableColumns(ColumnsDescription column) {
fTableColumns= column;
}
// ------ adapter communication
private void buttonPressed(int index) {
if (!managedButtonPressed(index)) {
fListAdapter.customButtonPressed(this, index);
}
}
/**
* Checks if the button pressed is handled internally
* @return Returns true if button has been handled.
*/
protected boolean managedButtonPressed(int index) {
if (index == fRemoveButtonIndex) {
remove();
} else if (index == fUpButtonIndex) {
up();
} else if (index == fDownButtonIndex) {
down();
} else {
return false;
}
return true;
}
// ------ layout helpers
/*
* @see DialogField#doFillIntoGrid
*/
public Control[] doFillIntoGrid(Composite parent, int nColumns) {
PixelConverter converter= new PixelConverter(parent);
assertEnoughColumns(nColumns);
Label label= getLabelControl(parent);
GridData gd= gridDataForLabel(1);
gd.verticalAlignment= GridData.BEGINNING;
label.setLayoutData(gd);
Control list= getListControl(parent);
gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.grabExcessHorizontalSpace= false;
gd.verticalAlignment= GridData.FILL;
gd.grabExcessVerticalSpace= true;
gd.horizontalSpan= nColumns - 2;
gd.widthHint= converter.convertWidthInCharsToPixels(50);
gd.heightHint= converter.convertHeightInCharsToPixels(6);
list.setLayoutData(gd);
Composite buttons= getButtonBox(parent);
gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.grabExcessHorizontalSpace= false;
gd.verticalAlignment= GridData.FILL;
gd.grabExcessVerticalSpace= true;
gd.horizontalSpan= 1;
buttons.setLayoutData(gd);
return new Control[] { label, list, buttons };
}
/*
* @see DialogField#getNumberOfControls
*/
public int getNumberOfControls() {
return 3;
}
/**
* Sets the minimal width of the buttons. Must be called after widget creation.
*/
public void setButtonsMinWidth(int minWidth) {
if (fLastSeparator != null) {
((GridData)fLastSeparator.getLayoutData()).widthHint= minWidth;
}
}
// ------ ui creation
/**
* Returns the list control. When called the first time, the control will be created.
* @param The parent composite when called the first time, or <code>null</code>
* after.
*/
public Control getListControl(Composite parent) {
if (fTableControl == null) {
assertCompositeNotNull(parent);
fTable= createTableViewer(parent);
fTableControl= (Table)fTable.getControl();
fTableControl.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
handleKeyPressed(e);
}
});
TableLayout tableLayout= new TableLayout();
fTableControl.setLayout(tableLayout);
if (fTableColumns != null) {
fTableControl.setHeaderVisible(fTableColumns.headers != null);
fTableControl.setLinesVisible(fTableColumns.drawLines);
ColumnLayoutData[] columns= fTableColumns.columns;
for (int i= 0; i < columns.length; i++) {
TableColumn column= new TableColumn(fTableControl, SWT.NONE);
tableLayout.addColumnData(columns[i]);
if (fTableColumns.headers != null) {
column.setText(fTableColumns.headers[i]);
}
}
}
fTable.setContentProvider(fListViewerAdapter);
fTable.setLabelProvider(fLabelProvider);
fTable.addSelectionChangedListener(fListViewerAdapter);
fTable.setInput(fParentElement);
if (fViewerSorter != null) {
fTable.setSorter(fViewerSorter);
}
fTableControl.setEnabled(isEnabled());
if (fSelectionWhenEnabled != null) {
postSetSelection(fSelectionWhenEnabled);
}
}
return fTableControl;
}
/**
* Returns the internally used table viewer.
*/
public TableViewer getTableViewer() {
return fTable;
}
/*
* Subclasses may override to specify a different style.
*/
protected int getListStyle(){
int style= SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL ;
if (fTableColumns != null) {
style |= SWT.FULL_SELECTION;
}
return style;
}
protected TableViewer createTableViewer(Composite parent) {
Table table= new Table(parent, getListStyle());
return new TableViewer(table);
}
protected Button createButton(Composite parent, String label, SelectionListener listener) {
Button button= new Button(parent, SWT.PUSH);
button.setText(label);
button.addSelectionListener(listener);
GridData gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.grabExcessHorizontalSpace= true;
gd.verticalAlignment= GridData.BEGINNING;
gd.heightHint = SWTUtil.getButtonHeigthHint(button);
gd.widthHint = SWTUtil.getButtonWidthHint(button);
button.setLayoutData(gd);
return button;
}
private Label createSeparator(Composite parent) {
Label separator= new Label(parent, SWT.NONE);
separator.setVisible(false);
GridData gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.verticalAlignment= GridData.BEGINNING;
gd.heightHint= 4;
separator.setLayoutData(gd);
return separator;
}
/**
* Returns the composite containing the buttons. When called the first time, the control
* will be created.
* @param The parent composite when called the first time, or <code>null</code>
* after.
*/
public Composite getButtonBox(Composite parent) {
if (fButtonsControl == null) {
assertCompositeNotNull(parent);
SelectionListener listener= new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
doButtonSelected(e);
}
public void widgetSelected(SelectionEvent e) {
doButtonSelected(e);
}
};
Composite contents= new Composite(parent, SWT.NULL);
GridLayout layout= new GridLayout();
layout.marginWidth= 0;
layout.marginHeight= 0;
contents.setLayout(layout);
if (fButtonLabels != null) {
fButtonControls= new Button[fButtonLabels.length];
for (int i= 0; i < fButtonLabels.length; i++) {
String currLabel= fButtonLabels[i];
if (currLabel != null) {
fButtonControls[i]= createButton(contents, currLabel, listener);
fButtonControls[i].setEnabled(isEnabled() && fButtonsEnabled[i]);
} else {
fButtonControls[i]= null;
createSeparator(contents);
}
}
}
fLastSeparator= createSeparator(contents);
updateButtonState();
fButtonsControl= contents;
}
return fButtonsControl;
}
private void doButtonSelected(SelectionEvent e) {
if (fButtonControls != null) {
for (int i= 0; i < fButtonControls.length; i++) {
if (e.widget == fButtonControls[i]) {
buttonPressed(i);
return;
}
}
}
}
/**
* Handles key events in the table viewer. Specifically
* when the delete key is pressed.
*/
protected void handleKeyPressed(KeyEvent event) {
if (event.character == SWT.DEL && event.stateMask == 0) {
if (fRemoveButtonIndex != -1 && isButtonEnabled(fTable.getSelection(), fRemoveButtonIndex)) {
managedButtonPressed(fRemoveButtonIndex);
}
}
}
// ------ enable / disable management
/*
* @see DialogField#dialogFieldChanged
*/
public void dialogFieldChanged() {
super.dialogFieldChanged();
updateButtonState();
}
private Button getButton(int index) {
if (fButtonControls != null && index >= 0 && index < fButtonControls.length) {
return fButtonControls[index];
}
return null;
}
/*
* Updates the enable state of the all buttons
*/
protected void updateButtonState() {
if (fButtonControls != null) {
ISelection sel= fTable.getSelection();
for (int i= 0; i < fButtonControls.length; i++) {
Button button= fButtonControls[i];
if (isOkToUse(button)) {
button.setEnabled(isButtonEnabled(sel, i));
}
}
}
}
protected boolean getManagedButtonState(ISelection sel, int index) {
if (index == fRemoveButtonIndex) {
return !sel.isEmpty();
} else if (index == fUpButtonIndex) {
return !sel.isEmpty() && canMoveUp();
} else if (index == fDownButtonIndex) {
return !sel.isEmpty() && canMoveDown();
}
return true;
}
/*
* @see DialogField#updateEnableState
*/
protected void updateEnableState() {
super.updateEnableState();
boolean enabled= isEnabled();
if (isOkToUse(fTableControl)) {
if (!enabled) {
fSelectionWhenEnabled= fTable.getSelection();
selectElements(null);
} else {
selectElements(fSelectionWhenEnabled);
fSelectionWhenEnabled= null;
}
fTableControl.setEnabled(enabled);
}
updateButtonState();
}
/**
* Sets a button enabled or disabled.
*/
public void enableButton(int index, boolean enable) {
if (fButtonsEnabled != null && index < fButtonsEnabled.length) {
fButtonsEnabled[index]= enable;
updateButtonState();
}
}
private boolean isButtonEnabled(ISelection sel, int index) {
boolean extraState= getManagedButtonState(sel, index);
return isEnabled() && extraState && fButtonsEnabled[index];
}
// ------ model access
/**
* Sets the elements shown in the list.
*/
public void setElements(List elements) {
fElements= new ArrayList(elements);
if (fTable != null) {
fTable.refresh();
}
dialogFieldChanged();
}
/**
* Gets the elements shown in the list.
* The list returned is a copy, so it can be modified by the user.
*/
public List getElements() {
return new ArrayList(fElements);
}
/**
* Gets the elements shown at the given index.
*/
public Object getElement(int index) {
return fElements.get(index);
}
/**
* Gets the index of an element in the list or -1 if element is not in list.
*/
public int getIndexOfElement(Object elem) {
return fElements.indexOf(elem);
}
/**
* Replace an element.
*/
public void replaceElement(Object oldElement, Object newElement) throws IllegalArgumentException {
int idx= fElements.indexOf(oldElement);
if (idx != -1) {
if (oldElement.equals(newElement) || fElements.contains(newElement)) {
return;
}
fElements.set(idx, newElement);
if (fTable != null) {
List selected= getSelectedElements();
if (selected.remove(oldElement)) {
selected.add(newElement);
}
fTable.refresh();
selectElements(new StructuredSelection(selected));
}
dialogFieldChanged();
} else {
throw new IllegalArgumentException();
}
}
/**
* Adds an element at the end of the list.
*/
public void addElement(Object element) {
if (fElements.contains(element)) {
return;
}
fElements.add(element);
if (fTable != null) {
fTable.add(element);
}
dialogFieldChanged();
}
/**
* Adds elements at the end of the list.
*/
public void addElements(List elements) {
int nElements= elements.size();
if (nElements > 0) {
// filter duplicated
ArrayList elementsToAdd= new ArrayList(nElements);
for (int i= 0; i < nElements; i++) {
Object elem= elements.get(i);
if (!fElements.contains(elem)) {
elementsToAdd.add(elem);
}
}
fElements.addAll(elementsToAdd);
if (fTable != null) {
fTable.add(elementsToAdd.toArray());
}
dialogFieldChanged();
}
}
/**
* Adds an element at a position.
*/
public void insertElementAt(Object element, int index) {
if (fElements.contains(element)) {
return;
}
fElements.add(index, element);
if (fTable != null) {
fTable.add(element);
}
dialogFieldChanged();
}
/**
* Adds an element at a position.
*/
public void removeAllElements() {
if (fElements.size() > 0) {
fElements.clear();
if (fTable != null) {
fTable.refresh();
}
dialogFieldChanged();
}
}
/**
* Removes an element from the list.
*/
public void removeElement(Object element) throws IllegalArgumentException {
if (fElements.remove(element)) {
if (fTable != null) {
fTable.remove(element);
}
dialogFieldChanged();
} else {
throw new IllegalArgumentException();
}
}
/**
* Removes elements from the list.
*/
public void removeElements(List elements) {
if (elements.size() > 0) {
fElements.removeAll(elements);
if (fTable != null) {
fTable.remove(elements.toArray());
}
dialogFieldChanged();
}
}
/**
* Gets the number of elements
*/
public int getSize() {
return fElements.size();
}
public void selectElements(ISelection selection) {
fSelectionWhenEnabled= selection;
if (fTable != null) {
fTable.setSelection(selection, true);
}
}
public void selectFirstElement() {
Object element= null;
if (fViewerSorter != null) {
Object[] arr= fElements.toArray();
fViewerSorter.sort(fTable, arr);
if (arr.length > 0) {
element= arr[0];
}
} else {
if (fElements.size() > 0) {
element= fElements.get(0);
}
}
if (element != null) {
selectElements(new StructuredSelection(element));
}
}
public void postSetSelection(final ISelection selection) {
if (isOkToUse(fTableControl)) {
Display d= fTableControl.getDisplay();
d.asyncExec(new Runnable() {
public void run() {
if (isOkToUse(fTableControl)) {
selectElements(selection);
}
}
});
}
}
/**
* Refreshes the table.
*/
public void refresh() {
if (fTable != null) {
fTable.refresh();
}
}
// ------- list maintenance
private List moveUp(List elements, List move) {
int nElements= elements.size();
List res= new ArrayList(nElements);
Object floating= null;
for (int i= 0; i < nElements; i++) {
Object curr= elements.get(i);
if (move.contains(curr)) {
res.add(curr);
} else {
if (floating != null) {
res.add(floating);
}
floating= curr;
}
}
if (floating != null) {
res.add(floating);
}
return res;
}
private void moveUp(List toMoveUp) {
if (toMoveUp.size() > 0) {
setElements(moveUp(fElements, toMoveUp));
fTable.reveal(toMoveUp.get(0));
}
}
private void moveDown(List toMoveDown) {
if (toMoveDown.size() > 0) {
setElements(reverse(moveUp(reverse(fElements), toMoveDown)));
fTable.reveal(toMoveDown.get(toMoveDown.size() - 1));
}
}
private List reverse(List p) {
List reverse= new ArrayList(p.size());
for (int i= p.size()-1; i >= 0; i--) {
reverse.add(p.get(i));
}
return reverse;
}
private void remove() {
removeElements(getSelectedElements());
}
private void up() {
moveUp(getSelectedElements());
}
private void down() {
moveDown(getSelectedElements());
}
private boolean canMoveUp() {
if (isOkToUse(fTableControl)) {
int[] indc= fTableControl.getSelectionIndices();
for (int i= 0; i < indc.length; i++) {
if (indc[i] != i) {
return true;
}
}
}
return false;
}
private boolean canMoveDown() {
if (isOkToUse(fTableControl)) {
int[] indc= fTableControl.getSelectionIndices();
int k= fElements.size() - 1;
for (int i= indc.length - 1; i >= 0 ; i--, k--) {
if (indc[i] != k) {
return true;
}
}
}
return false;
}
/**
* Returns the selected elements.
*/
public List getSelectedElements() {
List result= new ArrayList();
if (fTable != null) {
ISelection selection= fTable.getSelection();
if (selection instanceof IStructuredSelection) {
Iterator iter= ((IStructuredSelection)selection).iterator();
while (iter.hasNext()) {
result.add(iter.next());
}
}
}
return new ArrayList(0);
}
// ------- ListViewerAdapter
private class ListViewerAdapter implements IStructuredContentProvider, ISelectionChangedListener {
// ------- ITableContentProvider Interface ------------
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
// will never happen
}
public boolean isDeleted(Object element) {
return false;
}
public void dispose() {
}
public Object[] getElements(Object obj) {
return fElements.toArray();
}
// ------- ISelectionChangedListener Interface ------------
public void selectionChanged(SelectionChangedEvent event) {
doListSelected(event);
}
}
private void doListSelected(SelectionChangedEvent event) {
updateButtonState();
if (fListAdapter != null) {
fListAdapter.selectionChanged(this);
}
}
}
|
27,730 |
Bug 27730 Link not recolor on paste
|
I20021127 - copy some text - position the I beam on a line where you want to paste - position the cursor over a type name - press Ctrl to get the link highlighting - press V to paste the text observe: the link disappears but the type name is still rendered in blue.
|
resolved fixed
|
66ccfa2
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-05T11:24:08Z | 2002-12-05T09:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaEditor.java
|
/**********************************************************************
Copyright (c) 2000, 2002 IBM Corp. and others.
All rights reserved. This program and the accompanying materials
are made available under the terms of the Common Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/cpl-v10.html
Contributors:
IBM Corporation - Initial implementation
**********************************************************************/
package org.eclipse.jdt.internal.ui.javaeditor;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BidiSegmentEvent;
import org.eclipse.swt.custom.BidiSegmentListener;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DefaultInformationControl;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.jface.text.IInformationControl;
import org.eclipse.jface.text.IInformationControlCreator;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextHover;
import org.eclipse.jface.text.ITextInputListener;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.ITextViewerExtension2;
import org.eclipse.jface.text.ITextViewerExtension3;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.text.information.IInformationProvider;
import org.eclipse.jface.text.information.InformationPresenter;
import org.eclipse.jface.text.source.AnnotationRulerColumn;
import org.eclipse.jface.text.source.CompositeRuler;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.IVerticalRuler;
import org.eclipse.jface.text.source.IVerticalRulerColumn;
import org.eclipse.jface.text.source.LineNumberRulerColumn;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IPartService;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.editors.text.DefaultEncodingSupport;
import org.eclipse.ui.editors.text.IEncodingSupport;
import org.eclipse.ui.part.EditorActionBarContributor;
import org.eclipse.ui.texteditor.AddTaskAction;
import org.eclipse.ui.texteditor.DefaultRangeIndicator;
import org.eclipse.ui.texteditor.IAbstractTextEditorHelpContextIds;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
import org.eclipse.ui.texteditor.ResourceAction;
import org.eclipse.ui.texteditor.StatusTextEditor;
import org.eclipse.ui.texteditor.TextEditorAction;
import org.eclipse.ui.texteditor.TextOperationAction;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICodeAssist;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IPackageDeclaration;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds;
import org.eclipse.jdt.ui.actions.JavaSearchActionGroup;
import org.eclipse.jdt.ui.actions.OpenEditorActionGroup;
import org.eclipse.jdt.ui.actions.OpenViewActionGroup;
import org.eclipse.jdt.ui.actions.ShowActionGroup;
import org.eclipse.jdt.ui.text.IColorManager;
import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter;
import org.eclipse.jdt.internal.ui.text.JavaPartitionScanner;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider;
/**
* Java specific text editor.
*/
public abstract class JavaEditor extends StatusTextEditor implements IViewPartInputProvider {
/**
* "Smart" runnable for updating the outline page's selection.
*/
class OutlinePageSelectionUpdater implements Runnable {
/** Has the runnable already been posted? */
private boolean fPosted= false;
public OutlinePageSelectionUpdater() {
}
/*
* @see Runnable#run()
*/
public void run() {
synchronizeOutlinePageSelection();
fPosted= false;
}
/**
* Posts this runnable into the event queue.
*/
public void post() {
if (fPosted)
return;
Shell shell= getSite().getShell();
if (shell != null & !shell.isDisposed()) {
fPosted= true;
shell.getDisplay().asyncExec(this);
}
}
};
class SelectionChangedListener implements ISelectionChangedListener {
public void selectionChanged(SelectionChangedEvent event) {
doSelectionChanged(event);
}
};
/**
* Link mode.
*/
class MouseClickListener implements KeyListener, MouseListener, MouseMoveListener,
FocusListener, PaintListener, IPropertyChangeListener, IDocumentListener, ITextInputListener {
/** The session is active. */
private boolean fActive;
/** The currently active style range. */
private IRegion fActiveRegion;
/** The hand cursor. */
private Cursor fCursor;
/** The default cursor. */
private Cursor fDefaultCursor;
/** The link color. */
private Color fColor;
public void deactivate() {
if (!fActive)
return;
repairRepresentation();
fActive= false;
}
public void install() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
StyledText text= sourceViewer.getTextWidget();
if (text == null || text.isDisposed())
return;
updateColor(sourceViewer);
sourceViewer.addTextInputListener(this);
IDocument document= sourceViewer.getDocument();
if (document != null)
document.addDocumentListener(this);
text.addKeyListener(this);
text.addMouseListener(this);
text.addMouseMoveListener(this);
text.addFocusListener(this);
text.addPaintListener(this);
IPreferenceStore preferenceStore= getPreferenceStore();
preferenceStore.addPropertyChangeListener(this);
}
public void uninstall() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
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);
if (fColor != null) {
fColor.dispose();
fColor= null;
}
if (fCursor != null) {
fCursor.dispose();
fCursor= null;
}
}
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(JavaEditor.LINK_COLOR)) {
ISourceViewer viewer= getSourceViewer();
if (viewer != null)
updateColor(viewer);
}
}
private void updateColor(ISourceViewer viewer) {
if (fColor != null)
fColor.dispose();
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
Display display= text.getDisplay();
fColor= createColor(getPreferenceStore(), JavaEditor.LINK_COLOR, display);
}
/**
* Creates a color from the information stored in the given preference store.
* Returns <code>null</code> if there is no such information available.
*/
private Color createColor(IPreferenceStore store, String key, Display display) {
RGB rgb= null;
if (store.contains(key)) {
if (store.isDefault(key))
rgb= PreferenceConverter.getDefaultColor(store, key);
else
rgb= PreferenceConverter.getColor(store, key);
if (rgb != null)
return new Color(display, rgb);
}
return null;
}
private void repairRepresentation() {
if (fActiveRegion == null)
return;
ISourceViewer viewer= getSourceViewer();
if (viewer != null) {
resetCursor(viewer);
int offset= fActiveRegion.getOffset();
int length= fActiveRegion.getLength();
// remove style
if (viewer instanceof ITextViewerExtension2)
((ITextViewerExtension2) viewer).invalidateTextPresentation(offset, length);
else
viewer.invalidateTextPresentation();
// remove underline
if (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
offset= extension.modelOffset2WidgetOffset(offset);
} else {
offset -= viewer.getVisibleRegion().getOffset();
}
StyledText text= viewer.getTextWidget();
text.redrawRange(offset, length, true);
}
fActiveRegion= null;
}
private IJavaElement getInput(JavaEditor editor) {
if (editor == null)
return null;
IEditorInput input= editor.getEditorInput();
if (input instanceof IClassFileEditorInput)
return ((IClassFileEditorInput)input).getClassFile();
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
return manager.getWorkingCopy(input);
}
// will eventually be replaced by a method provided by jdt.core
private IRegion selectWord(IDocument document, int anchor) {
try {
int offset= anchor;
char c;
while (offset >= 0) {
c= document.getChar(offset);
if (!Character.isJavaIdentifierPart(c))
break;
--offset;
}
int start= offset;
offset= anchor;
int length= document.getLength();
while (offset < length) {
c= document.getChar(offset);
if (!Character.isJavaIdentifierPart(c))
break;
++offset;
}
int end= offset;
if (start == end)
return new Region(start, 0);
else
return new Region(start + 1, end - start - 1);
} catch (BadLocationException x) {
return null;
}
}
IRegion getCurrentTextRegion(ISourceViewer viewer) {
int offset= getCurrentTextOffset(viewer);
if (offset == -1)
return null;
IJavaElement input= SelectionConverter.getInput(JavaEditor.this);
if (input == null)
return null;
try {
IJavaElement[] elements= ((ICodeAssist) input).codeSelect(offset, 0);
if (elements == null || elements.length == 0)
return null;
return selectWord(viewer.getDocument(), offset);
} catch (JavaModelException e) {
return null;
}
}
private int getCurrentTextOffset(ISourceViewer viewer) {
try {
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return -1;
Display display= text.getDisplay();
Point absolutePosition= display.getCursorLocation();
Point relativePosition= text.toControl(absolutePosition);
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;
StyleRange styleRange= new StyleRange(offset, length, foregroundColor, backgroundColor);
text.setStyleRange(styleRange);
// underline
text.redrawRange(offset, length, true);
fActiveRegion= region;
}
private void activateCursor(ISourceViewer viewer) {
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
Display display= text.getDisplay();
if (fCursor == null)
fCursor= new Cursor(display, SWT.CURSOR_HAND);
text.setCursor(fCursor);
}
private void resetCursor(ISourceViewer viewer) {
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
Display display= text.getDisplay();
if (fDefaultCursor == null)
fDefaultCursor= new Cursor(display, SWT.CURSOR_IBEAM);
text.setCursor(fDefaultCursor);
if (fCursor != null) {
fCursor.dispose();
fCursor= null;
}
}
/*
* @see org.eclipse.swt.events.KeyListener#keyPressed(org.eclipse.swt.events.KeyEvent)
*/
public void keyPressed(KeyEvent event) {
if (fActive) {
deactivate();
return;
}
if (event.keyCode != SWT.CTRL) {
deactivate();
return;
}
fActive= true;
ISourceViewer viewer= getSourceViewer();
if (viewer == null)
return;
IRegion region= getCurrentTextRegion(viewer);
if (region == null)
return;
// removed for #25871
// highlightRegion(viewer, region);
// activateCursor(viewer);
}
/*
* @see org.eclipse.swt.events.KeyListener#keyReleased(org.eclipse.swt.events.KeyEvent)
*/
public void keyReleased(KeyEvent event) {
if (!fActive)
return;
deactivate();
}
/*
* @see org.eclipse.swt.events.MouseListener#mouseDoubleClick(org.eclipse.swt.events.MouseEvent)
*/
public void mouseDoubleClick(MouseEvent e) {}
/*
* @see org.eclipse.swt.events.MouseListener#mouseDown(org.eclipse.swt.events.MouseEvent)
*/
public void mouseDown(MouseEvent event) {
if (!fActive)
return;
if (event.stateMask != SWT.CTRL) {
deactivate();
return;
}
if (event.button != 1) {
deactivate();
return;
}
}
/*
* @see org.eclipse.swt.events.MouseListener#mouseUp(org.eclipse.swt.events.MouseEvent)
*/
public void mouseUp(MouseEvent e) {
if (!fActive)
return;
if (e.button != 1) {
deactivate();
return;
}
deactivate();
IAction action= getAction("OpenEditor"); //$NON-NLS-1$
if (action == null)
return;
action.run();
}
/*
* @see org.eclipse.swt.events.MouseMoveListener#mouseMove(org.eclipse.swt.events.MouseEvent)
*/
public void mouseMove(MouseEvent event) {
if (event.widget instanceof Control && !((Control) event.widget).isFocusControl()) {
deactivate();
return;
}
if (!fActive) {
if (event.stateMask != SWT.CTRL)
return;
// Ctrl was already pressed
fActive= true;
}
ISourceViewer viewer= getSourceViewer();
if (viewer == null) {
deactivate();
return;
}
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed()) {
deactivate();
return;
}
if ((event.stateMask & SWT.BUTTON1) != 0 && text.getSelectionCount() != 0) {
deactivate();
return;
}
IRegion region= getCurrentTextRegion(viewer);
if (region == null || 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) {
}
/*
* @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent)
*/
public void documentChanged(DocumentEvent event) {
deactivate();
}
/*
* @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
*/
public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) {
if (oldInput == null)
return;
deactivate();
oldInput.removeDocumentListener(this);
}
/*
* @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
*/
public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
if (newInput == null)
return;
newInput.addDocumentListener(this);
}
/*
* @see PaintListener#paintControl(PaintEvent)
*/
public void paintControl(PaintEvent event) {
if (fActiveRegion == null)
return;
ISourceViewer viewer= getSourceViewer();
if (viewer == null)
return;
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() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null) {
fTextOperationAction.run();
return;
}
if (! (sourceViewer instanceof ITextViewerExtension2)) {
fTextOperationAction.run();
return;
}
ITextViewerExtension2 textViewerExtension2= (ITextViewerExtension2) sourceViewer;
// does a text hover exist?
ITextHover textHover= textViewerExtension2.getCurrentTextHover();
if (textHover == null) {
fTextOperationAction.run();
return;
}
Point hoverEventLocation= textViewerExtension2.getHoverEventLocation();
int offset= computeOffsetAtLocation(sourceViewer, hoverEventLocation.x, hoverEventLocation.y);
if (offset == -1) {
fTextOperationAction.run();
return;
}
try {
// get the text hover content
IDocument document= sourceViewer.getDocument();
String contentType= document.getContentType(offset);
final IRegion hoverRegion= textHover.getHoverRegion(sourceViewer, offset);
if (hoverRegion == null)
return;
final String hoverInfo= textHover.getHoverInfo(sourceViewer, hoverRegion);
// with information provider
IInformationProvider informationProvider= new IInformationProvider() {
/*
* @see org.eclipse.jface.text.information.IInformationProvider#getSubject(org.eclipse.jface.text.ITextViewer, int)
*/
public IRegion getSubject(ITextViewer textViewer, int offset) {
return hoverRegion;
}
/*
* @see org.eclipse.jface.text.information.IInformationProvider#getInformation(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion)
*/
public String getInformation(ITextViewer textViewer, IRegion subject) {
return hoverInfo;
}
};
fInformationPresenter.setOffset(offset);
fInformationPresenter.setInformationProvider(informationProvider, contentType);
fInformationPresenter.showInformation();
} catch (BadLocationException e) {
}
}
// modified version from TextViewer
private int computeOffsetAtLocation(ITextViewer textViewer, int x, int y) {
StyledText styledText= textViewer.getTextWidget();
IDocument document= textViewer.getDocument();
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;
}
}
}
/** Preference key for showing the line number ruler */
private final static String LINE_NUMBER_RULER= PreferenceConstants.EDITOR_LINE_NUMBER_RULER;
/** Preference key for the foreground color of the line numbers */
private final static String LINE_NUMBER_COLOR= PreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR;
/** Preference key for the link color */
private final static String LINK_COLOR= PreferenceConstants.EDITOR_LINK_COLOR;
// /** Preference key for the default hover */
// private static final String DEFAULT_HOVER= PreferenceConstants.EDITOR_DEFAULT_HOVER;
// /** Preference key for hover while no modifier is pressed */
// private static final String NONE_HOVER= PreferenceConstants.EDITOR_NONE_HOVER;
// /** Preference key for hover while Ctrl modifier is pressed */
// private static final String CTRL_HOVER= PreferenceConstants.EDITOR_CTRL_HOVER;
// /** Preference key for hover while Shift modifier is pressed */
// private static final String SHIFT_HOVER= PreferenceConstants.EDITOR_SHIFT_HOVER;
// /** Preference key for hover while Ctrl+Alt modifiers are pressed */
// private static final String CTRL_ALT_HOVER= PreferenceConstants.EDITOR_CTRL_ALT_HOVER;
// /** Preference key for hover while Ctrl+Alt+Shift modifiers are pressed */
// private static final String CTRL_ALT_SHIFT_HOVER= PreferenceConstants.EDITOR_CTRL_ALT_SHIFT_HOVER;
// /** Preference key for hover while Ctrl+Shift modifiers are pressed */
// private static final String CTRL_SHIFT_HOVER= PreferenceConstants.EDITOR_CTRL_SHIFT_HOVER;
// /** Preference key for hover while Alt+Shift modifiers are pressed */
// private static final String ALT_SHIFT_HOVER= PreferenceConstants.EDITOR_ALT_SHIFT_HOVER;
// /** Id indicating no hover is configured */
// private static final String NO_HOVER_CONFIGURED_ID= PreferenceConstants.EDITOR_NO_HOVER_CONFIGURED_ID;
// /** Hover id indicating the default hover */
// private static final String DEFAULT_HOVER_CONFIGURED_ID= PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID;
/** The outline page */
protected JavaOutlinePage fOutlinePage;
/** Outliner context menu Id */
protected String fOutlinerContextMenuId;
/** The selection changed listener */
protected ISelectionChangedListener fSelectionChangedListener= new SelectionChangedListener();
/** The outline page selection updater */
private OutlinePageSelectionUpdater fUpdater;
/** Indicates whether this editor should react on outline page selection changes */
private int fIgnoreOutlinePageSelection;
/** The line number ruler column */
private LineNumberRulerColumn fLineNumberRulerColumn;
/** This editor's encoding support */
private DefaultEncodingSupport fEncodingSupport;
/** The mouse listener */
private MouseClickListener fMouseListener;
/** The information presenter. */
private InformationPresenter fInformationPresenter;
protected CompositeActionGroup fActionGroups;
private CompositeActionGroup fContextMenuGroup;
/**
* Returns the most narrow java element including the given offset
*
* @param offset the offset inside of the requested element
*/
abstract protected IJavaElement getElementAt(int offset);
/**
* Returns the java element of this editor's input corresponding to the given IJavaElement
*/
abstract protected IJavaElement getCorrespondingElement(IJavaElement element);
/**
* Sets the input of the editor's outline page.
*/
abstract protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input);
/**
* Default constructor.
*/
public JavaEditor() {
super();
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
setSourceViewerConfiguration(new JavaSourceViewerConfiguration(textTools, this));
setRangeIndicator(new DefaultRangeIndicator());
setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE))
fUpdater= new OutlinePageSelectionUpdater();
}
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected final ISourceViewer createSourceViewer(Composite parent, IVerticalRuler ruler, int styles) {
ISourceViewer viewer= createJavaSourceViewer(parent, ruler, styles);
StyledText text= viewer.getTextWidget();
text.addBidiSegmentListener(new BidiSegmentListener() {
public void lineGetSegments(BidiSegmentEvent event) {
event.segments= getBidiLineSegments(event.lineOffset, event.lineText);
}
});
JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR);
return viewer;
}
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler ruler, int styles) {
return super.createSourceViewer(parent, ruler, styles);
}
/*
* @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent)
*/
protected boolean affectsTextPresentation(PropertyChangeEvent event) {
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
return textTools.affectsBehavior(event);
}
/**
* Sets the outliner's context menu ID.
*/
protected void setOutlinerContextMenuId(String menuId) {
fOutlinerContextMenuId= menuId;
}
/**
* Returns the standard action group of this editor.
*/
protected ActionGroup getActionGroup() {
return fActionGroups;
}
/*
* @see AbstractTextEditor#editorContextMenuAboutToShow
*/
public void editorContextMenuAboutToShow(IMenuManager menu) {
super.editorContextMenuAboutToShow(menu);
menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, new Separator(IContextMenuConstants.GROUP_OPEN));
menu.insertAfter(IContextMenuConstants.GROUP_OPEN, new GroupMarker(IContextMenuConstants.GROUP_SHOW));
ActionContext context= new ActionContext(getSelectionProvider().getSelection());
fContextMenuGroup.setContext(context);
fContextMenuGroup.fillContextMenu(menu);
fContextMenuGroup.setContext(null);
}
/**
* Creates the outline page used with this editor.
*/
protected JavaOutlinePage createOutlinePage() {
JavaOutlinePage page= new JavaOutlinePage(fOutlinerContextMenuId, this);
page.addSelectionChangedListener(fSelectionChangedListener);
setOutlinePageInput(page, getEditorInput());
return page;
}
/**
* Informs the editor that its outliner has been closed.
*/
public void outlinePageClosed() {
if (fOutlinePage != null) {
fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener);
fOutlinePage= null;
resetHighlightRange();
}
}
/**
* Synchronizes the outliner selection with the actual cursor
* position in the editor.
*/
public void synchronizeOutlinePageSelection() {
if (isEditingScriptRunning())
return;
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null || fOutlinePage == null)
return;
StyledText styledText= sourceViewer.getTextWidget();
if (styledText == null)
return;
int 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);
if (element instanceof ISourceReference) {
fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener);
fOutlinePage.select((ISourceReference) element);
fOutlinePage.addSelectionChangedListener(fSelectionChangedListener);
}
}
/*
* Get the desktop's StatusLineManager
*/
protected IStatusLineManager getStatusLineManager() {
IEditorActionBarContributor contributor= getEditorSite().getActionBarContributor();
if (contributor instanceof EditorActionBarContributor) {
return ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager();
}
return null;
}
/*
* @see AbstractTextEditor#getAdapter(Class)
*/
public Object getAdapter(Class required) {
if (IContentOutlinePage.class.equals(required)) {
if (fOutlinePage == null)
fOutlinePage= createOutlinePage();
return fOutlinePage;
}
if (IEncodingSupport.class.equals(required))
return fEncodingSupport;
return super.getAdapter(required);
}
protected void setSelection(ISourceReference reference, boolean moveCursor) {
ISelection selection= getSelectionProvider().getSelection();
if (selection instanceof TextSelection) {
TextSelection textSelection= (TextSelection) selection;
if (textSelection.getOffset() != 0 || textSelection.getLength() != 0)
markInNavigationHistory();
}
if (reference != null) {
StyledText textWidget= null;
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null)
textWidget= sourceViewer.getTextWidget();
if (textWidget == null)
return;
try {
ISourceRange range= reference.getSourceRange();
if (range == null)
return;
int offset= range.getOffset();
int length= range.getLength();
if (offset < 0 || length < 0)
return;
textWidget.setRedraw(false);
setHighlightRange(offset, length, moveCursor);
if (!moveCursor)
return;
offset= -1;
length= -1;
if (reference instanceof IMember) {
range= ((IMember) reference).getNameRange();
if (range != null) {
offset= range.getOffset();
length= range.getLength();
}
} else if (reference instanceof IImportDeclaration) {
String name= ((IImportDeclaration) reference).getElementName();
if (name != null && name.length() > 0) {
String content= reference.getSource();
offset= range.getOffset() + content.indexOf(name);
length= name.length();
}
} else if (reference instanceof IPackageDeclaration) {
String name= ((IPackageDeclaration) reference).getElementName();
if (name != null && name.length() > 0) {
String content= reference.getSource();
offset= range.getOffset() + content.indexOf(name);
length= name.length();
}
}
if (offset > -1 && length > 0) {
sourceViewer.revealRange(offset, length);
sourceViewer.setSelectedRange(offset, length);
}
} catch (JavaModelException x) {
} catch (IllegalArgumentException x) {
} finally {
if (textWidget != null)
textWidget.setRedraw(true);
}
} else if (moveCursor) {
resetHighlightRange();
}
markInNavigationHistory();
}
public void setSelection(IJavaElement element) {
if (element == null || element instanceof ICompilationUnit || element instanceof IClassFile) {
/*
* If the element is an ICompilationUnit this unit is either the input
* of this editor or not being displayed. In both cases, nothing should
* happened. (http://dev.eclipse.org/bugs/show_bug.cgi?id=5128)
*/
return;
}
IJavaElement corresponding= getCorrespondingElement(element);
if (corresponding instanceof ISourceReference) {
ISourceReference reference= (ISourceReference) corresponding;
// set hightlight range
setSelection(reference, true);
// set outliner selection
if (fOutlinePage != null) {
fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener);
fOutlinePage.select(reference);
fOutlinePage.addSelectionChangedListener(fSelectionChangedListener);
}
}
}
public synchronized void editingScriptStarted() {
++ fIgnoreOutlinePageSelection;
}
public synchronized void editingScriptEnded() {
-- fIgnoreOutlinePageSelection;
}
public synchronized boolean isEditingScriptRunning() {
return (fIgnoreOutlinePageSelection > 0);
}
protected void doSelectionChanged(SelectionChangedEvent event) {
ISourceReference reference= null;
ISelection selection= event.getSelection();
Iterator iter= ((IStructuredSelection) selection).iterator();
while (iter.hasNext()) {
Object o= iter.next();
if (o instanceof ISourceReference) {
reference= (ISourceReference) o;
break;
}
}
if (!isActivePart() && JavaPlugin.getActivePage() != null)
JavaPlugin.getActivePage().bringToTop(this);
try {
editingScriptStarted();
setSelection(reference, !isActivePart());
} finally {
editingScriptEnded();
}
}
/*
* @see AbstractTextEditor#adjustHighlightRange(int, int)
*/
protected void adjustHighlightRange(int offset, int length) {
try {
IJavaElement element= getElementAt(offset);
while (element instanceof ISourceReference) {
ISourceRange range= ((ISourceReference) element).getSourceRange();
if (offset < range.getOffset() + range.getLength() && range.getOffset() < offset + length) {
setHighlightRange(range.getOffset(), range.getLength(), true);
if (fOutlinePage != null) {
fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener);
fOutlinePage.select((ISourceReference) element);
fOutlinePage.addSelectionChangedListener(fSelectionChangedListener);
}
return;
}
element= element.getParent();
}
} catch (JavaModelException x) {
JavaPlugin.log(x.getStatus());
}
resetHighlightRange();
}
protected boolean isActivePart() {
IWorkbenchWindow window= getSite().getWorkbenchWindow();
IPartService service= window.getPartService();
IWorkbenchPart part= service.getActivePart();
return part != null && part.equals(this);
}
/*
* @see StatusTextEditor#getStatusHeader(IStatus)
*/
protected String getStatusHeader(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusHeader(status);
if (message != null)
return message;
}
return super.getStatusHeader(status);
}
/*
* @see StatusTextEditor#getStatusBanner(IStatus)
*/
protected String getStatusBanner(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusBanner(status);
if (message != null)
return message;
}
return super.getStatusBanner(status);
}
/*
* @see StatusTextEditor#getStatusMessage(IStatus)
*/
protected String getStatusMessage(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusMessage(status);
if (message != null)
return message;
}
return super.getStatusMessage(status);
}
/*
* @see AbstractTextEditor#doSetInput
*/
protected void doSetInput(IEditorInput input) throws CoreException {
super.doSetInput(input);
if (fEncodingSupport != null)
fEncodingSupport.reset();
setOutlinePageInput(fOutlinePage, input);
}
/*
* @see IWorkbenchPart#dispose()
*/
public void dispose() {
if (fMouseListener != null) {
fMouseListener.uninstall();
fMouseListener= null;
}
if (fEncodingSupport != null) {
fEncodingSupport.dispose();
fEncodingSupport= null;
}
super.dispose();
}
protected void createActions() {
super.createActions();
ResourceAction action= new AddTaskAction(JavaEditorMessages.getResourceBundle(), "AddTask.", this); //$NON-NLS-1$
action.setHelpContextId(IAbstractTextEditorHelpContextIds.ADD_TASK_ACTION);
action.setActionDefinitionId(ITextEditorActionDefinitionIds.ADD_TASK);
setAction(ITextEditorActionConstants.ADD_TASK, action);
ActionGroup oeg, ovg, sg, jsg;
fActionGroups= new CompositeActionGroup(new ActionGroup[] {
oeg= new OpenEditorActionGroup(this),
ovg= new OpenViewActionGroup(this),
sg= new ShowActionGroup(this),
jsg= new JavaSearchActionGroup(this)
});
fContextMenuGroup= new CompositeActionGroup(new ActionGroup[] {oeg, ovg, sg, jsg});
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", this, ISourceViewer.INFORMATION, true); //$NON-NLS-1$
action= new InformationDispatchAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", (TextOperationAction) action); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_JAVADOC);
setAction("ShowJavaDoc", action); //$NON-NLS-1$
fEncodingSupport= new DefaultEncodingSupport();
fEncodingSupport.initialize(this);
if (fMouseListener == null) {
fMouseListener= new MouseClickListener();
fMouseListener.install();
}
}
private boolean isTextSelectionEmpty() {
ISelection selection= getSelectionProvider().getSelection();
if (!(selection instanceof ITextSelection))
return true;
return ((ITextSelection)selection).getLength() == 0;
}
public void updatedTitleImage(Image image) {
setTitleImage(image);
}
/*
* @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
*/
protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
try {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
String property= event.getProperty();
if (PreferenceConstants.EDITOR_TAB_WIDTH.equals(property)) {
Object value= event.getNewValue();
if (value instanceof Integer) {
sourceViewer.getTextWidget().setTabs(((Integer) value).intValue());
} else if (value instanceof String) {
sourceViewer.getTextWidget().setTabs(Integer.parseInt((String) value));
}
return;
}
if (LINE_NUMBER_RULER.equals(property)) {
if (isLineNumberRulerVisible())
showLineNumberRuler();
else
hideLineNumberRuler();
return;
}
if (fLineNumberRulerColumn != null &&
(LINE_NUMBER_COLOR.equals(property) ||
PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT.equals(property) ||
PREFERENCE_COLOR_BACKGROUND.equals(property))) {
initializeLineNumberRulerColumn(fLineNumberRulerColumn);
}
if (isJavaEditorHoverProperty(property)) {
updateHoverBehavior();
}
} finally {
super.handlePreferenceStoreChanged(event);
}
}
private boolean isJavaEditorHoverProperty(String property) {
return PreferenceConstants.EDITOR_DEFAULT_HOVER.equals(property)
|| PreferenceConstants.EDITOR_NONE_HOVER.equals(property)
|| PreferenceConstants.EDITOR_CTRL_HOVER.equals(property)
|| PreferenceConstants.EDITOR_SHIFT_HOVER.equals(property)
|| PreferenceConstants.EDITOR_CTRL_ALT_HOVER.equals(property)
|| PreferenceConstants.EDITOR_CTRL_SHIFT_HOVER.equals(property)
|| PreferenceConstants.EDITOR_CTRL_ALT_SHIFT_HOVER.equals(property)
|| PreferenceConstants.EDITOR_ALT_SHIFT_HOVER.equals(property);
}
/**
* Shows the line number ruler column.
*/
private void showLineNumberRuler() {
IVerticalRuler v= getVerticalRuler();
if (v instanceof CompositeRuler) {
CompositeRuler c= (CompositeRuler) v;
c.addDecorator(1, createLineNumberRulerColumn());
}
}
/**
* Hides the line number ruler column.
*/
private void hideLineNumberRuler() {
IVerticalRuler v= getVerticalRuler();
if (v instanceof CompositeRuler) {
CompositeRuler c= (CompositeRuler) v;
c.removeDecorator(1);
}
}
/**
* Return whether the line number ruler column should be
* visible according to the preference store settings.
* @return <code>true</code> if the line numbers should be visible
*/
private boolean isLineNumberRulerVisible() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(LINE_NUMBER_RULER);
}
/**
* Returns a segmentation of the line of the given document appropriate for bidi rendering.
* The default implementation returns only the string literals of a java code line as segments.
*
* @param document the document
* @param lineOffset the offset of the line
* @return the line's bidi segmentation
* @throws BadLocationException in case lineOffset is not valid in document
*/
public static int[] getBidiLineSegments(IDocument document, int lineOffset) throws BadLocationException {
IRegion line= document.getLineInformationOfOffset(lineOffset);
ITypedRegion[] linePartitioning= document.computePartitioning(lineOffset, line.getLength());
List segmentation= new ArrayList();
for (int i= 0; i < linePartitioning.length; i++) {
if (JavaPartitionScanner.JAVA_STRING.equals(linePartitioning[i].getType()))
segmentation.add(linePartitioning[i]);
}
if (segmentation.size() == 0)
return null;
int size= segmentation.size();
int[] segments= new int[size * 2 + 1];
int j= 0;
for (int i= 0; i < size; i++) {
ITypedRegion segment= (ITypedRegion) segmentation.get(i);
if (i == 0)
segments[j++]= 0;
int offset= segment.getOffset() - lineOffset;
if (offset > segments[j - 1])
segments[j++]= offset;
if (offset + segment.getLength() >= line.getLength())
break;
segments[j++]= offset + segment.getLength();
}
if (j < segments.length) {
int[] result= new int[j];
System.arraycopy(segments, 0, result, 0, j);
segments= result;
}
return segments;
}
/**
* Returns a segmentation of the given line appropriate for bidi rendering. The default
* implementation returns only the string literals of a java code line as segments.
*
* @param lineOffset the offset of the line
* @param line the content of the line
* @return the line's bidi segmentation
*/
protected int[] getBidiLineSegments(int lineOffset, String line) {
IDocumentProvider provider= getDocumentProvider();
if (provider != null && line != null && line.length() > 0) {
IDocument document= provider.getDocument(getEditorInput());
if (document != null)
try {
return getBidiLineSegments(document, lineOffset);
} catch (BadLocationException x) {
// ignore
}
}
return null;
}
/*
* @see AbstractTextEditor#handleCursorPositionChanged()
*/
protected void handleCursorPositionChanged() {
super.handleCursorPositionChanged();
if (!isEditingScriptRunning() && fUpdater != null)
fUpdater.post();
}
/**
* Initializes the given line number ruler column from the preference store.
* @param rulerColumn the ruler column to be initialized
*/
protected void initializeLineNumberRulerColumn(LineNumberRulerColumn rulerColumn) {
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
IColorManager manager= textTools.getColorManager();
IPreferenceStore store= getPreferenceStore();
if (store != null) {
RGB rgb= null;
// foreground color
if (store.contains(LINE_NUMBER_COLOR)) {
if (store.isDefault(LINE_NUMBER_COLOR))
rgb= PreferenceConverter.getDefaultColor(store, LINE_NUMBER_COLOR);
else
rgb= PreferenceConverter.getColor(store, LINE_NUMBER_COLOR);
}
rulerColumn.setForeground(manager.getColor(rgb));
rgb= null;
// background color
if (!store.getBoolean(PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)) {
if (store.contains(PREFERENCE_COLOR_BACKGROUND)) {
if (store.isDefault(PREFERENCE_COLOR_BACKGROUND))
rgb= PreferenceConverter.getDefaultColor(store, PREFERENCE_COLOR_BACKGROUND);
else
rgb= PreferenceConverter.getColor(store, PREFERENCE_COLOR_BACKGROUND);
}
}
rulerColumn.setBackground(manager.getColor(rgb));
}
}
/**
* Creates a new line number ruler column that is appropriately initialized.
*/
protected IVerticalRulerColumn createLineNumberRulerColumn() {
fLineNumberRulerColumn= new LineNumberRulerColumn();
initializeLineNumberRulerColumn(fLineNumberRulerColumn);
return fLineNumberRulerColumn;
}
/*
* @see AbstractTextEditor#createVerticalRuler()
*/
protected IVerticalRuler createVerticalRuler() {
CompositeRuler ruler= new CompositeRuler();
ruler.addDecorator(0, new AnnotationRulerColumn(VERTICAL_RULER_WIDTH));
if (isLineNumberRulerVisible())
ruler.addDecorator(1, createLineNumberRulerColumn());
return ruler;
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#updatePropertyDependentActions()
*/
protected void updatePropertyDependentActions() {
super.updatePropertyDependentActions();
if (fEncodingSupport != null)
fEncodingSupport.reset();
}
/*
* Update the hovering behavior depending on the preferences.
*/
private void updateHoverBehavior() {
SourceViewerConfiguration configuration= getSourceViewerConfiguration();
String[] types= configuration.getConfiguredContentTypes(getSourceViewer());
for (int i= 0; i < types.length; i++) {
String t= types[i];
int[] stateMasks= configuration.getConfiguredTextHoverStateMasks(getSourceViewer(), t);
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer instanceof ITextViewerExtension2) {
if (stateMasks != null) {
for (int j= 0; j < stateMasks.length; j++) {
int stateMask= stateMasks[j];
ITextHover textHover= configuration.getTextHover(sourceViewer, t, stateMask);
((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, stateMask);
}
} else {
ITextHover textHover= configuration.getTextHover(sourceViewer, t);
((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK);
}
} else
sourceViewer.setTextHover(configuration.getTextHover(sourceViewer, t), t);
}
}
/*
* @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
*/
public Object getViewPartInput() {
return getEditorInput().getAdapter(IJavaElement.class);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetSelection(ISelection)
*/
protected void doSetSelection(ISelection selection) {
super.doSetSelection(selection);
synchronizeOutlinePageSelection();
}
/*
* @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.
* widgets.Composite)
*/
public void createPartControl(Composite parent) {
super.createPartControl(parent);
IInformationControlCreator informationControlCreator= new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell parent) {
boolean cutDown= false;
int style= cutDown ? SWT.NONE : (SWT.V_SCROLL | SWT.H_SCROLL);
return new DefaultInformationControl(parent, SWT.RESIZE, style, new HTMLTextPresenter(cutDown));
}
};
fInformationPresenter= new InformationPresenter(informationControlCreator);
fInformationPresenter.setSizeConstraints(60, 10, true, true);
fInformationPresenter.install(getSourceViewer());
}
}
|
27,512 |
Bug 27512 Auto-indent levels broken for cut and paste
|
On M3: 1) Double-click on the opening brace '{' of a method. 2) Cut the method body. 3) Paste the method body. Problem: indentation is mangled incorrectly.
|
resolved fixed
|
213899a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-06T13:52:35Z | 2002-12-02T17:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaAutoIndentStrategy.java
|
package org.eclipse.jdt.internal.ui.text.java;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DefaultAutoIndentStrategy;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.DocumentCommand;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentPartitioner;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.corext.Assert;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.JavaPartitionScanner;
/**
* Auto indent strategy sensitive to brackets.
*/
public class JavaAutoIndentStrategy extends DefaultAutoIndentStrategy {
public JavaAutoIndentStrategy() {
}
// evaluate the line with the opening bracket that matches the closing bracket on the given line
protected int findMatchingOpenBracket(IDocument d, int line, int end, int closingBracketIncrease) throws BadLocationException {
int start= d.getLineOffset(line);
int brackcount= getBracketCount(d, start, end, false) - closingBracketIncrease;
// sum up the brackets counts of each line (closing brackets count negative,
// opening positive) until we find a line the brings the count to zero
while (brackcount < 0) {
line--;
if (line < 0) {
return -1;
}
start= d.getLineOffset(line);
end= start + d.getLineLength(line) - 1;
brackcount += getBracketCount(d, start, end, false);
}
return line;
}
private int getBracketCount(IDocument d, int start, int end, boolean ignoreCloseBrackets) throws BadLocationException {
int bracketcount= 0;
while (start < end) {
char curr= d.getChar(start);
start++;
switch (curr) {
case '/' :
if (start < end) {
char next= d.getChar(start);
if (next == '*') {
// a comment starts, advance to the comment end
start= getCommentEnd(d, start + 1, end);
} else if (next == '/') {
// '//'-comment: nothing to do anymore on this line
start= end;
}
}
break;
case '*' :
if (start < end) {
char next= d.getChar(start);
if (next == '/') {
// we have been in a comment: forget what we read before
bracketcount= 0;
start++;
}
}
break;
case '{' :
bracketcount++;
ignoreCloseBrackets= false;
break;
case '}' :
if (!ignoreCloseBrackets) {
bracketcount--;
}
break;
case '"' :
case '\'' :
start= getStringEnd(d, start, end, curr);
break;
default :
}
}
return bracketcount;
}
// ----------- bracket counting ------------------------------------------------------
private int getCommentEnd(IDocument d, int pos, int end) throws BadLocationException {
while (pos < end) {
char curr= d.getChar(pos);
pos++;
if (curr == '*') {
if (pos < end && d.getChar(pos) == '/') {
return pos + 1;
}
}
}
return end;
}
protected String getIndentOfLine(IDocument d, int line) throws BadLocationException {
if (line > -1) {
int start= d.getLineOffset(line);
int end= start + d.getLineLength(line) - 1;
int whiteend= findEndOfWhiteSpace(d, start, end);
return d.get(start, whiteend - start);
} else {
return ""; //$NON-NLS-1$
}
}
private int getStringEnd(IDocument d, int pos, int end, char ch) throws BadLocationException {
while (pos < end) {
char curr= d.getChar(pos);
pos++;
if (curr == '\\') {
// ignore escaped characters
pos++;
} else if (curr == ch) {
return pos;
}
}
return end;
}
protected void smartInsertAfterBracket(IDocument d, DocumentCommand c) {
if (c.offset == -1 || d.getLength() == 0)
return;
try {
int p= (c.offset == d.getLength() ? c.offset - 1 : c.offset);
int line= d.getLineOfOffset(p);
int start= d.getLineOffset(line);
int whiteend= findEndOfWhiteSpace(d, start, c.offset);
// shift only when line does not contain any text up to the closing bracket
if (whiteend == c.offset) {
// evaluate the line with the opening bracket that matches out closing bracket
int indLine= findMatchingOpenBracket(d, line, c.offset, 1);
if (indLine != -1 && indLine != line) {
// take the indent of the found line
StringBuffer replaceText= new StringBuffer(getIndentOfLine(d, indLine));
// add the rest of the current line including the just added close bracket
replaceText.append(d.get(whiteend, c.offset - whiteend));
replaceText.append(c.text);
// modify document command
c.length += c.offset - start;
c.offset= start;
c.text= replaceText.toString();
}
}
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
}
protected void smartIndentAfterNewLine(IDocument d, DocumentCommand c) {
int docLength= d.getLength();
if (c.offset == -1 || docLength == 0)
return;
try {
int p= (c.offset == docLength ? c.offset - 1 : c.offset);
int line= d.getLineOfOffset(p);
StringBuffer buf= new StringBuffer(c.text);
if (c.offset < docLength && d.getChar(c.offset) == '}') {
int indLine= findMatchingOpenBracket(d, line, c.offset, 0);
if (indLine == -1) {
indLine= line;
}
buf.append(getIndentOfLine(d, indLine));
} else {
int start= d.getLineOffset(line);
// if line just ended a javadoc comment, take the indent from the comment's begin line
IDocumentPartitioner partitioner= d.getDocumentPartitioner();
if (partitioner != null) {
ITypedRegion region= partitioner.getPartition(start);
if (JavaPartitionScanner.JAVA_DOC.equals(region.getType()))
start= d.getLineInformationOfOffset(region.getOffset()).getOffset();
}
int whiteend= findEndOfWhiteSpace(d, start, c.offset);
buf.append(d.get(start, whiteend - start));
if (getBracketCount(d, start, c.offset, true) > 0) {
buf.append(getOneIndentLevel());
}
}
c.text= buf.toString();
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
}
private static String getLineDelimiter(IDocument document) {
try {
if (document.getNumberOfLines() > 1)
return document.getLineDelimiter(0);
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
return System.getProperty("line.separator"); //$NON-NLS-1$
}
protected void smartPaste(IDocument document, DocumentCommand command) {
String lineDelimiter= getLineDelimiter(document);
try {
String pastedText= command.text;
Assert.isNotNull(pastedText);
Assert.isTrue(pastedText.length() > 1);
// #27512
// int selectionEnd= command.offset + command.length;
// IRegion region= document.getLineInformationOfOffset(selectionEnd);
// String selected= document.get(region.getOffset(), selectionEnd - region.getOffset());
// String notSelected= document.get(selectionEnd, region.getOffset() + region.getLength() - selectionEnd);
// if (selected.trim().length() == 0 && notSelected.trim().length() != 0) {
// pastedText += notSelected;
// command.length += notSelected.length();
// }
String strippedParagraph= stripIndent(pastedText, lineDelimiter);
// check selection
int offset= command.offset;
int line= document.getLineOfOffset(offset);
int lineOffset= document.getLineOffset(line);
// format
String prefix= document.get(lineOffset, offset - lineOffset);
String blockIndent= getBlockIndent(document, command);
String insideBlockIndent= blockIndent == null ? "" : blockIndent + createIndent(1); //$NON-NLS-1$ // add one indent level
String previousIndent= getIndent(document, command);
String indent= calculateDisplayedWidth(insideBlockIndent) < calculateDisplayedWidth(previousIndent)
? insideBlockIndent
: previousIndent;
boolean formatFirstLine= prefix.trim().length() == 0;
String formattedParagraph= format(strippedParagraph, indent, lineDelimiter, formatFirstLine);
// paste
if (formatFirstLine) {
int end= command.offset + command.length;
command.offset= lineOffset;
command.length= end - command.offset;
}
command.text= formattedParagraph;
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
}
/**
* Returns the displayed width of a string, taking in account the displayed tab width.
* The result can be compared against the print margin.
*/
private static int calculateDisplayedWidth(String string) {
final int tabWidth= JavaPlugin.getDefault().getPreferenceStore().getInt(PreferenceConstants.EDITOR_TAB_WIDTH);
int column= 0;
for (int i= 0; i < string.length(); i++)
if ('\t' == string.charAt(i))
column += tabWidth - (column % tabWidth);
else
column++;
return column;
}
private 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 String getIndent(IDocument document, DocumentCommand command) {
StringBuffer buf= new StringBuffer();
int docLength= document.getLength();
if (command.offset == -1 || docLength == 0)
return buf.toString();
try {
int p= (command.offset == docLength ? command.offset - 1 : command.offset);
int line= document.getLineOfOffset(p);
IRegion region= document.getLineInformation(line);
String string= document.get(region.getOffset(), command.offset - region.getOffset());
if (line != 0 && string.trim().length() == 0)
--line;
while (line != 0 && isLineEmpty(document, line))
--line;
int start= document.getLineOffset(line);
// if line is at end of a javadoc comment, take the indent from the comment's begin line
IDocumentPartitioner partitioner= document.getDocumentPartitioner();
if (partitioner != null) {
ITypedRegion typedRegion= partitioner.getPartition(start);
if (JavaPartitionScanner.JAVA_DOC.equals(typedRegion.getType()))
start= document.getLineInformationOfOffset(typedRegion.getOffset()).getOffset();
}
int whiteend= findEndOfWhiteSpace(document, start, command.offset);
buf.append(document.get(start, whiteend - start));
if (getBracketCount(document, start, command.offset, true) > 0) {
buf.append(getOneIndentLevel());
}
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
return buf.toString();
}
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 && indLine != line)
// take the indent of the found line
return getIndentOfLine(d, indLine);
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
return null;
}
private static final class LineIterator implements Iterator {
/** The document to iterator over. */
private final IDocument fDocument;
/** The line index. */
private int fLineIndex;
/**
* Creates a line iterator.
*/
public LineIterator(String string) {
fDocument= new Document(string);
}
/*
* @see java.util.Iterator#hasNext()
*/
public boolean hasNext() {
return fLineIndex != fDocument.getNumberOfLines();
}
/*
* @see java.util.Iterator#next()
*/
public Object next() {
try {
IRegion region= fDocument.getLineInformation(fLineIndex++);
return fDocument.get(region.getOffset(), region.getLength());
} catch (BadLocationException e) {
JavaPlugin.log(e);
throw new NoSuchElementException();
}
}
/*
* @see java.util.Iterator#remove()
*/
public void remove() {
throw new UnsupportedOperationException();
}
}
private static IPreferenceStore getPreferenceStore() {
return JavaPlugin.getDefault().getPreferenceStore();
}
private static String createIndent(int level) {
StringBuffer buffer= new StringBuffer();
if (useSpaces()) {
int tabWidth= getPreferenceStore().getInt(PreferenceConstants.EDITOR_TAB_WIDTH);
int width= level * tabWidth;
for (int i= 0; i != width; ++i)
buffer.append(' ');
} else {
buffer.append('\t');
}
return buffer.toString();
}
private static String createPrefix(int displayedWidth) {
StringBuffer buffer= new StringBuffer();
if (useSpaces()) {
for (int i= 0; i != displayedWidth; ++i)
buffer.append(' ');
} else {
int tabWidth= getPreferenceStore().getInt(PreferenceConstants.EDITOR_TAB_WIDTH);
int div= displayedWidth / tabWidth;
int mod= displayedWidth % tabWidth;
for (int i= 0; i != div; ++i)
buffer.append('\t');
for (int i= 0; i != mod; ++i)
buffer.append(' ');
}
return buffer.toString();
}
private String stripIndent(String paragraph, String lineDelimiter) {
final StringBuffer buffer= new StringBuffer();
// determine minimum indent width
int minIndentWidth= Integer.MAX_VALUE;
for (final Iterator iterator= new LineIterator(paragraph); iterator.hasNext();) {
String line= (String) iterator.next();
String trimmedLine= line.trim();
if (trimmedLine.length() == 0)
continue;
int index= line.indexOf(trimmedLine);
String indent= line.substring(0, index);
int width= calculateDisplayedWidth(indent);
minIndentWidth= Math.min(minIndentWidth, width);
}
// strip prefixes
for (final Iterator iterator= new LineIterator(paragraph); iterator.hasNext();) {
String line= (String) iterator.next();
String trimmedLine= line.trim();
if (trimmedLine.length() != 0) {
int index= line.indexOf(trimmedLine);
String indent= line.substring(0, index);
int width= calculateDisplayedWidth(indent);
int strippedWidth= width - minIndentWidth;
String prefix= createPrefix(strippedWidth);
buffer.append(prefix);
buffer.append(trimmedLine);
}
if (iterator.hasNext())
buffer.append(lineDelimiter);
}
return buffer.toString();
}
private String format(String paragraph, String indent, String lineDelimiter, boolean indentFirstLine) {
final StringBuffer buffer= new StringBuffer();
for (final Iterator iterator= new LineIterator(paragraph); iterator.hasNext();) {
String line= (String) iterator.next();
if (indentFirstLine && line.trim().length() != 0)
buffer.append(indent);
else
indentFirstLine= true;
buffer.append(line);
if (iterator.hasNext())
buffer.append(lineDelimiter);
}
return buffer.toString();
}
private String getOneIndentLevel() {
return String.valueOf('\t');
}
/**
* Returns whether the text ends with one of the given search strings.
*/
private boolean endsWithDelimiter(IDocument d, String txt) {
String[] delimiters= d.getLegalLineDelimiters();
for (int i= 0; i < delimiters.length; i++) {
if (txt.endsWith(delimiters[i]))
return true;
}
return false;
}
private boolean equalsDelimiter(IDocument d, String txt) {
String[] delimiters= d.getLegalLineDelimiters();
for (int i= 0; i < delimiters.length; i++) {
if (txt.equals(delimiters[i]))
return true;
}
return false;
}
private void smartIndentAfterBlockDelimiter(IDocument document, DocumentCommand command) {
if (command.text.charAt(0) == '}')
smartInsertAfterBracket(document, command);
}
/*
* @see org.eclipse.jface.text.IAutoIndentStrategy#customizeDocumentCommand(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.DocumentCommand)
*/
public void customizeDocumentCommand(IDocument d, DocumentCommand c) {
if (c.length == 0 && c.text != null && equalsDelimiter(d, c.text))
smartIndentAfterNewLine(d, c);
else if (c.text.length() == 1)
smartIndentAfterBlockDelimiter(d, c);
else if (c.text.length() > 1 && getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SMART_PASTE))
smartPaste(d, c);
}
private static boolean useSpaces() {
return JavaCore.SPACE.equals(JavaCore.getOptions().get(JavaCore.FORMATTER_TAB_CHAR));
}
}
|
27,849 |
Bug 27849 Organize Imports not working in Type with compilation errors
|
affected build: I20020412 "Orginze Imports" doesn't work with I have a bigger source file with some or more compilation errors _AND_ the cursor is position behind more or less compilation errors. If the cursor is in before the fist few compilation error, Organize Imports works as expected, if not the following exception is thrown. java.lang.ArrayIndexOutOfBoundsException: -1335 at org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation$TypeRe ferenceProcessor.findTypeRefs(OrganizeImportsOperation.java:452) at org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation$TypeRe ferenceProcessor.process(OrganizeImportsOperation.java:373) at org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation.run (OrganizeImportsOperation.java:529) at org.eclipse.jdt.internal.core.BatchOperation.executeOperation (BatchOperation.java:34) at org.eclipse.jdt.internal.core.JavaModelOperation.execute (JavaModelOperation.java:326) at org.eclipse.jdt.internal.core.JavaModelOperation.run (JavaModelOperation.java:626) at org.eclipse.core.internal.resources.Workspace.run (Workspace.java:1578) at org.eclipse.jdt.core.JavaCore.run(JavaCore.java:2383) at org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter.run (WorkbenchRunnableAdapter.java:32) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext$BusyRunnable.inter nalRun(BusyIndicatorRunnableContext.java:107) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext$BusyRunnable.run (BusyIndicatorRunnableContext.java:74) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:65) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext.run (BusyIndicatorRunnableContext.java:120) at org.eclipse.jdt.ui.actions.OrganizeImportsAction.runOnSingle (OrganizeImportsAction.java:363) at org.eclipse.jdt.ui.actions.OrganizeImportsAction.run (OrganizeImportsAction.java:245) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:193) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:169) at org.eclipse.jface.action.Action.runWithEvent(Action.java:769) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:411) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java:365) at org.eclipse.jface.action.ActionContributionItem.access$0 (ActionContributionItem.java:356) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java:48) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:825) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1405) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1388) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:841) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539)
|
resolved fixed
|
4d8e429
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-09T10:12:16Z | 2002-12-06T15:53:20Z |
org.eclipse.jdt.ui/core
| |
27,849 |
Bug 27849 Organize Imports not working in Type with compilation errors
|
affected build: I20020412 "Orginze Imports" doesn't work with I have a bigger source file with some or more compilation errors _AND_ the cursor is position behind more or less compilation errors. If the cursor is in before the fist few compilation error, Organize Imports works as expected, if not the following exception is thrown. java.lang.ArrayIndexOutOfBoundsException: -1335 at org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation$TypeRe ferenceProcessor.findTypeRefs(OrganizeImportsOperation.java:452) at org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation$TypeRe ferenceProcessor.process(OrganizeImportsOperation.java:373) at org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation.run (OrganizeImportsOperation.java:529) at org.eclipse.jdt.internal.core.BatchOperation.executeOperation (BatchOperation.java:34) at org.eclipse.jdt.internal.core.JavaModelOperation.execute (JavaModelOperation.java:326) at org.eclipse.jdt.internal.core.JavaModelOperation.run (JavaModelOperation.java:626) at org.eclipse.core.internal.resources.Workspace.run (Workspace.java:1578) at org.eclipse.jdt.core.JavaCore.run(JavaCore.java:2383) at org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter.run (WorkbenchRunnableAdapter.java:32) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext$BusyRunnable.inter nalRun(BusyIndicatorRunnableContext.java:107) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext$BusyRunnable.run (BusyIndicatorRunnableContext.java:74) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:65) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext.run (BusyIndicatorRunnableContext.java:120) at org.eclipse.jdt.ui.actions.OrganizeImportsAction.runOnSingle (OrganizeImportsAction.java:363) at org.eclipse.jdt.ui.actions.OrganizeImportsAction.run (OrganizeImportsAction.java:245) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:193) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:169) at org.eclipse.jface.action.Action.runWithEvent(Action.java:769) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:411) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java:365) at org.eclipse.jface.action.ActionContributionItem.access$0 (ActionContributionItem.java:356) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java:48) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:825) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1405) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1388) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:841) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539)
|
resolved fixed
|
4d8e429
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-09T10:12:16Z | 2002-12-06T15:53:20Z |
extension/org/eclipse/jdt/internal/corext/codemanipulation/OrganizeImportsOperation.java
| |
27,878 |
Bug 27878 infinite loop?
|
build N1206 on Win2K, IBM VM 1.3.1 in the big workspace I started up, opened the java perspective and navigated to org.eclipse.core.resources/src. When I clicked to expand the src folder my CPU went to 100% for alone time (forever?). Using ctrl-break I got the attached core dump which indicates that the RenameSupport.create() method appears to be called infinitely. Note that memory use does not seem to be increasing.
|
resolved fixed
|
b0c1f43
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-09T10:34:08Z | 2002-12-07T00:13:20Z |
org.eclipse.jdt.ui/ui
| |
27,878 |
Bug 27878 infinite loop?
|
build N1206 on Win2K, IBM VM 1.3.1 in the big workspace I started up, opened the java perspective and navigated to org.eclipse.core.resources/src. When I clicked to expand the src folder my CPU went to 100% for alone time (forever?). Using ctrl-break I got the attached core dump which indicates that the RenameSupport.create() method appears to be called infinitely. Note that memory use does not seem to be increasing.
|
resolved fixed
|
b0c1f43
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-09T10:34:08Z | 2002-12-07T00:13:20Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/RefactoringSupport.java
| |
27,878 |
Bug 27878 infinite loop?
|
build N1206 on Win2K, IBM VM 1.3.1 in the big workspace I started up, opened the java perspective and navigated to org.eclipse.core.resources/src. When I clicked to expand the src folder my CPU went to 100% for alone time (forever?). Using ctrl-break I got the attached core dump which indicates that the RenameSupport.create() method appears to be called infinitely. Note that memory use does not seem to be increasing.
|
resolved fixed
|
b0c1f43
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-09T10:34:08Z | 2002-12-07T00:13:20Z |
org.eclipse.jdt.ui/ui
| |
27,878 |
Bug 27878 infinite loop?
|
build N1206 on Win2K, IBM VM 1.3.1 in the big workspace I started up, opened the java perspective and navigated to org.eclipse.core.resources/src. When I clicked to expand the src folder my CPU went to 100% for alone time (forever?). Using ctrl-break I got the attached core dump which indicates that the RenameSupport.create() method appears to be called infinitely. Note that memory use does not seem to be increasing.
|
resolved fixed
|
b0c1f43
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-09T10:34:08Z | 2002-12-07T00:13:20Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/actions/RenameJavaElementAction.java
| |
27,878 |
Bug 27878 infinite loop?
|
build N1206 on Win2K, IBM VM 1.3.1 in the big workspace I started up, opened the java perspective and navigated to org.eclipse.core.resources/src. When I clicked to expand the src folder my CPU went to 100% for alone time (forever?). Using ctrl-break I got the attached core dump which indicates that the RenameSupport.create() method appears to be called infinitely. Note that memory use does not seem to be increasing.
|
resolved fixed
|
b0c1f43
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-09T10:34:08Z | 2002-12-07T00:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/reorg/IRefactoringRenameSupport.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.reorg;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jdt.core.JavaModelException;
/**
* Abstraction layer for renaming using refactoring.
*/
public interface IRefactoringRenameSupport {
/**
* whether the rename action should be enabled
*/
public boolean canRename(Object element) throws JavaModelException;
/**
* Do the rename
*/
public void rename(Shell parent, Object element) throws JavaModelException;
}
|
27,878 |
Bug 27878 infinite loop?
|
build N1206 on Win2K, IBM VM 1.3.1 in the big workspace I started up, opened the java perspective and navigated to org.eclipse.core.resources/src. When I clicked to expand the src folder my CPU went to 100% for alone time (forever?). Using ctrl-break I got the attached core dump which indicates that the RenameSupport.create() method appears to be called infinitely. Note that memory use does not seem to be increasing.
|
resolved fixed
|
b0c1f43
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-09T10:34:08Z | 2002-12-07T00:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/refactoring/RenameSupport.java
|
/*******************************************************************************
* Copyright (c) 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.ui.refactoring;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.core.runtime.CoreException;
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.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.internal.corext.refactoring.rename.RenameCompilationUnitRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.rename.RenameFieldRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.rename.RenameJavaProjectRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.rename.RenameMethodRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.rename.RenamePackageRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.rename.RenameTypeRefactoring;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringSupport;
import org.eclipse.jdt.internal.ui.reorg.IRefactoringRenameSupport;
/**
* Central access point to launch rename refactorings. Refactorings triggered
* through this class will perform the following steps:
* <ul>
* <li>check if the element can be renamed</li>
* <li>save all unsaved files</li>
* <li>open a corresponding refactoring dialog to gather user input</li>
* <li>execute or cancel the refactoring depending on user action</li>
* </ul>
*
* @since 2.1
*/
public class RenameSupport {
private IRefactoringRenameSupport fSupport;
private IJavaElement fElement;
/**
* Checks whether the rename support can actually rename the Java
* element passed to the create method.
* @return <code>true</code> if the element can be renamed; otherwise
* <code>false</code> is returned.
* @throws CoreException if an unexpected exception occurs while checking
* renaming.
*/
public boolean canRename() throws CoreException {
return fSupport.canRename(fElement);
}
/**
* Opens the refactoring dialog for this rename support.
*
* @param parent a shell used as a parent for the refactoring dialog.
* @throws CoreException if an unexpected exception occurs while opening the
* dialog.
*/
public void openDialog(Shell parent) throws CoreException {
fSupport.rename(parent, fElement);
}
/** Flag indication that no additional update is to be performed. */
public static final int NONE= 0;
/** Flag indicating that references are to be updated as well. */
public static final int UPDATE_REFERENCES= 1 << 0;
/** Flag indicating that Java doc comments are to be updated as well. */
public static final int UPDATE_JAVADOC_COMMENTS= 1 << 1;
/** Flag indicating that regular comments are to be updated as well. */
public static final int UPDATE_REGULAR_COMMENTS= 1 << 2;
/** Flag indicating that string literals are to be updated as well. */
public static final int UPDATE_STRING_LITERALS= 1 << 3;
/** Flag indicating that the getter method is to be updated as well. */
public static final int UPDATE_GETTER_METHOD= 1 << 4;
/** Flag indicating that the setter method is to be updated as well. */
public static final int UPDATE_SETTER_METHOD= 1 << 5;
private RenameSupport(IRefactoringRenameSupport support, IJavaElement element) {
fSupport= support;
fElement= element;
}
/**
* Creates a new rename support for the given <tt>IJavaProject</tt>.
*
* @param project the <tt>IJavaProject</tt> to be renamed.
* @param flags flags controlling additional parameters. Valid flags are
* <code>UPDATE_REFERENCES</code> or <code>NONE</code>.
* @return the <tt>RenameSupport</tt>.
* @throws CoreException if an unexpected error occured while creating
* the <tt>RenameSupport</tt>.
*/
public static RenameSupport create(IJavaProject project, int flags) throws CoreException {
RefactoringSupport.JavaProject support= new RefactoringSupport.JavaProject(project);
RenameJavaProjectRefactoring refactoring= support.getSpecificRefactoring();
refactoring.setUpdateReferences(updateReferences(flags));
return new RenameSupport(support, project);
}
/**
* Creates a new rename support for the given <tt>IPackageFragmentRoot</tt>.
*
* @param root the <tt>IPackageFragmentRoot</tt> to be renamed.
* @return the <tt>RenameSupport</tt>.
* @throws CoreException if an unexpected error occured while creating
* the <tt>RenameSupport</tt>.
*/
public static RenameSupport create(IPackageFragmentRoot root) throws CoreException {
RefactoringSupport.SourceFolder support= new RefactoringSupport.SourceFolder(root);
return new RenameSupport(support, root);
}
/**
* Creates a new rename support for the given <tt>IPackageFragment</tt>.
*
* @param fragment the <tt>IPackageFragment</tt> to be renamed.
* @param flags flags controlling additional parameters. Valid flags are
* <code>UPDATE_REFERENCES</code>, <code>UPDATE_JAVADOC_COMMENTS</code>,
* <code>UPDATE_REGULAR_COMMENTS</code> and
* <code>UPDATE_STRING_LITERALS</code>, or their bitwise OR, or
* <code>NONE</code>.
* @return the <tt>RenameSupport</tt>.
* @throws CoreException if an unexpected error occured while creating
* the <tt>RenameSupport</tt>.
*/
public static RenameSupport create(IPackageFragment fragment, int flags) throws CoreException {
RefactoringSupport.PackageFragment support= new RefactoringSupport.PackageFragment(fragment);
RenamePackageRefactoring refactoring= support.getSpecificRefactoring();
refactoring.setUpdateReferences(updateReferences(flags));
refactoring.setUpdateJavaDoc(updateJavadocComments(flags));
refactoring.setUpdateComments(updateRegularComments(flags));
refactoring.setUpdateStrings(updateStringLiterals(flags));
return new RenameSupport(support, fragment);
}
/**
* Creates a new rename support for the given <tt>ICompilationUnit</tt>.
*
* @param unit the <tt>ICompilationUnit</tt> to be renamed.
* @param flags flags controlling additional parameters. Valid flags are
* <code>UPDATE_REFERENCES</code>, <code>UPDATE_JAVADOC_COMMENTS</code>,
* <code>UPDATE_REGULAR_COMMENTS</code> and
* <code>UPDATE_STRING_LITERALS</code>, or their bitwise OR, or
* <code>NONE</code>.
* @return the <tt>RenameSupport</tt>.
* @throws CoreException if an unexpected error occured while creating
* the <tt>RenameSupport</tt>.
*/
public static RenameSupport create(ICompilationUnit unit, int flags) throws CoreException {
RefactoringSupport.CompilationUnit support= new RefactoringSupport.CompilationUnit(unit);
RenameCompilationUnitRefactoring refactoring= support.getSpecificRefactoring();
refactoring.setUpdateReferences(updateReferences(flags));
refactoring.setUpdateJavaDoc(updateJavadocComments(flags));
refactoring.setUpdateComments(updateRegularComments(flags));
refactoring.setUpdateStrings(updateStringLiterals(flags));
return new RenameSupport(support, unit);
}
/**
* Creates a new rename support for the given <tt>IType</tt>.
*
* @param type the <tt>IType</tt> to be renamed.
* @param flags flags controlling additional parameters. Valid flags are
* <code>UPDATE_REFERENCES</code>, <code>UPDATE_JAVADOC_COMMENTS</code>,
* <code>UPDATE_REGULAR_COMMENTS</code> and
* <code>UPDATE_STRING_LITERALS</code>, or their bitwise OR, or
* <code>NONE</code>.
* @return the <tt>RenameSupport</tt>.
* @throws CoreException if an unexpected error occured while creating
* the <tt>RenameSupport</tt>.
*/
public static RenameSupport create(IType type, int flags) throws CoreException {
RefactoringSupport.Type support= new RefactoringSupport.Type(type);
RenameTypeRefactoring refactoring= support.getSpecificRefactoring();
refactoring.setUpdateReferences(updateReferences(flags));
refactoring.setUpdateJavaDoc(updateJavadocComments(flags));
refactoring.setUpdateComments(updateRegularComments(flags));
refactoring.setUpdateStrings(updateStringLiterals(flags));
return new RenameSupport(support, type);
}
/**
* Creates a new rename support for the given <tt>IMethod</tt>.
*
* @param method the <tt>IMethod</tt> to be renamed.
* @param flags flags controlling additional parameters. Valid flags are
* <code>UPDATE_REFERENCES</code> or <code>NONE</code>.
* @return the <tt>RenameSupport</tt>.
* @throws CoreException if an unexpected error occured while creating
* the <tt>RenameSupport</tt>.
*/
public static RenameSupport create(IMethod method, int flags) throws CoreException {
RefactoringSupport.Method support= new RefactoringSupport.Method(method);
RenameMethodRefactoring refactoring= support.getSpecificRefactoring();
refactoring.setUpdateReferences(updateReferences(flags));
return new RenameSupport(support, method);
}
/**
* Creates a new rename support for the given <tt>IField</tt>.
*
* @param method the <tt>IField</tt> to be renamed.
* @param flags flags controlling additional parameters. Valid flags are
* <code>UPDATE_REFERENCES</code>, <code>UPDATE_JAVADOC_COMMENTS</code>,
* <code>UPDATE_REGULAR_COMMENTS</code>,
* <code>UPDATE_STRING_LITERALS</code>, </code>UPDATE_GETTER_METHOD</code>
* and </code>UPDATE_SETTER_METHOD</code>, or their bitwise OR, or
* <code>NONE</code>.
* @return the <tt>RenameSupport</tt>.
* @throws CoreException if an unexpected error occured while creating
* the <tt>RenameSupport</tt>.
*/
public static RenameSupport create(IField field, int flags) throws CoreException {
RefactoringSupport.Field support= new RefactoringSupport.Field(field);
RenameFieldRefactoring refactoring= support.getSpecificRefactoring();
refactoring.setUpdateReferences(updateReferences(flags));
refactoring.setUpdateJavaDoc(updateJavadocComments(flags));
refactoring.setUpdateComments(updateRegularComments(flags));
refactoring.setUpdateStrings(updateStringLiterals(flags));
refactoring.setRenameGetter(updateGetterMethod(flags));
refactoring.setRenameSetter(updateSetterMethod(flags));
return new RenameSupport(support, field);
}
/**
* Creates a new <tt>RenameSupport</tt> for the given <tt>IJavaElement</tt>
* by forwarding the creation to one of the concrete create methods
* depending on the type of the given <tt>IJavaElement</tt>.
* @param element the <tt>IJavaElement</tt> to be renamed
* @param flags flags controlling additional parameters. For a list of valid
* flags see the corresponding create methods of this class.
* @return the <tt>RenameSupport</tt>.
* @throws CoreException if an unexpected error occured while creating
* the <tt>RenameSupport</tt>.
*
* @see #create(IJavaProject, int)
* @see #create(IPackageFragmentRoot)
* @see #create(IPackageFragment, int)
* @see #create(ICompilationUnit, int)
* @see #create(IType, int)
* @see #create(IMethod, int)
* @see #create(IField, int)
*/
public static RenameSupport create(IJavaElement element, int flags) throws CoreException {
switch (element.getElementType()) {
case IJavaElement.JAVA_PROJECT:
return create((IJavaProject)element, flags);
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
return create((IPackageFragmentRoot)element, flags);
case IJavaElement.PACKAGE_FRAGMENT:
return create((IPackageFragment)element, flags);
case IJavaElement.COMPILATION_UNIT:
return create((ICompilationUnit)element, flags);
case IJavaElement.TYPE:
return create((IType)element, flags);
case IJavaElement.METHOD:
return create((IMethod)element, flags);
case IJavaElement.FIELD:
return create((IField)element, flags);
}
return null;
}
private static boolean updateReferences(int flags) {
return (flags & UPDATE_REFERENCES) != 0;
}
private static boolean updateJavadocComments(int flags) {
return (flags & UPDATE_JAVADOC_COMMENTS) != 0;
}
private static boolean updateRegularComments(int flags) {
return (flags & UPDATE_REGULAR_COMMENTS) != 0;
}
private static boolean updateStringLiterals(int flags) {
return (flags & UPDATE_STRING_LITERALS) != 0;
}
private static boolean updateGetterMethod(int flags) {
return (flags & UPDATE_GETTER_METHOD) != 0;
}
private static boolean updateSetterMethod(int flags) {
return (flags & UPDATE_SETTER_METHOD) != 0;
}
}
|
27,075 |
Bug 27075 ViewerSorter could maybe lazily initialize Collator
|
calling JavaElementSorter creates a lot of new objects (ViewerSorter calls Collator.getInstance() which is the culprit) so maybe fSorter could be initialized lazily
|
resolved fixed
|
bf897e6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-09T18:27:51Z | 2002-11-25T10:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/MembersOrderPreferencePage.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.internal.ui.preferences;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
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.Label;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.ui.JavaElementImageDescriptor;
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.JavaUIMessages;
import org.eclipse.jdt.internal.ui.viewsupport.ImageDescriptorRegistry;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField;
public class MembersOrderPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
private static final String ALL_ENTRIES= "T,SI,SF,SM,I,F,C,M"; //$NON-NLS-1$
private static final String PREF_OUTLINE_SORT_OPTION= PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER;
private static String CONSTRUCTORS= "C"; //$NON-NLS-1$
private static String FIELDS= "F"; //$NON-NLS-1$
private static String METHODS= "M"; //$NON-NLS-1$
private static String STATIC_METHODS= "SM"; //$NON-NLS-1$
private static String STATIC_FIELDS= "SF"; //$NON-NLS-1$
private static String INIT= "I"; //$NON-NLS-1$
private static String STATIC_INIT= "SI"; //$NON-NLS-1$
private static String TYPES= "T"; //$NON-NLS-1$
public static final int TYPE_INDEX= 0;
public static final int CONSTRUCTORS_INDEX= 1;
public static final int METHOD_INDEX= 2;
public static final int FIELDS_INDEX= 3;
public static final int INIT_INDEX= 4;
public static final int STATIC_FIELDS_INDEX= 5;
public static final int STATIC_INIT_INDEX= 6;
public static final int STATIC_METHODS_INDEX= 7;
private static final int LAST_INDEX= STATIC_METHODS_INDEX;
private final int DEFAULT= 0;
private ListDialogField fSortOrderList;
private static Cache fgCache= null;
private static class Cache implements IPropertyChangeListener {
private int[] offsets= null;
public void propertyChange(PropertyChangeEvent event) {
offsets= null;
}
public int getIndex(int kind) {
if (offsets == null) {
offsets= new int[LAST_INDEX + 1];
fillOffsets();
}
return offsets[kind];
}
private void fillOffsets() {
String string= JavaPlugin.getDefault().getPreferenceStore().getString(PREF_OUTLINE_SORT_OPTION);
List entries= getSortOrderList(string);
if (!isValidEntries(entries)) {
string= JavaPlugin.getDefault().getPreferenceStore().getDefaultString(PREF_OUTLINE_SORT_OPTION);
entries= getSortOrderList(string);
}
offsets[TYPE_INDEX]= entries.indexOf(TYPES);
offsets[METHOD_INDEX]= entries.indexOf(METHODS);
offsets[FIELDS_INDEX]= entries.indexOf(FIELDS);
offsets[INIT_INDEX]= entries.indexOf(INIT);
offsets[STATIC_FIELDS_INDEX]= entries.indexOf(STATIC_FIELDS);
offsets[STATIC_INIT_INDEX]= entries.indexOf(STATIC_INIT);
offsets[STATIC_METHODS_INDEX]= entries.indexOf(STATIC_METHODS);
offsets[CONSTRUCTORS_INDEX]= entries.indexOf(CONSTRUCTORS);
}
}
private static List getSortOrderList(String string) {
StringTokenizer tokenizer= new StringTokenizer(string, ","); //$NON-NLS-1$
List entries= new ArrayList();
for (int i= 0; tokenizer.hasMoreTokens(); i++) {
String token= tokenizer.nextToken();
entries.add(token);
}
return entries;
}
private static boolean isValidEntries(List entries) {
if (entries.size() != LAST_INDEX + 1)
return false;
StringTokenizer tokenizer= new StringTokenizer(ALL_ENTRIES, ","); //$NON-NLS-1$
for (int i= 0; tokenizer.hasMoreTokens(); i++) {
String token= tokenizer.nextToken();
if (!entries.contains(token))
return false;
}
return true;
}
public MembersOrderPreferencePage() {
//set the preference store
setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
String string= getPreferenceStore().getString(PREF_OUTLINE_SORT_OPTION);
String upLabel= JavaUIMessages.getString("MembersOrderPreferencePage.button.up"); //$NON-NLS-1$
String downLabel= JavaUIMessages.getString("MembersOrderPreferencePage.button.down"); //$NON-NLS-1$
String[] buttonlabels= new String[] { upLabel, downLabel };
fSortOrderList= new ListDialogField(new MemberSortAdapter(), buttonlabels, new MemberSortLabelProvider());
fSortOrderList.setDownButtonIndex(1);
fSortOrderList.setUpButtonIndex(0);
//validate entries stored in store, false get defaults
List entries= getSortOrderList(string);
if (!isValidEntries(entries)) {
string= JavaPlugin.getDefault().getPreferenceStore().getDefaultString(PREF_OUTLINE_SORT_OPTION);
entries= getSortOrderList(string);
}
fSortOrderList.setElements(entries);
}
/*
* @see PreferencePage#createControl(Composite)
*/
public void createControl(Composite parent) {
super.createControl(parent);
WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.SORT_ORDER_PREFERENCE_PAGE);
}
/**
* @see org.eclipse.jface.preference.PreferencePage#createContents(Composite)
*/
protected Control createContents(Composite parent) {
Composite composite= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.numColumns= 3;
layout.marginWidth= 0;
layout.marginHeight= 0;
composite.setLayout(layout);
GridData data= new GridData();
data.verticalAlignment= GridData.FILL;
data.horizontalAlignment= GridData.FILL_HORIZONTAL;
composite.setLayoutData(data);
createSortOrderListDialogField(composite, 3);
return composite;
}
private void createSortOrderListDialogField(Composite composite, int span) {
Label sortLabel= new Label(composite, SWT.NONE);
sortLabel.setText(JavaUIMessages.getString("MembersOrderPreferencePage.label.description")); //$NON-NLS-1$
GridData gridData= new GridData();
gridData.horizontalAlignment= GridData.FILL_HORIZONTAL;
gridData.horizontalSpan= span;
sortLabel.setLayoutData(gridData);
fSortOrderList.doFillIntoGrid(composite, span);
LayoutUtil.setHorizontalGrabbing(fSortOrderList.getListControl(null));
}
/**
* @see org.eclipse.ui.IWorkbenchPreferencePage#init(IWorkbench)
*/
public void init(IWorkbench workbench) {
}
/**
* @see org.eclipse.jface.preference.PreferencePage#performDefaults()
*/
protected void performDefaults() {
String string= getPreferenceStore().getDefaultString(PREF_OUTLINE_SORT_OPTION);
fSortOrderList.setElements(getSortOrderList(string));
}
/**
* @see org.eclipse.jface.preference.IPreferencePage#performOk()
*/
//reorders elements in the Outline based on selection
public boolean performOk() {
//update outline view
//save preferences
IPreferenceStore store= getPreferenceStore();
StringBuffer buf= new StringBuffer();
List curr= fSortOrderList.getElements();
for (Iterator iter= curr.iterator(); iter.hasNext();) {
String s= (String) iter.next();
buf.append(s);
buf.append(',');
}
store.setValue(PREF_OUTLINE_SORT_OPTION, buf.toString());
JavaPlugin.getDefault().savePluginPreferences();
return true;
}
public static int getOffset(int kind) {
if (fgCache == null) {
fgCache= new Cache();
JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(fgCache);
}
return fgCache.getIndex(kind);
}
private class MemberSortAdapter implements IListAdapter {
public MemberSortAdapter() {
}
/**
* @see org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter#customButtonPressed(ListDialogField, int)
*/
public void customButtonPressed(ListDialogField field, int index) {
}
/**
* @see org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter#selectionChanged(ListDialogField)
*/
public void selectionChanged(ListDialogField field) {
}
public void doubleClicked(ListDialogField field) {
}
}
private class MemberSortLabelProvider implements ILabelProvider {
public MemberSortLabelProvider() {
}
/**
* @see org.eclipse.jface.viewers.ILabelProvider#getText(Object)
*/
public String getText(Object element) {
if (element instanceof String) {
String s= (String) element;
if (s.equals(FIELDS)) {
return JavaUIMessages.getString("MembersOrderPreferencePage.fields.label"); //$NON-NLS-1$
} else if (s.equals(CONSTRUCTORS)) {
return JavaUIMessages.getString("MembersOrderPreferencePage.constructors.label"); //$NON-NLS-1$
} else if (s.equals(METHODS)) {
return JavaUIMessages.getString("MembersOrderPreferencePage.methods.label"); //$NON-NLS-1$
} else if (s.equals(STATIC_FIELDS)) {
return JavaUIMessages.getString("MembersOrderPreferencePage.staticfields.label"); //$NON-NLS-1$
} else if (s.equals(STATIC_METHODS)) {
return JavaUIMessages.getString("MembersOrderPreferencePage.staticmethods.label"); //$NON-NLS-1$
} else if (s.equals(INIT)) {
return JavaUIMessages.getString("MembersOrderPreferencePage.initialisers.label"); //$NON-NLS-1$
} else if (s.equals(STATIC_INIT)) {
return JavaUIMessages.getString("MembersOrderPreferencePage.staticinitialisers.label"); //$NON-NLS-1$
} else if (s.equals(TYPES)) {
return JavaUIMessages.getString("MembersOrderPreferencePage.types.label"); //$NON-NLS-1$
}
}
return ""; //$NON-NLS-1$
}
/**
* Not implemented
* @see org.eclipse.jface.viewers.IBaseLabelProvider#addListener(ILabelProviderListener)
*/
public void addListener(ILabelProviderListener listener) {
}
/**
* Not implemented
* @see org.eclipse.jface.viewers.IBaseLabelProvider#isLabelProperty(Object, String)
*/
public boolean isLabelProperty(Object element, String property) {
return false;
}
/**
* Not implemented
* @see org.eclipse.jface.viewers.IBaseLabelProvider#removeListener(ILabelProviderListener)
*/
public void removeListener(ILabelProviderListener listener) {
}
/**
* Not implemented
* @see org.eclipse.jface.viewers.IBaseLabelProvider#dispose
*/
public void dispose() {
}
/**
* @see org.eclipse.jface.viewers.ILabelProvider#getImage(Object)
*/
public Image getImage(Object element) {
//access to image registry
ImageDescriptorRegistry registry= JavaPlugin.getImageDescriptorRegistry();
ImageDescriptor descriptor= null;
if (element instanceof String) {
String s= (String) element;
if (s.equals(FIELDS)) {
//0 will give the default field image
descriptor= JavaElementImageProvider.getFieldImageDescriptor(false, Flags.AccPublic);
} else if (s.equals(CONSTRUCTORS)) {
descriptor= JavaElementImageProvider.getMethodImageDescriptor(false, DEFAULT);
//add a constructor adornment to the image descriptor
descriptor= new JavaElementImageDescriptor(descriptor, JavaElementImageDescriptor.CONSTRUCTOR, JavaElementImageProvider.SMALL_SIZE);
} else if (s.equals(METHODS)) {
descriptor= JavaElementImageProvider.getMethodImageDescriptor(false, Flags.AccPublic);
} else if (s.equals(STATIC_FIELDS)) {
descriptor= JavaElementImageProvider.getFieldImageDescriptor(false, Flags.AccPublic);
//add a constructor adornment to the image descriptor
descriptor= new JavaElementImageDescriptor(descriptor, JavaElementImageDescriptor.STATIC, JavaElementImageProvider.SMALL_SIZE);
} else if (s.equals(STATIC_METHODS)) {
descriptor= JavaElementImageProvider.getMethodImageDescriptor(false, Flags.AccPublic);
//add a constructor adornment to the image descriptor
descriptor= new JavaElementImageDescriptor(descriptor, JavaElementImageDescriptor.STATIC, JavaElementImageProvider.SMALL_SIZE);
} else if (s.equals(INIT)) {
descriptor= JavaElementImageProvider.getMethodImageDescriptor(false, DEFAULT);
} else if (s.equals(STATIC_INIT)) {
descriptor= JavaElementImageProvider.getMethodImageDescriptor(false, DEFAULT);
descriptor= new JavaElementImageDescriptor(descriptor, JavaElementImageDescriptor.STATIC, JavaElementImageProvider.SMALL_SIZE);
} else if (s.equals(TYPES)) {
descriptor= JavaElementImageProvider.getTypeImageDescriptor(false, true, Flags.AccPublic);
} else {
descriptor= JavaElementImageProvider.getMethodImageDescriptor(false, DEFAULT);
}
return registry.get(descriptor);
}
return null;
}
}
}
|
27,075 |
Bug 27075 ViewerSorter could maybe lazily initialize Collator
|
calling JavaElementSorter creates a lot of new objects (ViewerSorter calls Collator.getInstance() which is the culprit) so maybe fSorter could be initialized lazily
|
resolved fixed
|
bf897e6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-09T18:27:51Z | 2002-11-25T10:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/dialogfields/ListDialogField.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.wizards.dialogfields;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
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.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.ColumnLayoutData;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.jdt.internal.ui.util.PixelConverter;
import org.eclipse.jdt.internal.ui.util.SWTUtil;
/**
* A list with a button bar.
* Typical buttons are 'Add', 'Remove', 'Up' and 'Down'.
* List model is independend of widget creation.
* DialogFields controls are: Label, List and Composite containing buttons.
*/
public class ListDialogField extends DialogField {
public static class ColumnsDescription {
private ColumnLayoutData[] columns;
private String[] headers;
private boolean drawLines;
public ColumnsDescription(ColumnLayoutData[] columns, String[] headers, boolean drawLines) {
this.columns= columns;
this.headers= headers;
this.drawLines= drawLines;
}
public ColumnsDescription(String[] headers, boolean drawLines) {
this(createColumnWeightData(headers.length), headers, drawLines);
}
public ColumnsDescription(int nColumns, boolean drawLines) {
this(createColumnWeightData(nColumns), null, drawLines);
}
private static ColumnLayoutData[] createColumnWeightData(int nColumns) {
ColumnLayoutData[] data= new ColumnLayoutData[nColumns];
for (int i= 0; i < nColumns; i++) {
data[i]= new ColumnWeightData(1);
}
return data;
}
}
protected TableViewer fTable;
protected ILabelProvider fLabelProvider;
protected ListViewerAdapter fListViewerAdapter;
protected List fElements;
protected ViewerSorter fViewerSorter;
protected String[] fButtonLabels;
private Button[] fButtonControls;
private boolean[] fButtonsEnabled;
private int fRemoveButtonIndex;
private int fUpButtonIndex;
private int fDownButtonIndex;
private Label fLastSeparator;
private Table fTableControl;
private Composite fButtonsControl;
private ISelection fSelectionWhenEnabled;
private IListAdapter fListAdapter;
private Object fParentElement;
private ColumnsDescription fTableColumns;
/**
* Creates the <code>ListDialogField</code>.
* @param adapter A listener for button invocation, selection changes.
* @param buttonLabels The labels of all buttons: <code>null</code> is a valid array entry and
* marks a separator.
* @param lprovider The label provider to render the table entries
*/
public ListDialogField(IListAdapter adapter, String[] buttonLabels, ILabelProvider lprovider) {
super();
fListAdapter= adapter;
fLabelProvider= lprovider;
fListViewerAdapter= new ListViewerAdapter();
fParentElement= this;
fElements= new ArrayList(10);
fButtonLabels= buttonLabels;
if (fButtonLabels != null) {
int nButtons= fButtonLabels.length;
fButtonsEnabled= new boolean[nButtons];
for (int i= 0; i < nButtons; i++) {
fButtonsEnabled[i]= true;
}
}
fTable= null;
fTableControl= null;
fButtonsControl= null;
fTableColumns= null;
fRemoveButtonIndex= -1;
fUpButtonIndex= -1;
fDownButtonIndex= -1;
}
/**
* Sets the index of the 'remove' button in the button label array passed in the constructor.
* The behaviour of the button marked as the 'remove' button will then be handled internally.
* (enable state, button invocation behaviour)
*/
public void setRemoveButtonIndex(int removeButtonIndex) {
Assert.isTrue(removeButtonIndex < fButtonLabels.length);
fRemoveButtonIndex= removeButtonIndex;
}
/**
* Sets the index of the 'up' button in the button label array passed in the constructor.
* The behaviour of the button marked as the 'up' button will then be handled internally.
* (enable state, button invocation behaviour)
*/
public void setUpButtonIndex(int upButtonIndex) {
Assert.isTrue(upButtonIndex < fButtonLabels.length);
fUpButtonIndex= upButtonIndex;
}
/**
* Sets the index of the 'down' button in the button label array passed in the constructor.
* The behaviour of the button marked as the 'down' button will then be handled internally.
* (enable state, button invocation behaviour)
*/
public void setDownButtonIndex(int downButtonIndex) {
Assert.isTrue(downButtonIndex < fButtonLabels.length);
fDownButtonIndex= downButtonIndex;
}
/**
* Sets the viewerSorter.
* @param viewerSorter The viewerSorter to set
*/
public void setViewerSorter(ViewerSorter viewerSorter) {
fViewerSorter= viewerSorter;
}
public void setTableColumns(ColumnsDescription column) {
fTableColumns= column;
}
// ------ adapter communication
private void buttonPressed(int index) {
if (!managedButtonPressed(index)) {
fListAdapter.customButtonPressed(this, index);
}
}
/**
* Checks if the button pressed is handled internally
* @return Returns true if button has been handled.
*/
protected boolean managedButtonPressed(int index) {
if (index == fRemoveButtonIndex) {
remove();
} else if (index == fUpButtonIndex) {
up();
} else if (index == fDownButtonIndex) {
down();
} else {
return false;
}
return true;
}
// ------ layout helpers
/*
* @see DialogField#doFillIntoGrid
*/
public Control[] doFillIntoGrid(Composite parent, int nColumns) {
PixelConverter converter= new PixelConverter(parent);
assertEnoughColumns(nColumns);
Label label= getLabelControl(parent);
GridData gd= gridDataForLabel(1);
gd.verticalAlignment= GridData.BEGINNING;
label.setLayoutData(gd);
Control list= getListControl(parent);
gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.grabExcessHorizontalSpace= false;
gd.verticalAlignment= GridData.FILL;
gd.grabExcessVerticalSpace= true;
gd.horizontalSpan= nColumns - 2;
gd.widthHint= converter.convertWidthInCharsToPixels(50);
gd.heightHint= converter.convertHeightInCharsToPixels(6);
list.setLayoutData(gd);
Composite buttons= getButtonBox(parent);
gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.grabExcessHorizontalSpace= false;
gd.verticalAlignment= GridData.FILL;
gd.grabExcessVerticalSpace= true;
gd.horizontalSpan= 1;
buttons.setLayoutData(gd);
return new Control[] { label, list, buttons };
}
/*
* @see DialogField#getNumberOfControls
*/
public int getNumberOfControls() {
return 3;
}
/**
* Sets the minimal width of the buttons. Must be called after widget creation.
*/
public void setButtonsMinWidth(int minWidth) {
if (fLastSeparator != null) {
((GridData)fLastSeparator.getLayoutData()).widthHint= minWidth;
}
}
// ------ ui creation
/**
* Returns the list control. When called the first time, the control will be created.
* @param The parent composite when called the first time, or <code>null</code>
* after.
*/
public Control getListControl(Composite parent) {
if (fTableControl == null) {
assertCompositeNotNull(parent);
fTable= createTableViewer(parent);
fTableControl= (Table)fTable.getControl();
fTableControl.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
handleKeyPressed(e);
}
});
TableLayout tableLayout= new TableLayout();
fTableControl.setLayout(tableLayout);
if (fTableColumns != null) {
fTableControl.setHeaderVisible(fTableColumns.headers != null);
fTableControl.setLinesVisible(fTableColumns.drawLines);
ColumnLayoutData[] columns= fTableColumns.columns;
for (int i= 0; i < columns.length; i++) {
TableColumn column= new TableColumn(fTableControl, SWT.NONE);
tableLayout.addColumnData(columns[i]);
if (fTableColumns.headers != null) {
column.setText(fTableColumns.headers[i]);
}
}
}
fTable.setContentProvider(fListViewerAdapter);
fTable.setLabelProvider(fLabelProvider);
fTable.addSelectionChangedListener(fListViewerAdapter);
fTable.addDoubleClickListener(fListViewerAdapter);
fTable.setInput(fParentElement);
if (fViewerSorter != null) {
fTable.setSorter(fViewerSorter);
}
fTableControl.setEnabled(isEnabled());
if (fSelectionWhenEnabled != null) {
postSetSelection(fSelectionWhenEnabled);
}
}
return fTableControl;
}
/**
* Returns the internally used table viewer.
*/
public TableViewer getTableViewer() {
return fTable;
}
/*
* Subclasses may override to specify a different style.
*/
protected int getListStyle(){
int style= SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL ;
if (fTableColumns != null) {
style |= SWT.FULL_SELECTION;
}
return style;
}
protected TableViewer createTableViewer(Composite parent) {
Table table= new Table(parent, getListStyle());
return new TableViewer(table);
}
protected Button createButton(Composite parent, String label, SelectionListener listener) {
Button button= new Button(parent, SWT.PUSH);
button.setText(label);
button.addSelectionListener(listener);
GridData gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.grabExcessHorizontalSpace= true;
gd.verticalAlignment= GridData.BEGINNING;
gd.heightHint = SWTUtil.getButtonHeigthHint(button);
gd.widthHint = SWTUtil.getButtonWidthHint(button);
button.setLayoutData(gd);
return button;
}
private Label createSeparator(Composite parent) {
Label separator= new Label(parent, SWT.NONE);
separator.setVisible(false);
GridData gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.verticalAlignment= GridData.BEGINNING;
gd.heightHint= 4;
separator.setLayoutData(gd);
return separator;
}
/**
* Returns the composite containing the buttons. When called the first time, the control
* will be created.
* @param The parent composite when called the first time, or <code>null</code>
* after.
*/
public Composite getButtonBox(Composite parent) {
if (fButtonsControl == null) {
assertCompositeNotNull(parent);
SelectionListener listener= new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
doButtonSelected(e);
}
public void widgetSelected(SelectionEvent e) {
doButtonSelected(e);
}
};
Composite contents= new Composite(parent, SWT.NULL);
GridLayout layout= new GridLayout();
layout.marginWidth= 0;
layout.marginHeight= 0;
contents.setLayout(layout);
if (fButtonLabels != null) {
fButtonControls= new Button[fButtonLabels.length];
for (int i= 0; i < fButtonLabels.length; i++) {
String currLabel= fButtonLabels[i];
if (currLabel != null) {
fButtonControls[i]= createButton(contents, currLabel, listener);
fButtonControls[i].setEnabled(isEnabled() && fButtonsEnabled[i]);
} else {
fButtonControls[i]= null;
createSeparator(contents);
}
}
}
fLastSeparator= createSeparator(contents);
updateButtonState();
fButtonsControl= contents;
}
return fButtonsControl;
}
private void doButtonSelected(SelectionEvent e) {
if (fButtonControls != null) {
for (int i= 0; i < fButtonControls.length; i++) {
if (e.widget == fButtonControls[i]) {
buttonPressed(i);
return;
}
}
}
}
/**
* Handles key events in the table viewer. Specifically
* when the delete key is pressed.
*/
protected void handleKeyPressed(KeyEvent event) {
if (event.character == SWT.DEL && event.stateMask == 0) {
if (fRemoveButtonIndex != -1 && isButtonEnabled(fTable.getSelection(), fRemoveButtonIndex)) {
managedButtonPressed(fRemoveButtonIndex);
}
}
}
// ------ enable / disable management
/*
* @see DialogField#dialogFieldChanged
*/
public void dialogFieldChanged() {
super.dialogFieldChanged();
updateButtonState();
}
private Button getButton(int index) {
if (fButtonControls != null && index >= 0 && index < fButtonControls.length) {
return fButtonControls[index];
}
return null;
}
/*
* Updates the enable state of the all buttons
*/
protected void updateButtonState() {
if (fButtonControls != null) {
ISelection sel= fTable.getSelection();
for (int i= 0; i < fButtonControls.length; i++) {
Button button= fButtonControls[i];
if (isOkToUse(button)) {
button.setEnabled(isButtonEnabled(sel, i));
}
}
}
}
protected boolean getManagedButtonState(ISelection sel, int index) {
if (index == fRemoveButtonIndex) {
return !sel.isEmpty();
} else if (index == fUpButtonIndex) {
return !sel.isEmpty() && canMoveUp();
} else if (index == fDownButtonIndex) {
return !sel.isEmpty() && canMoveDown();
}
return true;
}
/*
* @see DialogField#updateEnableState
*/
protected void updateEnableState() {
super.updateEnableState();
boolean enabled= isEnabled();
if (isOkToUse(fTableControl)) {
if (!enabled) {
fSelectionWhenEnabled= fTable.getSelection();
selectElements(null);
} else {
selectElements(fSelectionWhenEnabled);
fSelectionWhenEnabled= null;
}
fTableControl.setEnabled(enabled);
}
updateButtonState();
}
/**
* Sets a button enabled or disabled.
*/
public void enableButton(int index, boolean enable) {
if (fButtonsEnabled != null && index < fButtonsEnabled.length) {
fButtonsEnabled[index]= enable;
updateButtonState();
}
}
private boolean isButtonEnabled(ISelection sel, int index) {
boolean extraState= getManagedButtonState(sel, index);
return isEnabled() && extraState && fButtonsEnabled[index];
}
// ------ model access
/**
* Sets the elements shown in the list.
*/
public void setElements(List elements) {
fElements= new ArrayList(elements);
if (fTable != null) {
fTable.refresh();
}
dialogFieldChanged();
}
/**
* Gets the elements shown in the list.
* The list returned is a copy, so it can be modified by the user.
*/
public List getElements() {
return new ArrayList(fElements);
}
/**
* Gets the elements shown at the given index.
*/
public Object getElement(int index) {
return fElements.get(index);
}
/**
* Gets the index of an element in the list or -1 if element is not in list.
*/
public int getIndexOfElement(Object elem) {
return fElements.indexOf(elem);
}
/**
* Replace an element.
*/
public void replaceElement(Object oldElement, Object newElement) throws IllegalArgumentException {
int idx= fElements.indexOf(oldElement);
if (idx != -1) {
if (oldElement.equals(newElement) || fElements.contains(newElement)) {
return;
}
fElements.set(idx, newElement);
if (fTable != null) {
List selected= getSelectedElements();
if (selected.remove(oldElement)) {
selected.add(newElement);
}
fTable.refresh();
selectElements(new StructuredSelection(selected));
}
dialogFieldChanged();
} else {
throw new IllegalArgumentException();
}
}
/**
* Adds an element at the end of the list.
*/
public void addElement(Object element) {
if (fElements.contains(element)) {
return;
}
fElements.add(element);
if (fTable != null) {
fTable.add(element);
}
dialogFieldChanged();
}
/**
* Adds elements at the end of the list.
*/
public void addElements(List elements) {
int nElements= elements.size();
if (nElements > 0) {
// filter duplicated
ArrayList elementsToAdd= new ArrayList(nElements);
for (int i= 0; i < nElements; i++) {
Object elem= elements.get(i);
if (!fElements.contains(elem)) {
elementsToAdd.add(elem);
}
}
fElements.addAll(elementsToAdd);
if (fTable != null) {
fTable.add(elementsToAdd.toArray());
}
dialogFieldChanged();
}
}
/**
* Adds an element at a position.
*/
public void insertElementAt(Object element, int index) {
if (fElements.contains(element)) {
return;
}
fElements.add(index, element);
if (fTable != null) {
fTable.add(element);
}
dialogFieldChanged();
}
/**
* Adds an element at a position.
*/
public void removeAllElements() {
if (fElements.size() > 0) {
fElements.clear();
if (fTable != null) {
fTable.refresh();
}
dialogFieldChanged();
}
}
/**
* Removes an element from the list.
*/
public void removeElement(Object element) throws IllegalArgumentException {
if (fElements.remove(element)) {
if (fTable != null) {
fTable.remove(element);
}
dialogFieldChanged();
} else {
throw new IllegalArgumentException();
}
}
/**
* Removes elements from the list.
*/
public void removeElements(List elements) {
if (elements.size() > 0) {
fElements.removeAll(elements);
if (fTable != null) {
fTable.remove(elements.toArray());
}
dialogFieldChanged();
}
}
/**
* Gets the number of elements
*/
public int getSize() {
return fElements.size();
}
public void selectElements(ISelection selection) {
fSelectionWhenEnabled= selection;
if (fTable != null) {
fTable.setSelection(selection, true);
}
}
public void selectFirstElement() {
Object element= null;
if (fViewerSorter != null) {
Object[] arr= fElements.toArray();
fViewerSorter.sort(fTable, arr);
if (arr.length > 0) {
element= arr[0];
}
} else {
if (fElements.size() > 0) {
element= fElements.get(0);
}
}
if (element != null) {
selectElements(new StructuredSelection(element));
}
}
public void postSetSelection(final ISelection selection) {
if (isOkToUse(fTableControl)) {
Display d= fTableControl.getDisplay();
d.asyncExec(new Runnable() {
public void run() {
if (isOkToUse(fTableControl)) {
selectElements(selection);
}
}
});
}
}
/**
* Refreshes the table.
*/
public void refresh() {
if (fTable != null) {
fTable.refresh();
}
}
// ------- list maintenance
private List moveUp(List elements, List move) {
int nElements= elements.size();
List res= new ArrayList(nElements);
Object floating= null;
for (int i= 0; i < nElements; i++) {
Object curr= elements.get(i);
if (move.contains(curr)) {
res.add(curr);
} else {
if (floating != null) {
res.add(floating);
}
floating= curr;
}
}
if (floating != null) {
res.add(floating);
}
return res;
}
private void moveUp(List toMoveUp) {
if (toMoveUp.size() > 0) {
setElements(moveUp(fElements, toMoveUp));
fTable.reveal(toMoveUp.get(0));
}
}
private void moveDown(List toMoveDown) {
if (toMoveDown.size() > 0) {
setElements(reverse(moveUp(reverse(fElements), toMoveDown)));
fTable.reveal(toMoveDown.get(toMoveDown.size() - 1));
}
}
private List reverse(List p) {
List reverse= new ArrayList(p.size());
for (int i= p.size()-1; i >= 0; i--) {
reverse.add(p.get(i));
}
return reverse;
}
private void remove() {
removeElements(getSelectedElements());
}
private void up() {
moveUp(getSelectedElements());
}
private void down() {
moveDown(getSelectedElements());
}
private boolean canMoveUp() {
if (isOkToUse(fTableControl)) {
int[] indc= fTableControl.getSelectionIndices();
for (int i= 0; i < indc.length; i++) {
if (indc[i] != i) {
return true;
}
}
}
return false;
}
private boolean canMoveDown() {
if (isOkToUse(fTableControl)) {
int[] indc= fTableControl.getSelectionIndices();
int k= fElements.size() - 1;
for (int i= indc.length - 1; i >= 0 ; i--, k--) {
if (indc[i] != k) {
return true;
}
}
}
return false;
}
/**
* Returns the selected elements.
*/
public List getSelectedElements() {
List result= new ArrayList();
if (fTable != null) {
ISelection selection= fTable.getSelection();
if (selection instanceof IStructuredSelection) {
Iterator iter= ((IStructuredSelection)selection).iterator();
while (iter.hasNext()) {
result.add(iter.next());
}
}
}
return result;
}
// ------- ListViewerAdapter
private class ListViewerAdapter implements IStructuredContentProvider, ISelectionChangedListener, IDoubleClickListener {
// ------- ITableContentProvider Interface ------------
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
// will never happen
}
public boolean isDeleted(Object element) {
return false;
}
public void dispose() {
}
public Object[] getElements(Object obj) {
return fElements.toArray();
}
// ------- ISelectionChangedListener Interface ------------
public void selectionChanged(SelectionChangedEvent event) {
doListSelected(event);
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.IDoubleClickListener#doubleClick(org.eclipse.jface.viewers.DoubleClickEvent)
*/
public void doubleClick(DoubleClickEvent event) {
doDoubleClick(event);
}
}
protected void doListSelected(SelectionChangedEvent event) {
updateButtonState();
if (fListAdapter != null) {
fListAdapter.selectionChanged(this);
}
}
protected void doDoubleClick(DoubleClickEvent event) {
if (fListAdapter != null) {
fListAdapter.doubleClicked(this);
}
}
}
|
27,075 |
Bug 27075 ViewerSorter could maybe lazily initialize Collator
|
calling JavaElementSorter creates a lot of new objects (ViewerSorter calls Collator.getInstance() which is the culprit) so maybe fSorter could be initialized lazily
|
resolved fixed
|
bf897e6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-09T18:27:51Z | 2002-11-25T10:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/JavaElementSorter.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.ui;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IStorage;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jface.viewers.ContentViewer;
import org.eclipse.jface.viewers.IBaseLabelProvider;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IInitializer;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.preferences.MembersOrderPreferencePage;
/**
* Sorter for Java elements. Ordered by element category, then by element name.
* Package fragment roots are sorted as ordered on the classpath.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.0
*/
public class JavaElementSorter extends ViewerSorter {
private static final int JAVAPROJECTS= 1;
private static final int PACKAGEFRAGMENTROOTS= 2;
private static final int PACKAGEFRAGMENT= 3;
private static final int COMPILATIONUNITS= 4;
private static final int CLASSFILES= 5;
private static final int RESOURCEFOLDERS= 7;
// private static final int RESOURCEPACKAGES= 6;
private static final int RESOURCES= 8;
private static final int STORAGE= 9;
private static final int PACKAGE_DECL= 10;
private static final int IMPORT_CONTAINER= 11;
private static final int IMPORT_DECLARATION= 12;
// Includes all categories ordered using the OutlineSortOrderPage:
// types, initializers, methods & fields
private static final int MEMBERSOFFSET= 13;
private static final int JAVAELEMENTS= 50;
private static final int OTHERS= 51;
public JavaElementSorter() {
}
/**
* @deprecated Bug 22518. Method never used: does not override ViewerSorter#isSorterProperty(Object, String).
* Method could be removed, but kept for API compatibility.
*/
public boolean isSorterProperty(Object element, Object property) {
return true;
}
/*
* @see ViewerSorter#category
*/
public int category(Object element) {
if (element instanceof IJavaElement) {
try {
IJavaElement je= (IJavaElement) element;
switch (je.getElementType()) {
case IJavaElement.METHOD:
{
IMethod method= (IMethod) je;
if (method.isConstructor()) {
return MEMBERSOFFSET + MembersOrderPreferencePage.getOffset(MembersOrderPreferencePage.CONSTRUCTORS_INDEX);
}
int flags= method.getFlags();
if (Flags.isStatic(flags))
return MEMBERSOFFSET + MembersOrderPreferencePage.getOffset(MembersOrderPreferencePage.STATIC_METHODS_INDEX);
else
return MEMBERSOFFSET + MembersOrderPreferencePage.getOffset(MembersOrderPreferencePage.METHOD_INDEX);
}
case IJavaElement.FIELD :
{
int flags= ((IField) je).getFlags();
if (Flags.isStatic(flags))
return MEMBERSOFFSET + MembersOrderPreferencePage.getOffset(MembersOrderPreferencePage.STATIC_FIELDS_INDEX);
else
return MEMBERSOFFSET + MembersOrderPreferencePage.getOffset(MembersOrderPreferencePage.FIELDS_INDEX);
}
case IJavaElement.INITIALIZER :
{
int flags= ((IInitializer) je).getFlags();
if (Flags.isStatic(flags))
return MEMBERSOFFSET + MembersOrderPreferencePage.getOffset(MembersOrderPreferencePage.STATIC_INIT_INDEX);
else
return MEMBERSOFFSET + MembersOrderPreferencePage.getOffset(MembersOrderPreferencePage.INIT_INDEX);
}
case IJavaElement.TYPE :
return MEMBERSOFFSET + MembersOrderPreferencePage.getOffset(MembersOrderPreferencePage.TYPE_INDEX);
case IJavaElement.PACKAGE_DECLARATION :
return PACKAGE_DECL;
case IJavaElement.IMPORT_CONTAINER :
return IMPORT_CONTAINER;
case IJavaElement.IMPORT_DECLARATION :
return IMPORT_DECLARATION;
case IJavaElement.PACKAGE_FRAGMENT :
IPackageFragment pack= (IPackageFragment) je;
if (pack.getParent().getResource() instanceof IProject) {
return PACKAGEFRAGMENTROOTS;
}
return PACKAGEFRAGMENT;
case IJavaElement.PACKAGE_FRAGMENT_ROOT :
return PACKAGEFRAGMENTROOTS;
case IJavaElement.JAVA_PROJECT :
return JAVAPROJECTS;
case IJavaElement.CLASS_FILE :
return CLASSFILES;
case IJavaElement.COMPILATION_UNIT :
return COMPILATIONUNITS;
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
return JAVAELEMENTS;
} else if (element instanceof IFile) {
return RESOURCES;
} else if (element instanceof IContainer) {
return RESOURCEFOLDERS;
} else if (element instanceof IStorage) {
return STORAGE;
}
return OTHERS;
}
/*
* @see ViewerSorter#compare
*/
public int compare(Viewer viewer, Object e1, Object e2) {
int cat1= category(e1);
int cat2= category(e2);
if (cat1 != cat2)
return cat1 - cat2;
if (cat1 == PACKAGEFRAGMENTROOTS) {
IPackageFragmentRoot root1= JavaModelUtil.getPackageFragmentRoot((IJavaElement)e1);
IPackageFragmentRoot root2= JavaModelUtil.getPackageFragmentRoot((IJavaElement)e2);
if (!root1.getPath().equals(root2.getPath())) {
int p1= getClassPathIndex(root1);
int p2= getClassPathIndex(root2);
if (p1 != p2) {
return p1 - p2;
}
}
}
// non - java resources are sorted using the label from the viewers label provider
if (cat1 == RESOURCES || cat1 == RESOURCEFOLDERS || cat1 == STORAGE || cat1 == OTHERS) {
return compareWithLabelProvider(viewer, e1, e2);
}
String name1= ((IJavaElement) e1).getElementName();
String name2= ((IJavaElement) e2).getElementName();
// java element are sorted by name
int cmp= getCollator().compare(name1, name2);
if (cmp != 0) {
return cmp;
}
if (e1 instanceof IMethod) {
String[] params1= ((IMethod) e1).getParameterTypes();
String[] params2= ((IMethod) e2).getParameterTypes();
int len= Math.min(params1.length, params2.length);
for (int i = 0; i < len; i++) {
cmp= getCollator().compare(Signature.toString(params1[i]), Signature.toString(params2[i]));
if (cmp != 0) {
return cmp;
}
}
return params1.length - params2.length;
}
return 0;
}
private int compareWithLabelProvider(Viewer viewer, Object e1, Object e2) {
if (viewer == null || !(viewer instanceof ContentViewer)) {
IBaseLabelProvider prov = ((ContentViewer) viewer).getLabelProvider();
if (prov instanceof ILabelProvider) {
ILabelProvider lprov= (ILabelProvider) prov;
String name1 = lprov.getText(e1);
String name2 = lprov.getText(e2);
if (name1 != null && name2 != null) {
return getCollator().compare(name1, name2);
}
}
}
return 0; // can't compare
}
private int getClassPathIndex(IPackageFragmentRoot root) {
try {
IPath rootPath= root.getPath();
IPackageFragmentRoot[] roots= root.getJavaProject().getPackageFragmentRoots();
for (int i= 0; i < roots.length; i++) {
if (roots[i].getPath().equals(rootPath)) {
return i;
}
}
} catch (JavaModelException e) {
}
return Integer.MAX_VALUE;
}
}
|
5,295 |
Bug 5295 Segmented view misses field comment
|
Build 20011025 1. Create the following CU: X.java ------ public class X { String s1 = "s1"; //comment for s1 } 2. Make sure that 'Show Source of Selected Element Only' is selected 3. In the Outline, select field 's1' Observe: The comment doesn't appear near the field declaration.
|
verified fixed
|
5cecf07
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-10T00:35:03Z | 2001-10-26T15:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/compare/JavaParseTreeBuilder.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.compare;
import java.util.Stack;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jdt.internal.compiler.*;
import org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
class JavaParseTreeBuilder extends SourceElementRequestorAdapter implements ICompilationUnit {
private static final boolean SHOW_COMPILATIONUNIT= true;
private char[] fBuffer;
private JavaNode fImportContainer;
private Stack fStack= new Stack();
/**
* Parsing is performed on the given buffer and the resulting tree
* (if any) hangs below the given root.
*/
JavaParseTreeBuilder(JavaNode root, char[] buffer) {
fImportContainer= null;
fStack.clear();
fStack.push(root);
fBuffer= buffer;
}
//---- ICompilationUnit
/* (non Java doc)
* @see ICompilationUnit#getContents
*/
public char[] getContents() {
return fBuffer;
}
/* (non Java doc)
* @see ICompilationUnit#getFileName
*/
public char[] getFileName() {
return new char[0];
}
/* (non Java doc)
* @see ICompilationUnit#getMainTypeName
*/
public char[] getMainTypeName() {
return new char[0];
}
/* (non Java doc)
* @see ICompilationUnit#getMainTypeName
*/
public char[][] getPackageName() {
return null;
}
//---- ISourceElementRequestor
public void enterCompilationUnit() {
if (SHOW_COMPILATIONUNIT)
push(JavaNode.CU, null, 0);
}
public void exitCompilationUnit(int declarationEnd) {
if (SHOW_COMPILATIONUNIT)
pop(declarationEnd);
}
public void acceptPackage(int declarationStart, int declarationEnd, char[] p3) {
push(JavaNode.PACKAGE, null, declarationStart);
pop(declarationEnd);
}
public void acceptImport(int declarationStart, int declarationEnd, char[] name, boolean onDemand) {
int length= declarationEnd-declarationStart+1;
if (fImportContainer == null)
fImportContainer= new JavaNode(getCurrentContainer(), JavaNode.IMPORT_CONTAINER, null, declarationStart, length);
String nm= new String(name);
if (onDemand)
nm+= ".*"; //$NON-NLS-1$
new JavaNode(fImportContainer, JavaNode.IMPORT, nm, declarationStart, length);
fImportContainer.setLength(declarationEnd-fImportContainer.getRange().getOffset()+1);
fImportContainer.setAppendPosition(declarationEnd+2); // FIXME
}
public void enterClass(int declarationStart, int p2, char[] name, int p4, int p5, char[] p6, char[][] p7) {
push(JavaNode.CLASS, new String(name), declarationStart);
}
public void exitClass(int declarationEnd) {
pop(declarationEnd);
}
public void enterInterface(int declarationStart, int p2, char[] name, int p4, int p5, char[][] p6) {
push(JavaNode.INTERFACE, new String(name), declarationStart);
}
public void exitInterface(int declarationEnd) {
pop(declarationEnd);
}
public void enterInitializer(int declarationStart, int modifiers) {
push(JavaNode.INIT, getCurrentContainer().getInitializerCount(), declarationStart);
}
public void exitInitializer(int declarationEnd) {
pop(declarationEnd);
}
public void enterConstructor(int declarationStart, int p2, char[] name, int p4, int p5, char[][] parameterTypes, char[][] p7, char[][] p8) {
push(JavaNode.CONSTRUCTOR, getSignature(name, parameterTypes), declarationStart);
}
public void exitConstructor(int declarationEnd) {
pop(declarationEnd);
}
public void enterMethod(int declarationStart, int p2, char[] p3, char[] name, int p5, int p6, char[][] parameterTypes, char[][] p8, char[][] p9){
push(JavaNode.METHOD, getSignature(name, parameterTypes), declarationStart);
}
public void exitMethod(int declarationEnd) {
pop(declarationEnd);
}
public void enterField(int declarationStart, int p2, char[] p3, char[] name, int p5, int p6) {
push(JavaNode.FIELD, new String(name), declarationStart);
}
/*
* Obsolete: remove in next build.
*/
public void exitField(int declarationEnd) {
pop(declarationEnd);
}
public void exitField(int initializationStart, int declarationEnd) {
pop(declarationEnd);
}
private IDocument getDocument() {
JavaNode top= (JavaNode) fStack.peek();
return top.getDocument();
}
private JavaNode getCurrentContainer() {
return (JavaNode) fStack.peek();
}
/**
* Adds a new JavaNode with the given type and name to the current container.
*/
private void push(int type, String name, int declarationStart) {
while (declarationStart > 0) {
char c= fBuffer[declarationStart-1];
if (c != ' ' && c != '\t')
break;
declarationStart--;
}
fStack.push(new JavaNode(getCurrentContainer(), type, name, declarationStart, 0));
}
/**
* Closes the current Java node by setting its end position
* and pops it off the stack.
*/
private void pop(int declarationEnd) {
JavaNode current= getCurrentContainer();
if (current.getTypeCode() == JavaNode.CU)
current.setAppendPosition(declarationEnd+1);
else
current.setAppendPosition(declarationEnd);
current.setLength(declarationEnd - current.getRange().getOffset() + 1);
fStack.pop();
}
/**
* Builds a signature string from the given name and parameter types.
*/
private String getSignature(char[] name, char[][] parameterTypes) {
StringBuffer buffer= new StringBuffer();
buffer.append(name);
buffer.append('(');
if (parameterTypes != null) {
for (int p= 0; p < parameterTypes.length; p++) {
String parameterType= new String(parameterTypes[p]);
int pos= parameterType.lastIndexOf('.');
if (pos >= 0)
parameterType= parameterType.substring(pos+1);
buffer.append(parameterType);
if (p < parameterTypes.length-1)
buffer.append(", "); //$NON-NLS-1$
}
}
buffer.append(')');
return buffer.toString();
}
}
|
27,764 |
Bug 27764 IResource.findMarkers is called too often
| null |
resolved fixed
|
aa5adb6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-10T10:19:21Z | 2002-12-05T14:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/PackageExplorerActionGroup.java
|
/*******************************************************************************
* Copyright (c) 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.internal.ui.packageview;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IResource;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.OpenStrategy;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.OpenEvent;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.IWorkingSet;
import org.eclipse.ui.IWorkingSetManager;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.actions.MoveResourceAction;
import org.eclipse.ui.actions.OpenInNewWindowAction;
import org.eclipse.ui.actions.RenameResourceAction;
import org.eclipse.ui.views.framelist.BackAction;
import org.eclipse.ui.views.framelist.ForwardAction;
import org.eclipse.ui.views.framelist.FrameList;
import org.eclipse.ui.views.framelist.GoIntoAction;
import org.eclipse.ui.views.framelist.UpAction;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IOpenable;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.actions.BuildActionGroup;
import org.eclipse.jdt.ui.actions.CCPActionGroup;
import org.eclipse.jdt.ui.actions.CustomFiltersActionGroup;
import org.eclipse.jdt.ui.actions.GenerateActionGroup;
import org.eclipse.jdt.ui.actions.ImportActionGroup;
import org.eclipse.jdt.ui.actions.JavaSearchActionGroup;
import org.eclipse.jdt.ui.actions.JdtActionConstants;
import org.eclipse.jdt.ui.actions.MemberFilterActionGroup;
import org.eclipse.jdt.ui.actions.NavigateActionGroup;
import org.eclipse.jdt.ui.actions.ProjectActionGroup;
import org.eclipse.jdt.ui.actions.RefactorActionGroup;
import org.eclipse.jdt.ui.actions.ShowActionGroup;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.actions.NewWizardsActionGroup;
import org.eclipse.jdt.internal.ui.workingsets.WorkingSetFilterActionGroup;
class PackageExplorerActionGroup extends CompositeActionGroup implements ISelectionChangedListener {
private PackageExplorerPart fPart;
private GoIntoAction fZoomInAction;
private BackAction fBackAction;
private ForwardAction fForwardAction;
private UpAction fUpAction;
private GotoTypeAction fGotoTypeAction;
private GotoPackageAction fGotoPackageAction;
private GotoResourceAction fGotoResourceAction;
private CollapseAllAction fCollapseAllAction;
private RenameResourceAction fRenameResourceAction;
private MoveResourceAction fMoveResourceAction;
private NavigateActionGroup fNavigateActionGroup;
private BuildActionGroup fBuildActionGroup;
private CCPActionGroup fCCPActionGroup;
private WorkingSetFilterActionGroup fWorkingSetFilterActionGroup;
private MemberFilterActionGroup fMemberFilterActionGroup;
private CustomFiltersActionGroup fCustomFiltersActionGroup;
public PackageExplorerActionGroup(PackageExplorerPart part) {
super();
fPart= part;
IWorkbenchPartSite site = fPart.getSite();
Shell shell= site.getShell();
ISelectionProvider provider= site.getSelectionProvider();
IStructuredSelection selection= (IStructuredSelection) provider.getSelection();
setGroups(new ActionGroup[] {
new NewWizardsActionGroup(site),
fNavigateActionGroup= new NavigateActionGroup(fPart),
new ShowActionGroup(fPart),
fCCPActionGroup= new CCPActionGroup(fPart),
new RefactorActionGroup(fPart),
new ImportActionGroup(fPart),
new GenerateActionGroup(fPart),
fBuildActionGroup= new BuildActionGroup(fPart),
new JavaSearchActionGroup(fPart),
new ProjectActionGroup(fPart),
fWorkingSetFilterActionGroup= new WorkingSetFilterActionGroup(part.getViewer(), JavaUI.ID_PACKAGES, shell, createTitleUpdater()),
new LayoutActionGroup(part)});
PackagesFrameSource frameSource= new PackagesFrameSource(fPart);
FrameList frameList= new FrameList(frameSource);
frameSource.connectTo(frameList);
fZoomInAction= new GoIntoAction(frameList);
fBackAction= new BackAction(frameList);
fForwardAction= new ForwardAction(frameList);
fUpAction= new UpAction(frameList);
fRenameResourceAction= new RenameResourceAction(shell);
fMoveResourceAction= new MoveResourceAction(shell);
fGotoTypeAction= new GotoTypeAction(fPart);
fGotoPackageAction= new GotoPackageAction(fPart);
fGotoResourceAction= new GotoResourceAction(fPart);
fCollapseAllAction= new CollapseAllAction(fPart);
fMemberFilterActionGroup= new MemberFilterActionGroup(fPart.getViewer(), "PackageView"); //$NON-NLS-1$
fCustomFiltersActionGroup= new CustomFiltersActionGroup(fPart, fPart.getViewer());
provider.addSelectionChangedListener(this);
update(selection);
}
public void dispose() {
if (fMemberFilterActionGroup != null) {
fMemberFilterActionGroup.dispose();
fMemberFilterActionGroup= null;
}
if (fCustomFiltersActionGroup != null) {
fCustomFiltersActionGroup.dispose();
fCustomFiltersActionGroup= null;
}
ISelectionProvider provider= fPart.getSite().getSelectionProvider();
provider.removeSelectionChangedListener(this);
super.dispose();
}
//---- Selection changed listener ---------------------------------------------------------
public void selectionChanged(SelectionChangedEvent event) {
fRenameResourceAction.selectionChanged(event);
fMoveResourceAction.selectionChanged(event);
IStructuredSelection selection= (IStructuredSelection)event.getSelection();
update(selection);
}
private void update(IStructuredSelection selection) {
int size= selection.size();
Object element= selection.getFirstElement();
IActionBars actionBars= fPart.getViewSite().getActionBars();
if (size == 1 && element instanceof IResource) {
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.RENAME, fRenameResourceAction);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.MOVE, fMoveResourceAction);
} else {
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.RENAME, null);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.MOVE, null);
}
actionBars.updateActionBars();
}
//---- Persistent state -----------------------------------------------------------------------
/* package */ void restoreState(IMemento memento) {
fMemberFilterActionGroup.restoreState(memento);
fWorkingSetFilterActionGroup.restoreState(memento);
fCustomFiltersActionGroup.restoreState(memento);
fPart.getViewer().getControl().setRedraw(false);
fPart.getViewer().refresh();
fPart.getViewer().getControl().setRedraw(true);
}
/* package */ void saveState(IMemento memento) {
fMemberFilterActionGroup.saveState(memento);
fWorkingSetFilterActionGroup.saveState(memento);
fCustomFiltersActionGroup.saveState(memento);
}
//---- Action Bars ----------------------------------------------------------------------------
public void fillActionBars(IActionBars actionBars) {
super.fillActionBars(actionBars);
setGlobalActionHandlers(actionBars);
fillToolBar(actionBars.getToolBarManager());
fillViewMenu(actionBars.getMenuManager());
fCustomFiltersActionGroup.fillActionBars(actionBars);
}
private void setGlobalActionHandlers(IActionBars actionBars) {
// Navigate Go Into and Go To actions.
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.GO_INTO, fZoomInAction);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.BACK, fBackAction);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.FORWARD, fForwardAction);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.UP, fUpAction);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.GO_TO_RESOURCE, fGotoResourceAction);
actionBars.setGlobalActionHandler(JdtActionConstants.GOTO_TYPE, fGotoTypeAction);
actionBars.setGlobalActionHandler(JdtActionConstants.GOTO_PACKAGE, fGotoPackageAction);
}
/* package */ void fillToolBar(IToolBarManager toolBar) {
toolBar.removeAll();
toolBar.add(fBackAction);
toolBar.add(fForwardAction);
toolBar.add(fUpAction);
if (showCompilationUnitChildren()) {
toolBar.add(new Separator());
fMemberFilterActionGroup.contributeToToolBar(toolBar);
}
toolBar.add(new Separator());
toolBar.add(fCollapseAllAction);
}
/* package */ void fillViewMenu(IMenuManager menu) {
menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS+"-end"));//$NON-NLS-1$
}
/* package */ void handleSelectionChanged(SelectionChangedEvent event) {
fZoomInAction.update();
}
//---- Context menu -------------------------------------------------------------------------
public void fillContextMenu(IMenuManager menu) {
IStructuredSelection selection= (IStructuredSelection)getContext().getSelection();
int size= selection.size();
Object element= selection.getFirstElement();
addGotoMenu(menu, element, size);
addOpenNewWindowAction(menu, element);
super.fillContextMenu(menu);
}
private void addGotoMenu(IMenuManager menu, Object element, int size) {
if (size == 1 && fPart.getViewer().isExpandable(element) && (isGoIntoTarget(element) || element instanceof IContainer))
menu.appendToGroup(IContextMenuConstants.GROUP_GOTO, fZoomInAction);
}
private boolean isNewTarget(IJavaElement element) {
if (element == null)
return false;
int type= element.getElementType();
return type == IJavaElement.JAVA_PROJECT ||
type == IJavaElement.PACKAGE_FRAGMENT_ROOT ||
type == IJavaElement.PACKAGE_FRAGMENT ||
type == IJavaElement.COMPILATION_UNIT ||
type == IJavaElement.TYPE;
}
private boolean isGoIntoTarget(Object element) {
if (element == null)
return false;
if (element instanceof IJavaElement) {
int type= ((IJavaElement)element).getElementType();
return type == IJavaElement.JAVA_PROJECT ||
type == IJavaElement.PACKAGE_FRAGMENT_ROOT ||
type == IJavaElement.PACKAGE_FRAGMENT;
}
return false;
}
private void addOpenNewWindowAction(IMenuManager menu, Object element) {
if (element instanceof IJavaElement) {
element= ((IJavaElement)element).getResource();
}
if (!(element instanceof IContainer))
return;
menu.appendToGroup(
IContextMenuConstants.GROUP_OPEN,
new OpenInNewWindowAction(fPart.getSite().getWorkbenchWindow(), (IContainer)element));
}
//---- Key board and mouse handling ------------------------------------------------------------
/* package*/ void handleDoubleClick(DoubleClickEvent event) {
TreeViewer viewer= fPart.getViewer();
Object element= ((IStructuredSelection)event.getSelection()).getFirstElement();
if (viewer.isExpandable(element)) {
if (doubleClickGoesInto()) {
// don't zoom into compilation units and class files
if (element instanceof IOpenable &&
!(element instanceof ICompilationUnit) &&
!(element instanceof IClassFile)) {
fZoomInAction.run();
}
} else {
if (element instanceof ICompilationUnit && OpenStrategy.getOpenMethod() == OpenStrategy.DOUBLE_CLICK)
return;
viewer.setExpandedState(element, !viewer.getExpandedState(element));
}
}
}
/* package */ void handleOpen(OpenEvent event) {
IAction openAction= fNavigateActionGroup.getOpenAction();
if (openAction != null && openAction.isEnabled()) {
openAction.run();
return;
}
}
/* package */ void handleKeyEvent(KeyEvent event) {
if (event.stateMask != 0)
return;
if (event.keyCode == SWT.F5) {
IAction refreshAction= fBuildActionGroup.getRefreshAction();
if (refreshAction != null && refreshAction.isEnabled())
refreshAction.run();
} else if (event.character == SWT.DEL) {
IAction delete= fCCPActionGroup.getDeleteAction();
if (delete != null && delete.isEnabled())
delete.run();
}
else if (event.keyCode == SWT.BS) {
if (fUpAction != null && fUpAction.isEnabled())
fUpAction.run();
}
}
private IPropertyChangeListener createTitleUpdater() {
return new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
String property= event.getProperty();
if (IWorkingSetManager.CHANGE_WORKING_SET_NAME_CHANGE.equals(property)) {
IWorkingSet workingSet= (IWorkingSet)event.getNewValue();
String workingSetName= null;
if (workingSet != null)
workingSetName= workingSet.getName();
fPart.setWorkingSetName(workingSetName);
fPart.updateTitle();
}
}
};
}
private boolean showCompilationUnitChildren() {
return PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.SHOW_CU_CHILDREN);
}
private boolean doubleClickGoesInto() {
return PreferenceConstants.DOUBLE_CLICK_GOES_INTO.equals(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.DOUBLE_CLICK));
}
}
|
27,764 |
Bug 27764 IResource.findMarkers is called too often
| null |
resolved fixed
|
aa5adb6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-10T10:19:21Z | 2002-12-05T14:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/PackageExplorerPart.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial implementation
******************************************************************************/
package org.eclipse.jdt.internal.ui.packageview;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.runtime.IPath;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.swt.widgets.Shell;
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.DecoratingLabelProvider;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ILabelDecorator;
import org.eclipse.jface.viewers.IOpenListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.ITreeViewerListener;
import org.eclipse.jface.viewers.OpenEvent;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeExpansionEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.part.ISetSelectionTarget;
import org.eclipse.ui.part.ResourceTransfer;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModel;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.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;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter;
import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer;
import org.eclipse.jdt.internal.ui.dnd.ResourceTransferDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.TransferDragSourceListener;
import org.eclipse.jdt.internal.ui.dnd.TransferDropTargetListener;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.javaeditor.IClassFileEditorInput;
import org.eclipse.jdt.internal.ui.javaeditor.JarEntryEditorInput;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.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;
/**
* The ViewPart for the ProjectExplorer. It listens to part activation events.
* When selection linking with the editor is enabled the view selection tracks
* the active editor page. Similarly when a resource is selected in the packages
* view the corresponding editor is activated.
*/
public class PackageExplorerPart extends ViewPart implements ISetSelectionTarget, IMenuListener, IPackagesViewPart, IPropertyChangeListener, IViewPartInputProvider {
private boolean fIsCurrentLayoutFlat; // true means flat, false means hierachical
private static final int HIERARCHICAL_LAYOUT= 0x1;
private static final int FLAT_LAYOUT= 0x2;
public final static String VIEW_ID= JavaUI.ID_PACKAGES;
// Persistance tags.
static final String TAG_SELECTION= "selection"; //$NON-NLS-1$
static final String TAG_EXPANDED= "expanded"; //$NON-NLS-1$
static final String TAG_ELEMENT= "element"; //$NON-NLS-1$
static final String TAG_PATH= "path"; //$NON-NLS-1$
static final String TAG_VERTICAL_POSITION= "verticalPosition"; //$NON-NLS-1$
static final String TAG_HORIZONTAL_POSITION= "horizontalPosition"; //$NON-NLS-1$
static final String TAG_FILTERS = "filters"; //$NON-NLS-1$
static final String TAG_FILTER = "filter"; //$NON-NLS-1$
static final String TAG_LAYOUT= "layout"; //$NON-NLS-1$
private PackageExplorerContentProvider fContentProvider;
private PackageExplorerActionGroup fActionSet;
private ProblemTreeViewer fViewer;
private Menu fContextMenu;
private IMemento fMemento;
private ISelectionChangedListener fSelectionListener;
private String fWorkingSetName;
private IPartListener fPartListener= new IPartListener() {
public void partActivated(IWorkbenchPart part) {
if (part instanceof IEditorPart)
editorActivated((IEditorPart) part);
}
public void partBroughtToTop(IWorkbenchPart part) {
}
public void partClosed(IWorkbenchPart part) {
}
public void partDeactivated(IWorkbenchPart part) {
}
public void partOpened(IWorkbenchPart part) {
}
};
private ITreeViewerListener fExpansionListener= new ITreeViewerListener() {
public void treeCollapsed(TreeExpansionEvent event) {
}
public void treeExpanded(TreeExpansionEvent event) {
Object element= event.getElement();
if (element instanceof ICompilationUnit ||
element instanceof IClassFile)
expandMainType(element);
}
};
private PackageExplorerLabelProvider fLabelProvider;
/* (non-Javadoc)
* Method declared on IViewPart.
*/
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() {
IViewPart view= JavaPlugin.getActivePage().findView(VIEW_ID);
if (view instanceof PackageExplorerPart)
return (PackageExplorerPart)view;
return null;
}
/**
* Makes the package explorer part visible in the active perspective. If there
* isn't a package explorer part registered <code>null</code> is returned.
* Otherwise the opened view part is returned.
*/
public static PackageExplorerPart openInActivePerspective() {
try {
return (PackageExplorerPart)JavaPlugin.getActivePage().showView(VIEW_ID);
} catch(PartInitException pe) {
return null;
}
}
public void dispose() {
if (fContextMenu != null && !fContextMenu.isDisposed())
fContextMenu.dispose();
getSite().getPage().removePartListener(fPartListener);
JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this);
if (fViewer != null)
fViewer.removeTreeListener(fExpansionListener);
if (fActionSet != null)
fActionSet.dispose();
super.dispose();
}
/**
* Implementation of IWorkbenchPart.createPartControl(Composite)
*/
public void createPartControl(Composite parent) {
fViewer= createViewer(parent);
setProviders();
JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this);
fViewer.setSorter(new JavaElementSorter());
fViewer.setUseHashlookup(true);
MenuManager menuMgr= new MenuManager("#PopupMenu"); //$NON-NLS-1$
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(this);
fContextMenu= menuMgr.createContextMenu(fViewer.getTree());
fViewer.getTree().setMenu(fContextMenu);
// Register viewer with site. This must be done before making the actions.
IWorkbenchPartSite site= getSite();
site.registerContextMenu(menuMgr, fViewer);
site.setSelectionProvider(fViewer);
site.getPage().addPartListener(fPartListener);
makeActions(); // call before registering for selection changes
// Set input after filter and sorter has been set. This avoids resorting
// and refiltering.
fViewer.setInput(findInputElement());
initDragAndDrop();
initKeyListener();
fSelectionListener= new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
handleSelectionChanged(event);
}
};
fViewer.addSelectionChangedListener(fSelectionListener);
fViewer.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
fActionSet.handleDoubleClick(event);
}
});
fViewer.addOpenListener(new IOpenListener() {
public void open(OpenEvent event) {
fActionSet.handleOpen(event);
}
});
IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager();
fViewer.addSelectionChangedListener(new StatusBarUpdater(slManager));
fViewer.addTreeListener(fExpansionListener);
if (fMemento != null)
restoreState(fMemento);
fMemento= null;
// Set help for the view
JavaUIHelp.setHelp(fViewer, IJavaHelpContextIds.PACKAGES_VIEW);
fillActionBars();
updateTitle();
}
/**
* This viewer ensures that non-leaves in the hierarchical
* layout are not removed by any filters.
*
* @since 2.1
*/
private ProblemTreeViewer createViewer(Composite parent) {
return new ProblemTreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL) {
/*
* @see org.eclipse.jface.viewers.StructuredViewer#filter(java.lang.Object)
*/
protected Object[] getFilteredChildren(Object parent) {
List list = new ArrayList();
ViewerFilter[] filters = fViewer.getFilters();
Object[] children = ((ITreeContentProvider) fViewer.getContentProvider()).getChildren(parent);
for (int i = 0; i < children.length; i++) {
Object object = children[i];
if (!isEssential(object)) {
object = filter(object, parent, filters);
if (object != null) {
list.add(object);
}
} else
list.add(object);
}
return list.toArray();
}
// Sends the object through the given filters
private Object filter(Object object, Object parent, ViewerFilter[] filters) {
for (int i = 0; i < filters.length; i++) {
ViewerFilter filter = filters[i];
if (!filter.select(fViewer, parent, object))
return null;
}
return object;
}
/* Checks if a filtered object in essential (ie. is a parent that
* should not be removed).
*/
private boolean isEssential(Object object) {
try {
if (!isFlatLayout() && object instanceof IPackageFragment) {
IPackageFragment fragment = (IPackageFragment) object;
return !fragment.isDefaultPackage() && fragment.hasSubpackages();
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
return false;
}
};
}
/**
* Answers whether this part shows the packages flat or hierarchical.
*
* @since 2.1
*/
boolean isFlatLayout() {
return fIsCurrentLayoutFlat;
}
private void setProviders() {
//content provider must be set before the label provider
fContentProvider= createContentProvider();
fContentProvider.setIsFlatLayout(fIsCurrentLayoutFlat);
fViewer.setContentProvider(fContentProvider);
fLabelProvider= createLabelProvider();
fLabelProvider.setIsFlatLayout(fIsCurrentLayoutFlat);
fViewer.setLabelProvider(new DecoratingLabelProvider(fLabelProvider, PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator()));
}
void toggleLayout() {
// Update current state and inform content and label providers
fIsCurrentLayoutFlat= !fIsCurrentLayoutFlat;
saveLayoutState(null);
fContentProvider.setIsFlatLayout(isFlatLayout());
fLabelProvider.setIsFlatLayout(isFlatLayout());
fViewer.getControl().setRedraw(false);
fViewer.refresh();
fViewer.getControl().setRedraw(true);
}
/**
* This method should only be called inside this class
* and from test cases.
*/
public PackageExplorerContentProvider createContentProvider() {
IPreferenceStore store= PreferenceConstants.getPreferenceStore();
boolean showCUChildren= store.getBoolean(PreferenceConstants.SHOW_CU_CHILDREN);
boolean reconcile= PreferenceConstants.UPDATE_WHILE_EDITING.equals(store.getString(PreferenceConstants.UPDATE_JAVA_VIEWS));
return new PackageExplorerContentProvider(showCUChildren, reconcile);
}
private PackageExplorerLabelProvider createLabelProvider() {
return new PackageExplorerLabelProvider(AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS | JavaElementLabels.P_COMPRESSED,
AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS | JavaElementImageProvider.SMALL_ICONS,
AppearanceAwareLabelProvider.getDecorators(true, null), 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) {
return JavaCore.create((IContainer)input);
}
//1GERPRT: ITPJUI:ALL - Packages View is empty when shown in Type Hierarchy Perspective
// we can't handle the input
// fall back to show the workspace
return JavaCore.create(JavaPlugin.getWorkspace().getRoot());
}
/**
* Answer the property defined by key.
*/
public Object getAdapter(Class key) {
if (key.equals(ISelectionProvider.class))
return fViewer;
return super.getAdapter(key);
}
/**
* Returns the tool tip text for the given element.
*/
String getToolTipText(Object element) {
String result;
if (!(element instanceof IResource)) {
result= JavaElementLabels.getTextLabel(element, 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 shell to use for opening dialogs.
* Used in this class, and in the actions.
*/
private Shell getShell() {
return fViewer.getTree().getShell();
}
/**
* Returns the selection provider.
*/
private ISelectionProvider getSelectionProvider() {
return fViewer;
}
/**
* Returns the current selection.
*/
private ISelection getSelection() {
return fViewer.getSelection();
}
//---- Action handling ----------------------------------------------------------
/**
* Called when the context menu is about to open. Override
* to add your own context dependent menu contributions.
*/
public void menuAboutToShow(IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
fActionSet.setContext(new ActionContext(getSelection()));
fActionSet.fillContextMenu(menu);
fActionSet.setContext(null);
}
private void makeActions() {
fActionSet= new PackageExplorerActionGroup(this);
}
private boolean isSelectionOfType(ISelection s, Class clazz, boolean considerUnderlyingResource) {
if (! (s instanceof IStructuredSelection) || s.isEmpty())
return false;
IStructuredSelection selection= (IStructuredSelection)s;
Iterator iter= selection.iterator();
while (iter.hasNext()) {
Object o= iter.next();
if (clazz.isInstance(o))
return true;
if (considerUnderlyingResource) {
if (! (o instanceof IJavaElement))
return false;
IJavaElement element= (IJavaElement)o;
Object resource= element.getAdapter(IResource.class);
if (! clazz.isInstance(resource))
return false;
}
}
return true;
}
//---- Event handling ----------------------------------------------------------
private void initDragAndDrop() {
int ops= DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK;
Transfer[] transfers= new Transfer[] {
LocalSelectionTransfer.getInstance(),
ResourceTransfer.getInstance(),
FileTransfer.getInstance()};
// Drop Adapter
TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] {
new SelectionTransferDropAdapter(fViewer),
new FileTransferDropAdapter(fViewer)
};
fViewer.addDropSupport(ops | DND.DROP_DEFAULT, transfers, new DelegatingDropAdapter(dropListeners));
// Drag Adapter
Control control= fViewer.getControl();
TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
new SelectionTransferDragAdapter(fViewer),
new ResourceTransferDragAdapter(fViewer),
new FileTransferDragAdapter(fViewer)
};
DragSource source= new DragSource(control, ops);
// Note, that the transfer agents are set by the delegating drag adapter itself.
source.addDragListener(new DelegatingDragAdapter(dragListeners) {
public void dragStart(DragSourceEvent event) {
IStructuredSelection selection= (IStructuredSelection)getSelection();
for (Iterator iter= selection.iterator(); iter.hasNext(); ) {
if (iter.next() instanceof IMember) {
setPossibleListeners(new TransferDragSourceListener[] {new SelectionTransferDragAdapter(fViewer)});
break;
}
}
super.dragStart(event);
}
});
}
/**
* Handles selection changed in viewer.
* Updates global actions.
* Links to editor (if option enabled)
*/
private void handleSelectionChanged(SelectionChangedEvent event) {
IStructuredSelection selection= (IStructuredSelection) event.getSelection();
fActionSet.handleSelectionChanged(event);
// if (OpenStrategy.getOpenMethod() != OpenStrategy.SINGLE_CLICK)
linkToEditor(selection);
}
public void selectReveal(ISelection selection) {
ISelection javaSelection= convertSelection(selection);
fViewer.setSelection(javaSelection, true);
if (javaSelection != selection && !javaSelection.equals(fViewer.getSelection()))
fViewer.setSelection(selection);
}
private ISelection convertSelection(ISelection s) {
if (!(s instanceof IStructuredSelection))
return s;
Object[] elements= ((StructuredSelection)s).toArray();
if (!containsResources(elements))
return s;
for (int i= 0; i < elements.length; i++) {
Object o= elements[i];
if (o instanceof IResource) {
IJavaElement jElement= JavaCore.create((IResource)o);
if (jElement != null)
elements[i]= jElement;
}
}
return new StructuredSelection(elements);
}
private boolean containsResources(Object[] elements) {
for (int i = 0; i < elements.length; i++) {
if (elements[i] instanceof IResource)
return true;
}
return false;
}
public void selectAndReveal(Object element) {
selectReveal(new StructuredSelection(element));
}
/**
* Returns whether the preference to link selection to active editor is enabled.
*/
boolean isLinkingEnabled() {
return 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);
// commented out because of http://bugs.eclipse.org/bugs/show_bug.cgi?id=4676
//saveScrollState(memento, fViewer.getTree());
fActionSet.saveState(memento);
}
/**
* 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());
}
}
}
void restoreState(IMemento memento) {
restoreExpansionState(memento);
restoreSelectionState(memento);
// commented out because of http://bugs.eclipse.org/bugs/show_bug.cgi?id=4676
//restoreScrollState(memento, fViewer.getTree());
fActionSet.restoreState(memento);
}
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;
Object input= getElementOfInput(editor.getEditorInput());
Object element= null;
if (input instanceof IFile)
element= JavaCore.create((IFile)input);
if (element == null) // try a non Java resource
element= input;
if (element != null) {
// if the current selection is a child of the new
// selection then ignore it.
IStructuredSelection oldSelection= (IStructuredSelection)getSelection();
if (oldSelection.size() == 1) {
Object o= oldSelection.getFirstElement();
if (o instanceof IJavaElement) {
ICompilationUnit cu= (ICompilationUnit)((IJavaElement)o).getAncestor(IJavaElement.COMPILATION_UNIT);
if (cu != null) {
if (cu.isWorkingCopy())
cu= (ICompilationUnit)cu.getOriginalElement();
if ( element.equals(cu))
return;
}
IClassFile cf= (IClassFile)((IJavaElement)o).getAncestor(IJavaElement.CLASS_FILE);
if (cf != null && element.equals(cf))
return;
}
}
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);
}
}
}
}
/**
* Returns the element's parent.
*
* @return the parent or <code>null</code> if there's no parent
*/
private Object getParent(Object element) {
if (element instanceof IJavaElement)
return ((IJavaElement)element).getParent();
else if (element instanceof IResource)
return ((IResource)element).getParent();
// else if (element instanceof IStorage) {
// can't get parent - see bug 22376
// }
return null;
}
/**
* A compilation unit or class was expanded, expand
* the main type.
*/
void expandMainType(Object element) {
try {
IType type= null;
if (element instanceof ICompilationUnit) {
ICompilationUnit cu= (ICompilationUnit)element;
IType[] types= cu.getTypes();
if (types.length > 0)
type= types[0];
}
else if (element instanceof IClassFile) {
IClassFile cf= (IClassFile)element;
type= cf.getType();
}
if (type != null) {
final IType type2= type;
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
ctrl.getDisplay().asyncExec(new Runnable() {
public void run() {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed())
fViewer.expandToLevel(type2, 1);
}
});
}
}
} catch(JavaModelException e) {
// no reveal
}
}
/**
* Returns the element contained in the EditorInput
*/
Object getElementOfInput(IEditorInput input) {
if (input instanceof IClassFileEditorInput)
return ((IClassFileEditorInput)input).getClassFile();
else if (input instanceof IFileEditorInput)
return ((IFileEditorInput)input).getFile();
else if (input instanceof JarEntryEditorInput)
return ((JarEntryEditorInput)input).getStorage();
return null;
}
/**
* Returns the Viewer.
*/
TreeViewer getViewer() {
return fViewer;
}
/**
* Returns the TreeViewer.
*/
public TreeViewer getTreeViewer() {
return fViewer;
}
boolean isExpandable(Object element) {
if (fViewer == null)
return false;
return fViewer.isExpandable(element);
}
void setWorkingSetName(String workingSetName) {
fWorkingSetName= workingSetName;
}
/**
* Updates the title text and title tool tip.
* Called whenever the input of the viewer changes.
*/
void updateTitle() {
Object input= fViewer.getInput();
String viewName= getConfigurationElement().getAttribute("name"); //$NON-NLS-1$
if (input == null
|| (input instanceof IJavaModel)) {
setTitle(viewName);
setTitleToolTip(""); //$NON-NLS-1$
} else {
String inputText= JavaElementLabels.getTextLabel(input, AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS);
String title= PackagesMessages.getFormattedString("PackageExplorer.argTitle", new String[] { viewName, inputText }); //$NON-NLS-1$
setTitle(title);
setTitleToolTip(getToolTipText(input));
}
}
/**
* Sets the decorator for the package explorer.
*
* @param decorator a label decorator or <code>null</code> for no decorations.
* @deprecated To be removed
*/
public void setLabelDecorator(ILabelDecorator decorator) {
}
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (fViewer == null)
return;
boolean refreshViewer= false;
if (PreferenceConstants.SHOW_CU_CHILDREN.equals(event.getProperty())) {
IActionBars actionBars= getViewSite().getActionBars();
fActionSet.fillToolBar(actionBars.getToolBarManager());
actionBars.updateActionBars();
boolean showCUChildren= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.SHOW_CU_CHILDREN);
((StandardJavaElementContentProvider)fViewer.getContentProvider()).setProvideMembers(showCUChildren);
refreshViewer= true;
} else if (PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER.equals(event.getProperty())) {
refreshViewer= true;
}
if (refreshViewer)
fViewer.refresh();
}
/* (non-Javadoc)
* @see IViewPartInputProvider#getViewPartInput()
*/
public Object getViewPartInput() {
if (fViewer != null) {
return fViewer.getInput();
}
return null;
}
public void collapseAll() {
fViewer.getControl().setRedraw(false);
fViewer.collapseToLevel(getViewPartInput(), TreeViewer.ALL_LEVELS);
fViewer.getControl().setRedraw(true);
}
public PackageExplorerPart() {
}
}
|
27,561 |
Bug 27561 ProblemsLabelDecorator.getErrorTicksFromWorkingCopy should avoid calling exists()
|
input for 20021203 calling exists() is expensive ironically, it may be cheaper to let the exception happen (we do not expect it to heppen to frequently), catch it and do the right thing will attach profile showing that method taking 8% of time needed to open java editor
|
resolved fixed
|
7da55fe
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-10T10:32:05Z | 2002-12-03T12:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/ProblemsLabelDecorator.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.ui;
import java.util.Iterator;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.util.ListenerList;
import org.eclipse.jface.viewers.IBaseLabelProvider;
import org.eclipse.jface.viewers.ILabelDecorator;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.LabelProviderChangedEvent;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.texteditor.MarkerAnnotation;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.viewsupport.IProblemChangedListener;
import org.eclipse.jdt.internal.ui.viewsupport.ImageDescriptorRegistry;
import org.eclipse.jdt.internal.ui.viewsupport.ImageImageDescriptor;
/**
* LabelDecorator that decorates an element's image with error and warning overlays that
* represent the severity of markers attached to the element's underlying resource. To see
* a problem decoration for a marker, the marker needs to be a subtype of <code>IMarker.PROBLEM</code>.
* <p>
* Note: Only images for elements in Java projects are currently updated on marker changes.
* </p>
*
* @since 2.0
*/
public class ProblemsLabelDecorator implements ILabelDecorator {
/**
* This is a special <code>LabelProviderChangedEvent</code> carring additional
* information whether the event orgins from a maker change.
* <p>
* <code>ProblemsLabelChangedEvent</code>s are only generated by <code>
* ProblemsLabelDecorator</code>s.
* </p>
*/
public static class ProblemsLabelChangedEvent extends LabelProviderChangedEvent {
private boolean fMarkerChange;
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*/
public ProblemsLabelChangedEvent(IBaseLabelProvider source, IResource[] changedResource, boolean isMarkerChange) {
super(source, changedResource);
fMarkerChange= isMarkerChange;
}
/**
* Returns whether this event origins from marker changes. If <code>false</code> an annotation
* model change is the origin. In this case viewers not displaying working copies can ignore these
* events.
*
* @return if this event origins from a marker change.
*/
public boolean isMarkerChange() {
return fMarkerChange;
}
}
private static final int ERRORTICK_WARNING= JavaElementImageDescriptor.WARNING;
private static final int ERRORTICK_ERROR= JavaElementImageDescriptor.ERROR;
private ImageDescriptorRegistry fRegistry;
private boolean fRegistryNeedsDispose= false;
private IProblemChangedListener fProblemChangedListener;
private ListenerList fListeners;
/**
* Creates a new <code>ProblemsLabelDecorator</code>.
*/
public ProblemsLabelDecorator() {
this(new ImageDescriptorRegistry());
fRegistryNeedsDispose= true;
}
/*
* Creates decorator with a shared image registry.
*
* @param registry The registry to use or <code>null</code> to use the Java plugin's
* image registry.
*/
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*/
public ProblemsLabelDecorator(ImageDescriptorRegistry registry) {
if (registry == null) {
registry= JavaPlugin.getImageDescriptorRegistry();
}
fRegistry= registry;
fProblemChangedListener= null;
}
/* (non-Javadoc)
* @see ILabelDecorator#decorateText(String, Object)
*/
public String decorateText(String text, Object element) {
return text;
}
/* (non-Javadoc)
* @see ILabelDecorator#decorateImage(Image, Object)
*/
public Image decorateImage(Image image, Object obj) {
int adornmentFlags= computeAdornmentFlags(obj);
if (adornmentFlags != 0) {
ImageDescriptor baseImage= new ImageImageDescriptor(image);
Rectangle bounds= image.getBounds();
return fRegistry.get(new JavaElementImageDescriptor(baseImage, adornmentFlags, new Point(bounds.width, bounds.height)));
}
return image;
}
protected int computeAdornmentFlags(Object obj) {
try {
if (obj instanceof IJavaElement) {
IJavaElement element= (IJavaElement) obj;
int type= element.getElementType();
switch (type) {
case IJavaElement.JAVA_PROJECT:
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
return getErrorTicksFromMarkers(element.getResource(), IResource.DEPTH_INFINITE, null);
case IJavaElement.PACKAGE_FRAGMENT:
case IJavaElement.CLASS_FILE:
return getErrorTicksFromMarkers(element.getResource(), IResource.DEPTH_ONE, null);
case IJavaElement.COMPILATION_UNIT:
case IJavaElement.PACKAGE_DECLARATION:
case IJavaElement.IMPORT_DECLARATION:
case IJavaElement.IMPORT_CONTAINER:
case IJavaElement.TYPE:
case IJavaElement.INITIALIZER:
case IJavaElement.METHOD:
case IJavaElement.FIELD:
ICompilationUnit cu= (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT);
if (cu != null) {
ISourceReference ref= (type == IJavaElement.COMPILATION_UNIT) ? null : (ISourceReference) element;
// The assumption is that only source elements in compilation unit can have markers
if (cu.isWorkingCopy()) {
// working copy: look at annotation model
return getErrorTicksFromWorkingCopy((ICompilationUnit) cu.getOriginalElement(), ref);
}
return getErrorTicksFromMarkers(cu.getResource(), IResource.DEPTH_ONE, ref);
}
break;
default:
}
} else if (obj instanceof IResource) {
return getErrorTicksFromMarkers((IResource) obj, IResource.DEPTH_INFINITE, null);
}
} catch (CoreException e) {
// http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
if (JavaModelUtil.filterNotPresentException(e))
JavaPlugin.log(e);
}
return 0;
}
private int getErrorTicksFromMarkers(IResource res, int depth, ISourceReference sourceElement) throws CoreException {
if (res == null || !res.isAccessible()) {
return 0;
}
int info= 0;
IMarker[] markers= res.findMarkers(IMarker.PROBLEM, true, depth);
if (markers != null) {
for (int i= 0; i < markers.length && (info != ERRORTICK_ERROR); i++) {
IMarker curr= markers[i];
if (sourceElement == null || isMarkerInRange(curr, sourceElement)) {
int priority= curr.getAttribute(IMarker.SEVERITY, -1);
if (priority == IMarker.SEVERITY_WARNING) {
info= ERRORTICK_WARNING;
} else if (priority == IMarker.SEVERITY_ERROR) {
info= ERRORTICK_ERROR;
}
}
}
}
return info;
}
private boolean isMarkerInRange(IMarker marker, ISourceReference sourceElement) throws CoreException {
if (marker.isSubtypeOf(IMarker.TEXT)) {
int pos= marker.getAttribute(IMarker.CHAR_START, -1);
return isInside(pos, sourceElement);
}
return false;
}
private int getErrorTicksFromWorkingCopy(ICompilationUnit original, ISourceReference sourceElement) throws CoreException {
int info= 0;
if (!original.exists()) {
return 0;
}
FileEditorInput editorInput= new FileEditorInput((IFile) original.getResource());
IAnnotationModel model= JavaPlugin.getDefault().getCompilationUnitDocumentProvider().getAnnotationModel(editorInput);
if (model != null) {
Iterator iter= model.getAnnotationIterator();
while ((info != ERRORTICK_ERROR) && iter.hasNext()) {
Annotation curr= (Annotation) iter.next();
IMarker marker= isAnnotationInRange(model, curr, sourceElement);
if (marker != null) {
int priority= marker.getAttribute(IMarker.SEVERITY, -1);
if (priority == IMarker.SEVERITY_WARNING) {
info= ERRORTICK_WARNING;
} else if (priority == IMarker.SEVERITY_ERROR) {
info= ERRORTICK_ERROR;
}
}
}
}
return info;
}
private IMarker isAnnotationInRange(IAnnotationModel model, Annotation annot, ISourceReference sourceElement) throws CoreException {
if (annot instanceof MarkerAnnotation) {
IMarker marker= ((MarkerAnnotation) annot).getMarker();
if (marker.exists() && marker.isSubtypeOf(IMarker.PROBLEM)) {
Position pos= model.getPosition(annot);
if (isInside(pos.getOffset(), sourceElement)) {
return marker;
}
}
}
return null;
}
/**
* Tests if a position is inside the source range of an element.
* @param pos Position to be tested.
* @param sourceElement Source element (must be a IJavaElement)
* @return boolean Return <code>true</code> if position is located inside the source element.
* @throws CoreException Exception thrown if element range could not be accessed.
*/
protected boolean isInside(int pos, ISourceReference sourceElement) throws CoreException {
ISourceRange range= sourceElement.getSourceRange();
int rangeOffset= range.getOffset();
return (rangeOffset <= pos && rangeOffset + range.getLength() > pos);
}
/* (non-Javadoc)
* @see IBaseLabelProvider#dispose()
*/
public void dispose() {
if (fProblemChangedListener != null) {
JavaPlugin.getDefault().getProblemMarkerManager().removeListener(fProblemChangedListener);
fProblemChangedListener= null;
}
if (fRegistryNeedsDispose) {
fRegistry.dispose();
}
}
/* (non-Javadoc)
* @see IBaseLabelProvider#isLabelProperty(Object, String)
*/
public boolean isLabelProperty(Object element, String property) {
return true;
}
/* (non-Javadoc)
* @see IBaseLabelProvider#addListener(ILabelProviderListener)
*/
public void addListener(ILabelProviderListener listener) {
if (fListeners == null) {
fListeners= new ListenerList();
}
fListeners.add(listener);
if (fProblemChangedListener == null) {
fProblemChangedListener= new IProblemChangedListener() {
public void problemsChanged(IResource[] changedResources, boolean isMarkerChange) {
fireProblemsChanged(changedResources, isMarkerChange);
}
};
JavaPlugin.getDefault().getProblemMarkerManager().addListener(fProblemChangedListener);
}
}
/* (non-Javadoc)
* @see IBaseLabelProvider#removeListener(ILabelProviderListener)
*/
public void removeListener(ILabelProviderListener listener) {
if (fListeners != null) {
fListeners.remove(listener);
if (fListeners.isEmpty() && fProblemChangedListener != null) {
JavaPlugin.getDefault().getProblemMarkerManager().removeListener(fProblemChangedListener);
fProblemChangedListener= null;
}
}
}
private void fireProblemsChanged(IResource[] changedResources, boolean isMarkerChange) {
if (fListeners != null && !fListeners.isEmpty()) {
LabelProviderChangedEvent event= new ProblemsLabelChangedEvent(this, changedResources, isMarkerChange);
Object[] listeners= fListeners.getListeners();
for (int i= 0; i < listeners.length; i++) {
((ILabelProviderListener) listeners[i]).labelProviderChanged(event);
}
}
}
}
|
27,194 |
Bug 27194 StringMatcher bug - matches too much
| null |
resolved fixed
|
7d6e4a3
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-11T16:20:27Z | 2002-11-26T22:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/util/StringMatcher.java
| |
28,102 |
Bug 28102 Folder not refreshed after adding a file
|
Build 20021210 Add "Eclipse JDT Builds" from CVS repository (ottcvs1) Open Package Explorer Switch to hierarchical layout Add a text file to "scripts" ==> it does not show up works with flat layout.
|
resolved fixed
|
9048e22
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-11T16:25:46Z | 2002-12-11T15:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/PackageExplorerContentProvider.java
|
/*
* (c) Copyright IBM Corp. 2000, 2002.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.packageview;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.swt.widgets.Control;
import org.eclipse.jface.viewers.IBasicPropertyConstants;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jdt.core.ElementChangedEvent;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IElementChangedListener;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaElementDelta;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IWorkingCopy;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.StandardJavaElementContentProvider;
import org.eclipse.jdt.internal.ui.JavaPlugin;
/**
* Content provider for the PackageExplorer.
*
* <p>
* Since 2.1 this content provider can provide the children for flat or hierarchical
* layout. The hierarchical layout is done by delegating to the <code>PackageFragmentProvider</code>.
* </p>
*
* @see org.eclipse.jdt.ui.StandardJavaElementContentProvider
* @see org.eclipse.jdt.internal.ui.packageview.PackageFragmentProvider
*/
class PackageExplorerContentProvider extends StandardJavaElementContentProvider implements ITreeContentProvider, IElementChangedListener {
protected TreeViewer fViewer;
protected Object fInput;
private boolean fIsFlatLayout;
private PackageFragmentProvider fPackageFragmentProvider= new PackageFragmentProvider();
/**
* Creates a new content provider for Java elements.
*/
public PackageExplorerContentProvider() {
}
/**
* Creates a new content provider for Java elements.
*/
public PackageExplorerContentProvider(boolean provideMembers, boolean provideWorkingCopy) {
super(provideMembers, provideWorkingCopy);
}
/* (non-Javadoc)
* Method declared on IElementChangedListener.
*/
public void elementChanged(final ElementChangedEvent event) {
try {
processDelta(event.getDelta());
} catch(JavaModelException e) {
JavaPlugin.log(e);
}
}
/* (non-Javadoc)
* Method declared on IContentProvider.
*/
public void dispose() {
super.dispose();
JavaCore.removeElementChangedListener(this);
fPackageFragmentProvider.dispose();
}
// ------ Code which delegates to PackageFragmentProvider ------
private boolean needsToDelegate(Object element) {
int type= -1;
if (element instanceof IJavaElement)
type= ((IJavaElement)element).getElementType();
return (!fIsFlatLayout && (type == IJavaElement.PACKAGE_FRAGMENT || type == IJavaElement.PACKAGE_FRAGMENT_ROOT || type == IJavaElement.JAVA_PROJECT));
}
public Object[] getChildren(Object parentElement) {
if (needsToDelegate(parentElement)) {
Object[] packageFragments= fPackageFragmentProvider.getChildren(parentElement);
return getWithParentsResources(packageFragments, parentElement);
} else
return super.getChildren(parentElement);
}
public Object getParent(Object child) {
if (needsToDelegate(child)) {
return fPackageFragmentProvider.getParent(child);
} else
return super.getParent(child);
}
/**
* Returns the given objects with the resources of the parent.
*/
private Object[] getWithParentsResources(Object[] existingObject, Object parent) {
Object[] objects= super.getChildren(parent);
List list= new ArrayList();
// Add everything that is not a PackageFragment
for (int i= 0; i < objects.length; i++) {
Object object= objects[i];
if (!(object instanceof IPackageFragment)) {
list.add(object);
}
}
if (existingObject != null)
list.addAll(Arrays.asList(existingObject));
return list.toArray();
}
/* (non-Javadoc)
* Method declared on IContentProvider.
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
super.inputChanged(viewer, oldInput, newInput);
fPackageFragmentProvider.inputChanged(viewer, oldInput, newInput);
fViewer= (TreeViewer)viewer;
if (oldInput == null && newInput != null) {
JavaCore.addElementChangedListener(this);
} else if (oldInput != null && newInput == null) {
JavaCore.removeElementChangedListener(this);
}
fInput= newInput;
}
// ------ delta processing ------
/**
* Processes a delta recursively. When more than two children are affected the
* tree is fully refreshed starting at this node. The delta is processed in the
* current thread but the viewer updates are posted to the UI thread.
*/
public void processDelta(IJavaElementDelta delta) throws JavaModelException {
int kind= delta.getKind();
int flags= delta.getFlags();
IJavaElement element= delta.getElement();
if(element.getElementType()!= IJavaElement.JAVA_MODEL && element.getElementType()!= IJavaElement.JAVA_PROJECT){
IJavaProject proj= element.getJavaProject();
if (proj == null || !proj.getProject().isOpen())
return;
}
if (!fIsFlatLayout && element.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
fPackageFragmentProvider.processDelta(delta);
IJavaElementDelta[] affectedChildren= delta.getAffectedChildren();
processAffectedChildren(affectedChildren);
return;
}
if (!getProvideWorkingCopy() && isWorkingCopy(element))
return;
if (element != null && element.getElementType() == IJavaElement.COMPILATION_UNIT && !isOnClassPath((ICompilationUnit)element))
return;
// handle open and closing of a solution or project
if (((flags & IJavaElementDelta.F_CLOSED) != 0) || ((flags & IJavaElementDelta.F_OPENED) != 0)) {
postRefresh(element);
return;
}
if (kind == IJavaElementDelta.REMOVED) {
// when a working copy is removed all we have to do
// is to refresh the compilation unit
if (isWorkingCopy(element)) {
refreshWorkingCopy((IWorkingCopy)element);
return;
}
Object parent= internalGetParent(element);
postRemove(element);
if (parent instanceof IPackageFragment)
postUpdateIcon((IPackageFragment)parent);
// we are filtering out empty subpackages, so we
// a package becomes empty we remove it from the viewer.
if (isPackageFragmentEmpty(element.getParent())) {
if (fViewer.testFindItem(parent) != null)
postRefresh(internalGetParent(parent));
}
return;
}
if (kind == IJavaElementDelta.ADDED) {
// when a working copy is added all we have to do
// is to refresh the compilation unit
if (isWorkingCopy(element)) {
refreshWorkingCopy((IWorkingCopy)element);
return;
}
Object parent= internalGetParent(element);
// we are filtering out empty subpackages, so we
// have to handle additions to them specially.
if (parent instanceof IPackageFragment) {
Object grandparent= internalGetParent(parent);
// 1GE8SI6: ITPJUI:WIN98 - Rename is not shown in Packages View
// avoid posting a refresh to an unvisible parent
if (parent.equals(fInput)) {
postRefresh(parent);
} else {
// refresh from grandparent if parent isn't visible yet
if (fViewer.testFindItem(parent) == null)
postRefresh(grandparent);
else {
postRefresh(parent);
}
}
return;
} else {
postAdd(parent, element);
}
}
if (element instanceof ICompilationUnit) {
if (getProvideWorkingCopy()) {
IJavaElement original= ((IWorkingCopy)element).getOriginalElement();
if (original != null)
element= original;
}
if (kind == IJavaElementDelta.CHANGED) {
postRefresh(element);
updateSelection(delta);
return;
}
}
// we don't show the contents of a compilation or IClassFile, so don't go any deeper
if ((element instanceof ICompilationUnit) || (element instanceof IClassFile))
return;
// the contents of an external JAR has changed
if (element instanceof IPackageFragmentRoot && ((flags & IJavaElementDelta.F_ARCHIVE_CONTENT_CHANGED) != 0)) {
postRefresh(element);
return;
}
// the source attachment of a JAR has changed
if (element instanceof IPackageFragmentRoot && (((flags & IJavaElementDelta.F_SOURCEATTACHED) != 0 || ((flags & IJavaElementDelta.F_SOURCEDETACHED)) != 0)))
postUpdateIcon(element);
if (isClassPathChange(delta)) {
// throw the towel and do a full refresh of the affected java project.
postRefresh(element.getJavaProject());
return;
}
if (processResourceDeltas(delta.getResourceDeltas(), element))
return;
handleAffectedChildren(delta, element);
}
private void handleAffectedChildren(IJavaElementDelta delta, IJavaElement element) throws JavaModelException {
IJavaElementDelta[] affectedChildren= delta.getAffectedChildren();
if (affectedChildren.length > 1) {
// a package fragment might become non empty refresh from the parent
if (element instanceof IPackageFragment) {
IJavaElement parent= (IJavaElement)internalGetParent(element);
// 1GE8SI6: ITPJUI:WIN98 - Rename is not shown in Packages View
// avoid posting a refresh to an unvisible parent
if (element.equals(fInput)) {
postRefresh(element);
} else {
postRefresh(parent);
}
return;
}
// more than one child changed, refresh from here downwards
if (element instanceof IPackageFragmentRoot)
postRefresh(skipProjectPackageFragmentRoot((IPackageFragmentRoot)element));
else
postRefresh(element);
return;
}
processAffectedChildren(affectedChildren);
}
protected void processAffectedChildren(IJavaElementDelta[] affectedChildren) throws JavaModelException {
for (int i= 0; i < affectedChildren.length; i++) {
processDelta(affectedChildren[i]);
}
}
private boolean isOnClassPath(ICompilationUnit element) throws JavaModelException {
IJavaProject project= element.getJavaProject();
if (project == null || !project.exists())
return false;
return project.isOnClasspath(element);
}
/**
* Updates the selection. It finds newly added elements
* and selects them.
*/
private void updateSelection(IJavaElementDelta delta) {
final IJavaElement addedElement= findAddedElement(delta);
if (addedElement != null) {
final StructuredSelection selection= new StructuredSelection(addedElement);
postRunnable(new Runnable() {
public void run() {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
// 19431
// if the item is already visible then select it
if (fViewer.testFindItem(addedElement) != null)
fViewer.setSelection(selection);
}
}
});
}
}
private IJavaElement findAddedElement(IJavaElementDelta delta) {
if (delta.getKind() == IJavaElementDelta.ADDED)
return delta.getElement();
IJavaElementDelta[] affectedChildren= delta.getAffectedChildren();
for (int i= 0; i < affectedChildren.length; i++)
return findAddedElement(affectedChildren[i]);
return null;
}
/**
* Refreshes the Compilation unit corresponding to the workging copy
* @param iWorkingCopy
*/
private void refreshWorkingCopy(IWorkingCopy workingCopy) {
IJavaElement original= workingCopy.getOriginalElement();
if (original != null)
postRefresh(original);
}
private boolean isWorkingCopy(IJavaElement element) {
return (element instanceof IWorkingCopy) && ((IWorkingCopy)element).isWorkingCopy();
}
/**
* Updates the package icon
*/
private void postUpdateIcon(final IJavaElement element) {
postRunnable(new Runnable() {
public void run() {
// 1GF87WR: ITPUI:ALL - SWTEx + NPE closing a workbench window.
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed())
fViewer.update(element, new String[]{IBasicPropertyConstants.P_IMAGE});
}
});
}
/**
1 * Process a resource delta.
*
* @return true if the parent got refreshed
*/
private boolean processResourceDelta(IResourceDelta delta, Object parent) {
int status= delta.getKind();
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);
}
processResourceDeltas(delta.getAffectedChildren(), resource);
return false;
}
/**
* 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(final Object root) {
postRunnable(new Runnable() {
public void run() {
// 1GF87WR: ITPUI:ALL - SWTEx + NPE closing a workbench window.
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()){
fViewer.refresh(root);
}
}
});
}
private void postAdd(final Object parent, final Object element) {
postRunnable(new Runnable() {
public void run() {
// 1GF87WR: ITPUI:ALL - SWTEx + NPE closing a workbench window.
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()){
fViewer.add(parent, element);
}
}
});
}
private void postRemove(final Object element) {
postRunnable(new Runnable() {
public void run() {
// 1GF87WR: ITPUI:ALL - SWTEx + NPE closing a workbench window.
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
fViewer.remove(element);
}
}
});
}
private void postRunnable(final Runnable r) {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
ctrl.getDisplay().asyncExec(r);
}
}
void setIsFlatLayout(boolean state) {
fIsFlatLayout= state;
}
}
|
28,152 |
Bug 28152 IAE when opening editor
|
Build 20021210 + plugin export 20021211 Got the following IAE when trying to open an editor. java.lang.IllegalArgumentException at org.eclipse.core.runtime.Preferences.setValue(Preferences.java:1164) at org.eclipse.ui.plugin.AbstractUIPlugin$CompatibilityPreferenceStore.setValue (AbstractUIPlugin.java:455) at org.eclipse.jdt.ui.JavaElementSorter$Cache.getOffsets (JavaElementSorter.java:122) at org.eclipse.jdt.ui.JavaElementSorter$Cache.getIndex (JavaElementSorter.java:111) at org.eclipse.jdt.ui.JavaElementSorter.getMemberCategory (JavaElementSorter.java:99) at org.eclipse.jdt.ui.JavaElementSorter.category (JavaElementSorter.java:205) at org.eclipse.jdt.ui.JavaElementSorter.compare (JavaElementSorter.java:247) at org.eclipse.jface.viewers.ViewerSorter$1.compare (ViewerSorter.java:163) at java.util.Arrays.mergeSort(Arrays.java:1181) at java.util.Arrays.sort(Arrays.java:1128) at org.eclipse.jface.viewers.ViewerSorter.sort(ViewerSorter.java:161) at org.eclipse.jface.viewers.StructuredViewer.getSortedChildren (StructuredViewer.java:447) at org.eclipse.jface.viewers.AbstractTreeViewer.createChildren (AbstractTreeViewer.java:250) at org.eclipse.jface.viewers.AbstractTreeViewer.internalExpand (AbstractTreeViewer.java:734) at org.eclipse.jface.viewers.AbstractTreeViewer.setSelectionToWidget (AbstractTreeViewer.java:1141) at org.eclipse.jface.viewers.StructuredViewer.setSelectionToWidget (StructuredViewer.java:933) at org.eclipse.jface.viewers.StructuredViewer.setSelection (StructuredViewer.java:898) at org.eclipse.jdt.internal.ui.javaeditor.JavaOutlinePage.select (JavaOutlinePage.java:1008) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor.synchronizeOutlineP ageSelection(CompilationUnitEditor.java:1951) at org.eclipse.jdt.internal.ui.javaeditor.JavaEditor$OutlinePageSelectionUpdater.ru n(JavaEditor.java:166) at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:31) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages (Synchronizer.java:94) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:1669) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1414) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1403) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1386) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539)
|
resolved fixed
|
2c39fc2
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-12T10:57:44Z | 2002-12-12T10:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/JavaElementSorter.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.ui;
import java.text.Collator;
import java.util.StringTokenizer;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IStorage;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.ContentViewer;
import org.eclipse.jface.viewers.IBaseLabelProvider;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IInitializer;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
/**
* Sorter for Java elements. Ordered by element category, then by element name.
* Package fragment roots are sorted as ordered on the classpath.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.0
*/
public class JavaElementSorter extends ViewerSorter {
private static final int JAVAPROJECTS= 1;
private static final int PACKAGEFRAGMENTROOTS= 2;
private static final int PACKAGEFRAGMENT= 3;
private static final int COMPILATIONUNITS= 4;
private static final int CLASSFILES= 5;
private static final int RESOURCEFOLDERS= 7;
private static final int RESOURCES= 8;
private static final int STORAGE= 9;
private static final int PACKAGE_DECL= 10;
private static final int IMPORT_CONTAINER= 11;
private static final int IMPORT_DECLARATION= 12;
// Includes all categories ordered using the OutlineSortOrderPage:
// types, initializers, methods & fields
private static final int MEMBERSOFFSET= 15;
private static final int JAVAELEMENTS= 50;
private static final int OTHERS= 51;
// cache for configurable member sort order
// index to cache array
private static final int TYPE_INDEX= 0;
private static final int CONSTRUCTORS_INDEX= 1;
private static final int METHOD_INDEX= 2;
private static final int FIELDS_INDEX= 3;
private static final int INIT_INDEX= 4;
private static final int STATIC_FIELDS_INDEX= 5;
private static final int STATIC_INIT_INDEX= 6;
private static final int STATIC_METHODS_INDEX= 7;
private static final int N_ENTRIES= STATIC_METHODS_INDEX + 1;
private static Cache fgCache= null;
private static int getMemberCategory(int kind) {
if (fgCache == null) {
fgCache= new Cache();
PreferenceConstants.getPreferenceStore().addPropertyChangeListener(fgCache);
}
return fgCache.getIndex(kind) + MEMBERSOFFSET;
}
private static class Cache implements IPropertyChangeListener {
private int[] fOffsets= null;
public void propertyChange(PropertyChangeEvent event) {
fOffsets= null;
}
public int getIndex(int kind) {
if (fOffsets == null) {
fOffsets= getOffsets();
}
return fOffsets[kind];
}
private int[] getOffsets() {
int[] offsets= new int[N_ENTRIES];
IPreferenceStore store= PreferenceConstants.getPreferenceStore();
String key= PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER;
boolean success= fillOffsetsFromPreferenceString(store.getString(key), offsets);
if (!success) {
store.setValue(key, null);
fillOffsetsFromPreferenceString(store.getDefaultString(key), offsets);
}
return offsets;
}
private boolean fillOffsetsFromPreferenceString(String str, int[] offsets) {
StringTokenizer tokenizer= new StringTokenizer(str, ","); //$NON-NLS-1$
int i= 0;
while (tokenizer.hasMoreTokens()) {
String token= tokenizer.nextToken().trim();
if ("T".equals(token)) {
offsets[TYPE_INDEX]= i++;
} else if ("M".equals(token)) {
offsets[METHOD_INDEX]= i++;
} else if ("F".equals(token)) {
offsets[FIELDS_INDEX]= i++;
} else if ("I".equals(token)) {
offsets[INIT_INDEX]= i++;
} else if ("SF".equals(token)) {
offsets[STATIC_FIELDS_INDEX]= i++;
} else if ("SI".equals(token)) {
offsets[STATIC_INIT_INDEX]= i++;
} else if ("SM".equals(token)) {
offsets[STATIC_METHODS_INDEX]= i++;
} else if ("C".equals(token)) {
offsets[CONSTRUCTORS_INDEX]= i++;
}
}
return i == N_ENTRIES;
}
}
public JavaElementSorter() {
super(null); // delay initialization of collator
}
/**
* @deprecated Bug 22518. Method never used: does not override ViewerSorter#isSorterProperty(Object, String).
* Method could be removed, but kept for API compatibility.
*/
public boolean isSorterProperty(Object element, Object property) {
return true;
}
/*
* @see ViewerSorter#category
*/
public int category(Object element) {
if (element instanceof IJavaElement) {
try {
IJavaElement je= (IJavaElement) element;
switch (je.getElementType()) {
case IJavaElement.METHOD:
{
IMethod method= (IMethod) je;
if (method.isConstructor()) {
return getMemberCategory(CONSTRUCTORS_INDEX);
}
int flags= method.getFlags();
if (Flags.isStatic(flags))
return getMemberCategory(STATIC_METHODS_INDEX);
else
return getMemberCategory(METHOD_INDEX);
}
case IJavaElement.FIELD :
{
int flags= ((IField) je).getFlags();
if (Flags.isStatic(flags))
return getMemberCategory(STATIC_FIELDS_INDEX);
else
return getMemberCategory(FIELDS_INDEX);
}
case IJavaElement.INITIALIZER :
{
int flags= ((IInitializer) je).getFlags();
if (Flags.isStatic(flags))
return getMemberCategory(STATIC_INIT_INDEX);
else
return getMemberCategory(INIT_INDEX);
}
case IJavaElement.TYPE :
return getMemberCategory(TYPE_INDEX);
case IJavaElement.PACKAGE_DECLARATION :
return PACKAGE_DECL;
case IJavaElement.IMPORT_CONTAINER :
return IMPORT_CONTAINER;
case IJavaElement.IMPORT_DECLARATION :
return IMPORT_DECLARATION;
case IJavaElement.PACKAGE_FRAGMENT :
IPackageFragment pack= (IPackageFragment) je;
if (pack.getParent().getResource() instanceof IProject) {
return PACKAGEFRAGMENTROOTS;
}
return PACKAGEFRAGMENT;
case IJavaElement.PACKAGE_FRAGMENT_ROOT :
return PACKAGEFRAGMENTROOTS;
case IJavaElement.JAVA_PROJECT :
return JAVAPROJECTS;
case IJavaElement.CLASS_FILE :
return CLASSFILES;
case IJavaElement.COMPILATION_UNIT :
return COMPILATIONUNITS;
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
return JAVAELEMENTS;
} else if (element instanceof IFile) {
return RESOURCES;
} else if (element instanceof IContainer) {
return RESOURCEFOLDERS;
} else if (element instanceof IStorage) {
return STORAGE;
}
return OTHERS;
}
/*
* @see ViewerSorter#compare
*/
public int compare(Viewer viewer, Object e1, Object e2) {
int cat1= category(e1);
int cat2= category(e2);
if (cat1 != cat2)
return cat1 - cat2;
if (cat1 == PACKAGEFRAGMENTROOTS) {
IPackageFragmentRoot root1= JavaModelUtil.getPackageFragmentRoot((IJavaElement)e1);
IPackageFragmentRoot root2= JavaModelUtil.getPackageFragmentRoot((IJavaElement)e2);
if (!root1.getPath().equals(root2.getPath())) {
int p1= getClassPathIndex(root1);
int p2= getClassPathIndex(root2);
if (p1 != p2) {
return p1 - p2;
}
}
}
// non - java resources are sorted using the label from the viewers label provider
if (cat1 == RESOURCES || cat1 == RESOURCEFOLDERS || cat1 == STORAGE || cat1 == OTHERS) {
return compareWithLabelProvider(viewer, e1, e2);
}
String name1= ((IJavaElement) e1).getElementName();
String name2= ((IJavaElement) e2).getElementName();
// java element are sorted by name
int cmp= getCollator().compare(name1, name2);
if (cmp != 0) {
return cmp;
}
if (e1 instanceof IMethod) {
String[] params1= ((IMethod) e1).getParameterTypes();
String[] params2= ((IMethod) e2).getParameterTypes();
int len= Math.min(params1.length, params2.length);
for (int i = 0; i < len; i++) {
cmp= getCollator().compare(Signature.toString(params1[i]), Signature.toString(params2[i]));
if (cmp != 0) {
return cmp;
}
}
return params1.length - params2.length;
}
return 0;
}
private int compareWithLabelProvider(Viewer viewer, Object e1, Object e2) {
if (viewer == null || !(viewer instanceof ContentViewer)) {
IBaseLabelProvider prov = ((ContentViewer) viewer).getLabelProvider();
if (prov instanceof ILabelProvider) {
ILabelProvider lprov= (ILabelProvider) prov;
String name1 = lprov.getText(e1);
String name2 = lprov.getText(e2);
if (name1 != null && name2 != null) {
return getCollator().compare(name1, name2);
}
}
}
return 0; // can't compare
}
private int getClassPathIndex(IPackageFragmentRoot root) {
try {
IPath rootPath= root.getPath();
IPackageFragmentRoot[] roots= root.getJavaProject().getPackageFragmentRoots();
for (int i= 0; i < roots.length; i++) {
if (roots[i].getPath().equals(rootPath)) {
return i;
}
}
} catch (JavaModelException e) {
}
return Integer.MAX_VALUE;
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ViewerSorter#getCollator()
*/
public final Collator getCollator() {
if (collator == null) {
collator= Collator.getInstance();
}
return collator;
}
}
|
27,687 |
Bug 27687 Jar export: Cannot export java project as a jar when manifest file is present
|
Steps to reproduce: 1. Create a java project 2. Create a simple folder in your project. Call it "META-INF". 3. Create a simple file in the META-INF folder. Call it "MANIFEST.MF". 4. In the context menu of your java project, click "Export" and select JAR file. 5. Fill in the export destination path and click Next. 6. Click Next again to go to the JAR Manifest Specification page of the wizard. The same thing happens whether you choose "Generate the manifest file" or "Use existing manifest from workspace" and select the file, then click Finish. The popup appears: Confirm Replace The file 'E:\eclipse_workbench\eclipse\workspace\Test.jar' already exists. Do you want to overwrite it? Yes No No: takes you back to the JAR Manifest Specification page of the JAR Export wizard. Yes: brings up the following error popup: JAR Export JAR creation failed. See details for additional information Details: Problem writing /<project name>/META-INF/MANIFEST.MF to JAR: duplicate entry: META-INF/MANIFEST.MF
|
resolved fixed
|
9f8dbe9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-12T16:55:25Z | 2002-12-04T19:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarpackager/JarFileExportOperation.java
|
/*
* (c) Copyright IBM Corp. 2000, 2002.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.jarpackager;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.Manifest;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.operation.ModalContext;
import org.eclipse.jface.util.Assert;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModelMarker;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.jarpackager.IJarDescriptionWriter;
import org.eclipse.jdt.ui.jarpackager.IJarExportRunnable;
import org.eclipse.jdt.ui.jarpackager.JarPackageData;
import org.eclipse.jdt.ui.jarpackager.JarWriter;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.IJavaStatusConstants;
import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
/**
* Operation for exporting a resource and its children to a new JAR file.
*/
public class JarFileExportOperation implements IJarExportRunnable {
private static class MessageMultiStatus extends MultiStatus {
MessageMultiStatus(String pluginId, int code, String message, Throwable exception) {
super(pluginId, code, message, exception);
}
/*
* allows to change the message
*/
protected void setMessage(String message) {
super.setMessage(message);
}
}
private JarWriter fJarWriter;
private JarPackageData fJarPackage;
private JarPackageData[] fJarPackages;
private Shell fParentShell;
private Map fJavaNameToClassFilesMap;
private IContainer fClassFilesMapContainer;
private Set fExportedClassContainers;
private MessageMultiStatus fStatus;
/**
* Creates an instance of this class.
*
* @param jarPackage the JAR package specification
* @param parent the parent for the dialog,
* or <code>null</code> if no dialog should be presented
*/
public JarFileExportOperation(JarPackageData jarPackage, Shell parent) {
this(new JarPackageData[] {jarPackage}, parent);
}
/**
* Creates an instance of this class.
*
* @param jarPackages an array with JAR package data objects
* @param parent the parent for the dialog,
* or <code>null</code> if no dialog should be presented
*/
public JarFileExportOperation(JarPackageData[] jarPackages, Shell parent) {
this(parent);
fJarPackages= jarPackages;
}
private JarFileExportOperation(Shell parent) {
fParentShell= parent;
fStatus= new MessageMultiStatus(JavaPlugin.getPluginId(), IStatus.OK, "", null); //$NON-NLS-1$
}
protected void addToStatus(CoreException ex) {
IStatus status= ex.getStatus();
String message= ex.getLocalizedMessage();
if (message == null || message.length() < 1) {
message= JarPackagerMessages.getString("JarFileExportOperation.coreErrorDuringExport"); //$NON-NLS-1$
status= new Status(status.getSeverity(), status.getPlugin(), status.getCode(), message, ex);
}
fStatus.add(status);
}
/**
* Adds a new info to the list with the passed information.
* Normally the export operation continues after a warning.
* @param message the message
* @param exception the throwable that caused the warning, or <code>null</code>
*/
protected void addInfo(String message, Throwable error) {
fStatus.add(new Status(IStatus.INFO, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, error));
}
/**
* Adds a new warning to the list with the passed information.
* Normally the export operation continues after a warning.
* @param message the message
* @param exception the throwable that caused the warning, or <code>null</code>
*/
protected void addWarning(String message, Throwable error) {
fStatus.add(new Status(IStatus.WARNING, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, error));
}
/**
* Adds a new error to the list with the passed information.
* Normally an error terminates the export operation.
* @param message the message
* @param exception the throwable that caused the error, or <code>null</code>
*/
protected void addError(String message, Throwable error) {
fStatus.add(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, error));
}
/**
* Answers the number of file resources specified by the JAR package.
*
* @return int
*/
protected int countSelectedElements() {
int count= 0;
int n= fJarPackage.getElements().length;
for (int i= 0; i < n; i++) {
Object element= fJarPackage.getElements()[i];
IResource resource= null;
if (element instanceof IJavaElement) {
IJavaElement je= (IJavaElement)element;
try {
resource= je.getUnderlyingResource();
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.underlyingResourceNotFound", je.getElementName()), ex); //$NON-NLS-1$
return count;
}
}
else
resource= (IResource)element;
if (resource.getType() == IResource.FILE)
count++;
else
count += getTotalChildCount((IContainer)resource);
}
return count;
}
private int getTotalChildCount(IContainer container) {
IResource[] members;
try {
members= container.members();
} catch (CoreException ex) {
return 0;
}
int count= 0;
for (int i= 0; i < members.length; i++) {
if (members[i].getType() == IResource.FILE)
count++;
else
count += getTotalChildCount((IContainer)members[i]);
}
return count;
}
/**
* Exports the passed resource to the JAR file
*
* @param element the resource or JavaElement to export
*/
protected void exportElement(Object element, IProgressMonitor progressMonitor) throws InterruptedException {
int leadSegmentsToRemove= 1;
IPackageFragmentRoot pkgRoot= null;
boolean isInJavaProject= false;
IResource resource= null;
IJavaProject jProject= null;
if (element instanceof IJavaElement) {
isInJavaProject= true;
IJavaElement je= (IJavaElement)element;
try {
resource= je.getUnderlyingResource();
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.underlyingResourceNotFound", je.getElementName()), ex); //$NON-NLS-1$
return;
}
jProject= je.getJavaProject();
pkgRoot= JavaModelUtil.getPackageFragmentRoot(je);
}
else
resource= (IResource)element;
if (!resource.isAccessible()) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.resourceNotFound", resource.getFullPath()), null); //$NON-NLS-1$
return;
}
if (resource.getType() == IResource.FILE) {
if (!resource.isLocal(IResource.DEPTH_ZERO))
try {
resource.setLocal(true , IResource.DEPTH_ZERO, progressMonitor);
} catch (CoreException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.resourceNotLocal", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
if (!isInJavaProject) {
// check if it's a Java resource
try {
isInJavaProject= resource.getProject().hasNature(JavaCore.NATURE_ID);
} catch (CoreException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.projectNatureNotDeterminable", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
if (isInJavaProject) {
jProject= JavaCore.create(resource.getProject());
try {
IPackageFragment pkgFragment= jProject.findPackageFragment(resource.getFullPath().removeLastSegments(1));
if (pkgFragment != null)
pkgRoot= JavaModelUtil.getPackageFragmentRoot(pkgFragment);
else
pkgRoot= findPackageFragmentRoot(jProject, resource.getFullPath().removeLastSegments(1));
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.javaPackageNotDeterminable", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
}
}
if (pkgRoot != null) {
leadSegmentsToRemove= pkgRoot.getPath().segmentCount();
if (mustUseSourceFolderHierarchy() && !pkgRoot.getElementName().equals(IPackageFragmentRoot.DEFAULT_PACKAGEROOT_PATH))
leadSegmentsToRemove--;
}
IPath destinationPath= resource.getFullPath().removeFirstSegments(leadSegmentsToRemove);
boolean isInOutputFolder= false;
if (isInJavaProject) {
try {
isInOutputFolder= jProject.getOutputLocation().isPrefixOf(resource.getFullPath());
} catch (JavaModelException ex) {
isInOutputFolder= false;
}
}
exportClassFiles(progressMonitor, pkgRoot, resource, jProject, destinationPath);
exportResource(progressMonitor, pkgRoot, isInJavaProject, resource, destinationPath, isInOutputFolder);
progressMonitor.worked(1);
ModalContext.checkCanceled(progressMonitor);
} else if (element instanceof IPackageFragment)
exportPackageFragment(progressMonitor, (IPackageFragment)element);
else
exportContainer(progressMonitor, (IContainer)resource);
}
private void exportPackageFragment(IProgressMonitor progressMonitor, IPackageFragment pkgFragment) throws java.lang.InterruptedException {
Object[] children;
try {
children= pkgFragment.getChildren();
for (int i= 0; i < children.length; i++)
exportElement(children[i], progressMonitor);
children= pkgFragment.getNonJavaResources();
for (int i= 0; i < children.length; i++)
exportElement(children[i], progressMonitor);
} catch (CoreException e) {
// this should never happen because an #isAccessible check is done before #members is invoked
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.errorDuringExport", pkgFragment.toString()), e); //$NON-NLS-1$
}
}
private void exportContainer(IProgressMonitor progressMonitor, IContainer container) throws java.lang.InterruptedException {
if (container.getType() == IResource.FOLDER && isOutputFolder((IFolder)container))
return;
IResource[] children= null;
try {
children= container.members();
} catch (CoreException e) {
// this should never happen because an #isAccessible check is done before #members is invoked
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.errorDuringExport", container.getFullPath()), e); //$NON-NLS-1$
}
for (int i= 0; i < children.length; i++)
exportElement(children[i], progressMonitor);
}
private IPackageFragmentRoot findPackageFragmentRoot(IJavaProject jProject, IPath path) throws JavaModelException {
if (jProject == null || path == null || path.segmentCount() <= 0)
return null;
IPackageFragmentRoot pkgRoot= jProject.findPackageFragmentRoot(path);
if (pkgRoot != null)
return pkgRoot;
else
return findPackageFragmentRoot(jProject, path.removeLastSegments(1));
}
private void exportResource(IProgressMonitor progressMonitor, IPackageFragmentRoot pkgRoot, boolean isInJavaProject, IResource resource, IPath destinationPath, boolean isInOutputFolder) {
boolean isNonJavaResource= !isInJavaProject || pkgRoot == null;
boolean isInClassFolder= false;
try {
isInClassFolder= pkgRoot != null && !pkgRoot.isArchive() && pkgRoot.getKind() == IPackageFragmentRoot.K_BINARY;
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.cantGetRootKind", resource.getFullPath()), ex); //$NON-NLS-1$
}
if ((fJarPackage.areClassFilesExported() &&
((isNonJavaResource || (pkgRoot != null && !isJavaFile(resource) && !isClassFile(resource)))
|| isInClassFolder && isClassFile(resource)))
|| (fJarPackage.areJavaFilesExported() && (isNonJavaResource || (pkgRoot != null && !isClassFile(resource))))) {
try {
progressMonitor.subTask(JarPackagerMessages.getFormattedString("JarFileExportOperation.exporting", destinationPath.toString())); //$NON-NLS-1$
fJarWriter.write((IFile) resource, destinationPath);
} catch (CoreException ex) {
addToStatus(ex);
}
}
}
private boolean isOutputFolder(IFolder folder) {
try {
IJavaProject javaProject= JavaCore.create(folder.getProject());
IPath outputFolderPath= javaProject.getOutputLocation();
return folder.getFullPath().equals(outputFolderPath);
} catch (JavaModelException ex) {
return false;
}
}
private void exportClassFiles(IProgressMonitor progressMonitor, IPackageFragmentRoot pkgRoot, IResource resource, IJavaProject jProject, IPath destinationPath) {
if (fJarPackage.areClassFilesExported() && isJavaFile(resource) && pkgRoot != null) {
try {
// find corresponding file(s) on classpath and export
Iterator iter= filesOnClasspath((IFile)resource, destinationPath, jProject, pkgRoot, progressMonitor);
IPath baseDestinationPath= destinationPath.removeLastSegments(1);
while (iter.hasNext()) {
IFile file= (IFile)iter.next();
if (!resource.isLocal(IResource.DEPTH_ZERO))
file.setLocal(true , IResource.DEPTH_ZERO, progressMonitor);
IPath classFilePath= baseDestinationPath.append(file.getName());
progressMonitor.subTask(JarPackagerMessages.getFormattedString("JarFileExportOperation.exporting", classFilePath.toString())); //$NON-NLS-1$
fJarWriter.write(file, classFilePath);
}
} catch (CoreException ex) {
addToStatus(ex);
}
}
}
/**
* Exports the resources as specified by the JAR package.
*/
protected void exportSelectedElements(IProgressMonitor progressMonitor) throws InterruptedException {
fExportedClassContainers= new HashSet(10);
int n= fJarPackage.getElements().length;
for (int i= 0; i < n; i++)
exportElement(fJarPackage.getElements()[i], progressMonitor);
}
/**
* Returns an iterator on a list with files that correspond to the
* passed file and that are on the classpath of its project.
*
* @param file the file for which to find the corresponding classpath resources
* @param pathInJar the path that the file has in the JAR (i.e. project and source folder segments removed)
* @param javaProject the javaProject that contains the file
* @return the iterator over the corresponding classpath files for the given file
* @deprecated As of 2.1 use the method with additional IPackageFragmentRoot paramter
*/
protected Iterator filesOnClasspath(IFile file, IPath pathInJar, IJavaProject javaProject, IProgressMonitor progressMonitor) throws CoreException {
return filesOnClasspath(file, pathInJar, javaProject, null, progressMonitor);
}
/**
* Returns an iterator on a list with files that correspond to the
* passed file and that are on the classpath of its project.
*
* @param file the file for which to find the corresponding classpath resources
* @param pathInJar the path that the file has in the JAR (i.e. project and source folder segments removed)
* @param javaProject the javaProject that contains the file
* @param pkgRoot the package fragment root that contains the file
* @return the iterator over the corresponding classpath files for the given file
*/
protected Iterator filesOnClasspath(IFile file, IPath pathInJar, IJavaProject javaProject, IPackageFragmentRoot pkgRoot, IProgressMonitor progressMonitor) throws CoreException {
// Allow JAR Package to provide its own strategy
IFile[] classFiles= fJarPackage.findClassfilesFor(file);
if (classFiles != null)
return Arrays.asList(classFiles).iterator();
if (!isJavaFile(file))
return Collections.EMPTY_LIST.iterator();
IPath outputPath= null;
if (pkgRoot != null) {
IClasspathEntry cpEntry= pkgRoot.getRawClasspathEntry();
if (cpEntry.getEntryKind() == IClasspathEntry.CPE_SOURCE)
outputPath= cpEntry.getOutputLocation();
}
if (outputPath == null)
// Use default output location
outputPath= javaProject.getOutputLocation();
IContainer outputContainer;
if (javaProject.getProject().getFullPath().equals(outputPath))
outputContainer= javaProject.getProject();
else {
outputContainer= createFolderHandle(outputPath);
if (outputContainer == null || !outputContainer.isAccessible()) {
String msg= JarPackagerMessages.getString("JarFileExportOperation.outputContainerNotAccessible"); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, msg, null));
}
}
// Java CU - search files with .class ending
boolean hasErrors= hasCompileErrors(file);
boolean hasWarnings= hasCompileWarnings(file);
boolean canBeExported= canBeExported(hasErrors, hasWarnings);
if (!canBeExported)
return Collections.EMPTY_LIST.iterator();
reportPossibleCompileProblems(file, hasErrors, hasWarnings, canBeExported);
IContainer classContainer= outputContainer;
if (pathInJar.segmentCount() > 1)
classContainer= outputContainer.getFolder(pathInJar.removeLastSegments(1));
if (fExportedClassContainers.contains(classContainer))
return Collections.EMPTY_LIST.iterator();
if (fClassFilesMapContainer == null || !fClassFilesMapContainer.equals(classContainer)) {
fJavaNameToClassFilesMap= buildJavaToClassMap(classContainer);
if (fJavaNameToClassFilesMap == null) {
// Could not fully build map. fallback is to export whole directory
String msg= JarPackagerMessages.getFormattedString("JarFileExportOperation.missingSourceFileAttributeExportedAll", classContainer.getLocation().toFile()); //$NON-NLS-1$
addInfo(msg, null);
fExportedClassContainers.add(classContainer);
return getClassesIn(classContainer);
}
fClassFilesMapContainer= classContainer;
}
ArrayList classFileList= (ArrayList)fJavaNameToClassFilesMap.get(file.getName());
if (classFileList == null || classFileList.isEmpty()) {
String msg= JarPackagerMessages.getFormattedString("JarFileExportOperation.classFileOnClasspathNotAccessible", file.getFullPath()); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, msg, null));
}
return classFileList.iterator();
}
private Iterator getClassesIn(IContainer classContainer) throws CoreException {
IResource[] resources= classContainer.members();
List files= new ArrayList(resources.length);
for (int i= 0; i < resources.length; i++)
if (resources[i].getType() == IResource.FILE && isClassFile(resources[i]))
files.add(resources[i]);
return files.iterator();
}
/**
* Answers whether the given resource is a Java file.
* The resource must be a file whose file name ends with ".java".
*
* @return a <code>true<code> if the given resource is a Java file
*/
boolean isJavaFile(IResource file) {
return file != null
&& file.getType() == IFile.FILE
&& file.getFileExtension() != null
&& file.getFileExtension().equalsIgnoreCase("java"); //$NON-NLS-1$
}
/**
* Answers whether the given resource is a class file.
* The resource must be a file whose file name ends with ".class".
*
* @return a <code>true<code> if the given resource is a class file
*/
boolean isClassFile(IResource file) {
return file != null
&& file.getType() == IFile.FILE
&& file.getFileExtension() != null
&& file.getFileExtension().equalsIgnoreCase("class"); //$NON-NLS-1$
}
/*
* Builds and returns a map that has the class files
* for each java file in a given directory
*/
private Map buildJavaToClassMap(IContainer container) throws CoreException {
if (!isCompilerGeneratingSourceFileAttribute())
return null;
if (container == null || !container.isAccessible())
return new HashMap(0);
/*
* XXX: Bug 6584: Need a way to get class files for a java file (or CU)
*/
org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader cfReader;
IResource[] members= container.members();
Map map= new HashMap(members.length);
for (int i= 0; i < members.length; i++) {
if (isClassFile(members[i])) {
IFile classFile= (IFile)members[i];
try {
cfReader= org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader.read(classFile.getLocation().toFile());
} catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.invalidClassFileFormat", classFile.getLocation().toFile()), ex); //$NON-NLS-1$
continue;
} catch (IOException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.ioErrorDuringClassFileLookup", classFile.getLocation().toFile()), ex); //$NON-NLS-1$
continue;
}
if (cfReader != null) {
if (cfReader.sourceFileName() == null) {
/*
* Can't fully build the map because one or more
* class file does not contain the name of its
* source file.
*/
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.classFileWithoutSourceFileAttribute", classFile.getLocation().toFile()), null); //$NON-NLS-1$
return null;
}
String javaName= new String(cfReader.sourceFileName());
Object classFiles= map.get(javaName);
if (classFiles == null) {
classFiles= new ArrayList(3);
map.put(javaName, classFiles);
}
((ArrayList)classFiles).add(classFile);
}
}
}
return map;
}
/**
* Creates a file resource handle for the file with the given workspace path.
* This method does not create the file resource; this is the responsibility
* of <code>createFile</code>.
*
* @param filePath the path of the file resource to create a handle for
* @return the new file resource handle
* @see #createFile
*/
protected IFile createFileHandle(IPath filePath) {
if (filePath.isValidPath(filePath.toString()) && filePath.segmentCount() >= 2)
return JavaPlugin.getWorkspace().getRoot().getFile(filePath);
else
return null;
}
/**
* Creates a folder resource handle for the folder with the given workspace path.
*
* @param folderPath the path of the folder to create a handle for
* @return the new folder resource handle
*/
protected IFolder createFolderHandle(IPath folderPath) {
if (folderPath.isValidPath(folderPath.toString()) && folderPath.segmentCount() >= 2)
return JavaPlugin.getWorkspace().getRoot().getFolder(folderPath);
else
return null;
}
/**
* Returns the status of this operation.
* The result is a status object containing individual
* status objects.
*
* @return the status of this operation
*/
public IStatus getStatus() {
String message= null;
switch (fStatus.getSeverity()) {
case IStatus.OK:
message= ""; //$NON-NLS-1$
break;
case IStatus.INFO:
message= JarPackagerMessages.getString("JarFileExportOperation.exportFinishedWithInfo"); //$NON-NLS-1$
break;
case IStatus.WARNING:
message= JarPackagerMessages.getString("JarFileExportOperation.exportFinishedWithWarnings"); //$NON-NLS-1$
break;
case IStatus.ERROR:
if (fJarPackages.length > 1)
message= JarPackagerMessages.getString("JarFileExportOperation.creationOfSomeJARsFailed"); //$NON-NLS-1$
else
message= JarPackagerMessages.getString("JarFileExportOperation.jarCreationFailed"); //$NON-NLS-1$
break;
default:
// defensive code in case new severity is defined
message= ""; //$NON-NLS-1$
break;
}
fStatus.setMessage(message);
return fStatus;
}
/**
* Answer a boolean indicating whether the passed child is a descendant
* of one or more members of the passed resources collection
*
* @param resources a List contain potential parents
* @param child the resource to test
* @return a <code>boolean</code> indicating if the child is a descendant
*/
protected boolean isDescendant(List resources, IResource child) {
if (child.getType() == IResource.PROJECT)
return false;
IResource parent= child.getParent();
if (resources.contains(parent))
return true;
return isDescendant(resources, parent);
}
protected boolean canBeExported(boolean hasErrors, boolean hasWarnings) throws CoreException {
return (!hasErrors && !hasWarnings)
|| (hasErrors && fJarPackage.areErrorsExported())
|| (hasWarnings && fJarPackage.exportWarnings());
}
protected void reportPossibleCompileProblems(IFile file, boolean hasErrors, boolean hasWarnings, boolean canBeExported) {
if (hasErrors) {
if (canBeExported)
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.exportedWithCompileErrors", file.getFullPath()), null); //$NON-NLS-1$
else
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.notExportedDueToCompileErrors", file.getFullPath()), null); //$NON-NLS-1$
}
if (hasWarnings) {
if (canBeExported)
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.exportedWithCompileWarnings", file.getFullPath()), null); //$NON-NLS-1$
else
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.notExportedDueToCompileWarnings", file.getFullPath()), null); //$NON-NLS-1$
}
}
/**
* Exports the resources as specified by the JAR package.
*
* @param progressMonitor the progress monitor that displays the progress
* @see #getStatus()
*/
public void run(IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException {
int count= fJarPackages.length;
progressMonitor.beginTask("", count); //$NON-NLS-1$
try {
for (int i= 0; i < count; i++) {
SubProgressMonitor subProgressMonitor= new SubProgressMonitor(progressMonitor, 1);
fJarPackage= fJarPackages[i];
if (fJarPackage != null)
singleRun(subProgressMonitor);
}
} finally {
progressMonitor.done();
}
}
public void singleRun(IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException {
try {
if (!preconditionsOK())
throw new InvocationTargetException(null, JarPackagerMessages.getString("JarFileExportOperation.jarCreationFailedSeeDetails")); //$NON-NLS-1$
int totalWork= countSelectedElements();
if (!isAutoBuilding() && fJarPackage.isBuildingIfNeeded() && fJarPackage.areClassFilesExported()) {
int subMonitorTicks= totalWork/10;
totalWork += subMonitorTicks;
progressMonitor.beginTask("", totalWork); //$NON-NLS-1$
SubProgressMonitor subProgressMonitor= new SubProgressMonitor(progressMonitor, subMonitorTicks, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
buildProjects(subProgressMonitor);
} else
progressMonitor.beginTask("", totalWork); //$NON-NLS-1$
fJarWriter= fJarPackage.createJarWriter(fParentShell);
exportSelectedElements(progressMonitor);
if (getStatus().getSeverity() != IStatus.ERROR) {
progressMonitor.subTask(JarPackagerMessages.getString("JarFileExportOperation.savingFiles")); //$NON-NLS-1$
saveFiles();
}
} catch (CoreException ex) {
addToStatus(ex);
} finally {
try {
if (fJarWriter != null)
fJarWriter.close();
} catch (CoreException ex) {
addToStatus(ex);
}
progressMonitor.done();
}
}
protected boolean preconditionsOK() {
if (!fJarPackage.areClassFilesExported() && !fJarPackage.areJavaFilesExported()) {
addError(JarPackagerMessages.getString("JarFileExportOperation.noExportTypeChosen"), null); //$NON-NLS-1$
return false;
}
if (fJarPackage.getElements() == null || fJarPackage.getElements().length == 0) {
addError(JarPackagerMessages.getString("JarFileExportOperation.noResourcesSelected"), null); //$NON-NLS-1$
return false;
}
if (fJarPackage.getJarLocation() == null) {
addError(JarPackagerMessages.getString("JarFileExportOperation.invalidJarLocation"), null); //$NON-NLS-1$
return false;
}
File targetFile= fJarPackage.getJarLocation().toFile();
if (targetFile.exists() && !targetFile.canWrite()) {
addError(JarPackagerMessages.getString("JarFileExportOperation.jarFileExistsAndNotWritable"), null); //$NON-NLS-1$
return false;
}
if (!fJarPackage.isManifestAccessible()) {
addError(JarPackagerMessages.getString("JarFileExportOperation.manifestDoesNotExist"), null); //$NON-NLS-1$
return false;
}
if (!fJarPackage.isMainClassValid(new BusyIndicatorRunnableContext())) {
addError(JarPackagerMessages.getString("JarFileExportOperation.invalidMainClass"), null); //$NON-NLS-1$
return false;
}
if (fParentShell == null)
// no checking if shell is null
return true;
IFile[] unsavedFiles= getUnsavedFiles();
if (unsavedFiles.length > 0)
return saveModifiedResourcesIfUserConfirms(unsavedFiles);
return true;
}
/**
* 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() {
IEditorPart[] dirtyEditors= getDirtyEditors(fParentShell);
Set unsavedFiles= new HashSet(dirtyEditors.length);
if (dirtyEditors.length > 0) {
List selection= JarPackagerUtil.asResources(fJarPackage.getElements());
for (int i= 0; i < dirtyEditors.length; i++) {
if (dirtyEditors[i].getEditorInput() instanceof IFileEditorInput) {
IFile dirtyFile= ((IFileEditorInput)dirtyEditors[i].getEditorInput()).getFile();
if (JarPackagerUtil.contains(selection, dirtyFile)) {
unsavedFiles.add(dirtyFile);
}
}
}
}
return (IFile[])unsavedFiles.toArray(new IFile[unsavedFiles.size()]);
}
/**
* 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= fParentShell.getDisplay();
if (display == null || display.isDisposed())
return false;
// Ask user to confirm saving of all files
final ConfirmSaveModifiedResourcesDialog dlg= new ConfirmSaveModifiedResourcesDialog(fParentShell, 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;
}
/**
* Asks to confirm to save the modified resources
* and save them if OK is pressed.
*
* @return true if user pressed OK and save was successful.
*/
private boolean saveModifiedResourcesIfUserConfirms(IFile[] dirtyFiles) {
if (confirmSaveModifiedResources(dirtyFiles))
return saveModifiedResources(dirtyFiles);
// Report unsaved files
for (int i= 0; i < dirtyFiles.length; i++)
addError(JarPackagerMessages.getFormattedString("JarFileExportOperation.fileUnsaved", dirtyFiles[i].getFullPath()), null); //$NON-NLS-1$
return false;
}
/**
* Save all of the editors in the workbench.
*
* @return true if successful.
*/
private boolean saveModifiedResources(final IFile[] dirtyFiles) {
// Get display for further UI operations
Display display= fParentShell.getDisplay();
if (display == null || display.isDisposed())
return false;
final boolean[] retVal= new boolean[1];
Runnable runnable= new Runnable() {
public void run() {
try {
new ProgressMonitorDialog(fParentShell).run(false, false, createSaveModifiedResourcesRunnable(dirtyFiles));
retVal[0]= true;
} catch (InvocationTargetException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingModifiedResources"), ex); //$NON-NLS-1$
JavaPlugin.log(ex);
retVal[0]= false;
} catch (InterruptedException ex) {
Assert.isTrue(false); // Can't happen. Operation isn't cancelable.
retVal[0]= false;
}
}
};
display.syncExec(runnable);
return retVal[0];
}
private IRunnableWithProgress createSaveModifiedResourcesRunnable(final IFile[] dirtyFiles) {
return new IRunnableWithProgress() {
public void run(final IProgressMonitor pm) {
IEditorPart[] editorsToSave= getDirtyEditors(fParentShell);
pm.beginTask(JarPackagerMessages.getString("JarFileExportOperation.savingModifiedResources"), editorsToSave.length); //$NON-NLS-1$
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();
}
}
};
}
protected void saveFiles() {
// Save the manifest
if (fJarPackage.areClassFilesExported() && fJarPackage.isManifestGenerated() && fJarPackage.isManifestSaved()) {
try {
saveManifest();
} catch (CoreException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingManifest"), ex); //$NON-NLS-1$
} catch (IOException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingManifest"), ex); //$NON-NLS-1$
}
}
// Save the description
if (fJarPackage.isDescriptionSaved()) {
try {
saveDescription();
} catch (CoreException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingDescription"), ex); //$NON-NLS-1$
} catch (IOException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingDescription"), ex); //$NON-NLS-1$
}
}
}
private IEditorPart[] getDirtyEditors(Shell parent) {
Display display= parent.getDisplay();
final Object[] result= new Object[1];
display.syncExec(
new Runnable() {
public void run() {
result[0]= JavaPlugin.getDirtyEditors();
}
}
);
return (IEditorPart[])result[0];
}
protected void saveDescription() throws CoreException, IOException {
// Adjust JAR package attributes
if (fJarPackage.isManifestReused())
fJarPackage.setGenerateManifest(false);
ByteArrayOutputStream objectStreamOutput= new ByteArrayOutputStream();
IJarDescriptionWriter writer= fJarPackage.createJarDescriptionWriter(objectStreamOutput);
ByteArrayInputStream fileInput= null;
try {
writer.write(fJarPackage);
fileInput= new ByteArrayInputStream(objectStreamOutput.toByteArray());
IFile descriptionFile= fJarPackage.getDescriptionFile();
if (descriptionFile.isAccessible()) {
if (fJarPackage.allowOverwrite() || JarPackagerUtil.askForOverwritePermission(fParentShell, descriptionFile.getFullPath().toString()))
descriptionFile.setContents(fileInput, true, true, null);
} else
descriptionFile.create(fileInput, true, null);
} finally {
if (fileInput != null)
fileInput.close();
if (writer != null)
writer.close();
}
}
protected void saveManifest() throws CoreException, IOException {
ByteArrayOutputStream manifestOutput= new ByteArrayOutputStream();
ByteArrayInputStream fileInput= null;
try {
Manifest manifest= fJarPackage.getManifestProvider().create(fJarPackage);
manifest.write(manifestOutput);
fileInput= new ByteArrayInputStream(manifestOutput.toByteArray());
IFile manifestFile= fJarPackage.getManifestFile();
if (manifestFile.isAccessible()) {
if (fJarPackage.allowOverwrite() || JarPackagerUtil.askForOverwritePermission(fParentShell, manifestFile.getFullPath().toString()))
manifestFile.setContents(fileInput, true, true, null);
} else
manifestFile.create(fileInput, true, null);
} finally {
if (manifestOutput != null)
manifestOutput.close();
if (fileInput != null)
fileInput.close();
}
}
private boolean isAutoBuilding() {
return ResourcesPlugin.getWorkspace().getDescription().isAutoBuilding();
}
private boolean isCompilerGeneratingSourceFileAttribute() {
Object value= JavaCore.getOptions().get(JavaCore.COMPILER_SOURCE_FILE_ATTR);
if (value instanceof String)
return "generate".equalsIgnoreCase((String)value); //$NON-NLS-1$
else
return true; // default
}
private void buildProjects(IProgressMonitor progressMonitor) {
Set builtProjects= new HashSet(10);
Object[] elements= fJarPackage.getElements();
for (int i= 0; i < elements.length; i++) {
IProject project= null;
Object element= elements[i];
if (element instanceof IResource)
project= ((IResource)element).getProject();
else if (element instanceof IJavaElement)
project= ((IJavaElement)element).getJavaProject().getProject();
if (project != null && !builtProjects.contains(project)) {
try {
project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, progressMonitor);
} catch (CoreException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.errorDuringProjectBuild", project.getFullPath()); //$NON-NLS-1$
addError(message, ex);
} finally {
// don't try to build same project a second time even if it failed
builtProjects.add(project);
}
}
}
}
/**
* Tells whether the given resource (or its children) have compile errors.
* The method acts on the current build state and does not recompile.
*
* @param resource the resource to check for errors
* @return <code>true</code> if the resource (and its children) are error free
* @throws import org.eclipse.core.runtime.CoreException if there's a marker problem
*/
private boolean hasCompileErrors(IResource resource) throws CoreException {
IMarker[] problemMarkers= resource.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE);
for (int i= 0; i < problemMarkers.length; i++) {
if (problemMarkers[i].getAttribute(IMarker.SEVERITY, -1) == IMarker.SEVERITY_ERROR)
return true;
}
return false;
}
/**
* Tells whether the given resource (or its children) have compile errors.
* The method acts on the current build state and does not recompile.
*
* @param resource the resource to check for errors
* @return <code>true</code> if the resource (and its children) are error free
* @throws import org.eclipse.core.runtime.CoreException if there's a marker problem
*/
private boolean hasCompileWarnings(IResource resource) throws CoreException {
IMarker[] problemMarkers= resource.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE);
for (int i= 0; i < problemMarkers.length; i++) {
if (problemMarkers[i].getAttribute(IMarker.SEVERITY, -1) == IMarker.SEVERITY_WARNING)
return true;
}
return false;
}
private boolean mustUseSourceFolderHierarchy() {
return fJarPackage.useSourceFolderHierarchy() && fJarPackage.areJavaFilesExported() && !fJarPackage.areClassFilesExported();
}
}
|
22,164 |
Bug 22164 Referencing JavaPlugin class in earlyStartup causes invalid thread access [misc]
|
It is possible that this is not a bug, either because it's known & not supported to because it's internal API, but it was rather unexpected, bizzare behavor. I have a plugin which depends on JDT-UI. This plugin also happens to implement IStartup. If at anypoint, I load the org.eclipse.jdt.internal.ui.JavaPlugin class from earlyStartup(), the Plugin loader attempts to load JDT-UI, which then promptly bombs out with invalid thread access and fails to load. This only happens if no JDT UI perspectives are loaded (in other words, on a fresh workspace). I will attach a simple plugin that demonstrates the problem. Just run it on a fresh workspace. The line it fails on seems to be "manager.registerAdapters(new JavaElementAdapterFactory(), IJavaElement.class);" in the startup() method. Thanks, Andrew
|
resolved fixed
|
faac42c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-12T18:27:54Z | 2002-08-05T12:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/JavaElementImageProvider.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.viewsupport;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.util.Assert;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.model.IWorkbenchAdapter;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaElementImageDescriptor;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
/**
* Default strategy of the Java plugin for the construction of Java element icons.
*/
public class JavaElementImageProvider {
/**
* Flags for the JavaImageLabelProvider:
* Generate images with overlays.
*/
public final static int OVERLAY_ICONS= 0x1;
/**
* Generate small sized images.
*/
public final static int SMALL_ICONS= 0x2;
/**
* Use the 'light' style for rendering types.
*/
public final static int LIGHT_TYPE_ICONS= 0x4;
public static final Point SMALL_SIZE= new Point(16, 16);
public static final Point BIG_SIZE= new Point(22, 16);
private static ImageDescriptor DESC_OBJ_PROJECT_CLOSED;
private static ImageDescriptor DESC_OBJ_PROJECT;
private static ImageDescriptor DESC_OBJ_FOLDER;
{
ISharedImages images= JavaPlugin.getDefault().getWorkbench().getSharedImages();
DESC_OBJ_PROJECT_CLOSED= images.getImageDescriptor(ISharedImages.IMG_OBJ_PROJECT_CLOSED);
DESC_OBJ_PROJECT= images.getImageDescriptor(ISharedImages.IMG_OBJ_PROJECT);
DESC_OBJ_FOLDER= images.getImageDescriptor(ISharedImages.IMG_OBJ_FOLDER);
}
private ImageDescriptorRegistry fRegistry;
public JavaElementImageProvider() {
fRegistry= JavaPlugin.getImageDescriptorRegistry();
}
/**
* Returns the icon for a given element. The icon depends on the element type
* and element properties. If configured, overlay icons are constructed for
* <code>ISourceReference</code>s.
* @param flags Flags as defined by the JavaImageLabelProvider
*/
public Image getImageLabel(Object element, int flags) {
return getImageLabel(computeDescriptor(element, flags));
}
private Image getImageLabel(ImageDescriptor descriptor){
if (descriptor == null)
return null;
return fRegistry.get(descriptor);
}
private ImageDescriptor computeDescriptor(Object element, int flags){
if (element instanceof IJavaElement) {
return getJavaImageDescriptor((IJavaElement) element, flags);
} else if (element instanceof IFile) {
IFile file= (IFile) element;
if ("java".equals(file.getFileExtension())) {
return getCUResourceImageDescriptor(file, flags); // image for a CU not on the build path
}
return getWorkbenchImageDescriptor(file, flags);
} else if (element instanceof IAdaptable) {
return getWorkbenchImageDescriptor((IAdaptable) element, flags);
}
return null;
}
private static boolean showOverlayIcons(int flags) {
return (flags & OVERLAY_ICONS) != 0;
}
private static boolean useSmallSize(int flags) {
return (flags & SMALL_ICONS) != 0;
}
private static boolean useLightIcons(int flags) {
return (flags & LIGHT_TYPE_ICONS) != 0;
}
/**
* Returns an image descriptor for a compilatio unit not on the class path.
* The descriptor includes overlays, if specified.
*/
public ImageDescriptor getCUResourceImageDescriptor(IFile file, int flags) {
Point size= useSmallSize(flags) ? SMALL_SIZE : BIG_SIZE;
return new JavaElementImageDescriptor(JavaPluginImages.DESC_OBJS_CUNIT_RESOURCE, 0, size);
}
/**
* Returns an image descriptor for a java element. The descriptor includes overlays, if specified.
*/
public ImageDescriptor getJavaImageDescriptor(IJavaElement element, int flags) {
int adornmentFlags= computeJavaAdornmentFlags(element, flags);
Point size= useSmallSize(flags) ? SMALL_SIZE : BIG_SIZE;
return new JavaElementImageDescriptor(getBaseImageDescriptor(element, flags), adornmentFlags, size);
}
/**
* Returns an image descriptor for a IAdaptable. The descriptor includes overlays, if specified (only error ticks apply).
* Returns <code>null</code> if no image could be found.
*/
public ImageDescriptor getWorkbenchImageDescriptor(IAdaptable adaptable, int flags) {
IWorkbenchAdapter wbAdapter= (IWorkbenchAdapter) adaptable.getAdapter(IWorkbenchAdapter.class);
if (wbAdapter == null) {
return null;
}
ImageDescriptor descriptor= wbAdapter.getImageDescriptor(adaptable);
if (descriptor == null) {
return null;
}
Point size= useSmallSize(flags) ? SMALL_SIZE : BIG_SIZE;
return new JavaElementImageDescriptor(descriptor, 0, size);
}
// ---- Computation of base image key -------------------------------------------------
/**
* Returns an image descriptor for a java element. This is the base image, no overlays.
*/
public ImageDescriptor getBaseImageDescriptor(IJavaElement element, int renderFlags) {
try {
switch (element.getElementType()) {
case IJavaElement.INITIALIZER:
return JavaPluginImages.DESC_MISC_PRIVATE; // 23479
case IJavaElement.METHOD:
IMember member= (IMember) element;
return getMethodImageDescriptor(member.getDeclaringType().isInterface(), member.getFlags());
case IJavaElement.FIELD:
IField field= (IField) element;
return getFieldImageDescriptor(field.getDeclaringType().isInterface(), field.getFlags());
case IJavaElement.PACKAGE_DECLARATION:
return JavaPluginImages.DESC_OBJS_PACKDECL;
case IJavaElement.IMPORT_DECLARATION:
return JavaPluginImages.DESC_OBJS_IMPDECL;
case IJavaElement.IMPORT_CONTAINER:
return JavaPluginImages.DESC_OBJS_IMPCONT;
case IJavaElement.TYPE: {
IType type= (IType) element;
boolean isInterface= type.isInterface();
if (useLightIcons(renderFlags)) {
return isInterface ? JavaPluginImages.DESC_OBJS_INTERFACEALT : JavaPluginImages.DESC_OBJS_CLASSALT;
}
boolean isInner= type.getDeclaringType() != null;
return getTypeImageDescriptor(isInterface, isInner, type.getFlags());
}
case IJavaElement.PACKAGE_FRAGMENT_ROOT: {
IPackageFragmentRoot root= (IPackageFragmentRoot) element;
if (root.isArchive()) {
IPath attach= root.getSourceAttachmentPath();
if (root.isExternal()) {
if (attach == null) {
return JavaPluginImages.DESC_OBJS_EXTJAR;
} else {
return JavaPluginImages.DESC_OBJS_EXTJAR_WSRC;
}
} else {
if (attach == null) {
return JavaPluginImages.DESC_OBJS_JAR;
} else {
return JavaPluginImages.DESC_OBJS_JAR_WSRC;
}
}
} else {
return JavaPluginImages.DESC_OBJS_PACKFRAG_ROOT;
}
}
case IJavaElement.PACKAGE_FRAGMENT:
return getPackageFragmentIcon(element, renderFlags);
case IJavaElement.COMPILATION_UNIT:
return JavaPluginImages.DESC_OBJS_CUNIT;
case IJavaElement.CLASS_FILE:
/* this is too expensive for large packages
try {
IClassFile cfile= (IClassFile)element;
if (cfile.isClass())
return JavaPluginImages.IMG_OBJS_CFILECLASS;
return JavaPluginImages.IMG_OBJS_CFILEINT;
} catch(JavaModelException e) {
// fall through;
}*/
return JavaPluginImages.DESC_OBJS_CFILE;
case IJavaElement.JAVA_PROJECT:
IJavaProject jp= (IJavaProject)element;
if (jp.getProject().isOpen()) {
IProject project= jp.getProject();
IWorkbenchAdapter adapter= (IWorkbenchAdapter)project.getAdapter(IWorkbenchAdapter.class);
if (adapter != null) {
ImageDescriptor result= adapter.getImageDescriptor(project);
if (result != null)
return result;
}
return DESC_OBJ_PROJECT;
}
return DESC_OBJ_PROJECT_CLOSED;
case IJavaElement.JAVA_MODEL:
return JavaPluginImages.DESC_OBJS_JAVA_MODEL;
}
Assert.isTrue(false, JavaUIMessages.getString("JavaImageLabelprovider.assert.wrongImage")); //$NON-NLS-1$
return null; //$NON-NLS-1$
} catch (JavaModelException e) {
if (!e.isDoesNotExist()) {
JavaPlugin.log(e);
}
return JavaPluginImages.DESC_OBJS_GHOST;
}
}
protected ImageDescriptor getPackageFragmentIcon(IJavaElement element, int renderFlags) throws JavaModelException {
IPackageFragment fragment= (IPackageFragment)element;
boolean containsJavaElements= false;
try {
containsJavaElements= fragment.hasChildren();
} catch(JavaModelException e) {
// assuming no children;
}
if(!containsJavaElements && (fragment.getNonJavaResources().length > 0))
return JavaPluginImages.DESC_OBJS_EMPTY_PACKAGE_RESOURCES;
else if (!containsJavaElements)
return JavaPluginImages.DESC_OBJS_EMPTY_PACKAGE;
return JavaPluginImages.DESC_OBJS_PACKAGE;
}
public void dispose() {
}
// ---- Methods to compute the adornments flags ---------------------------------
private int computeJavaAdornmentFlags(IJavaElement element, int renderFlags) {
int flags= 0;
if (showOverlayIcons(renderFlags) && element instanceof IMember) {
try {
IMember member= (IMember) element;
if (element.getElementType() == IJavaElement.METHOD && ((IMethod)element).isConstructor())
flags |= JavaElementImageDescriptor.CONSTRUCTOR;
int modifiers= member.getFlags();
if (Flags.isAbstract(modifiers) && confirmAbstract(member))
flags |= JavaElementImageDescriptor.ABSTRACT;
if (Flags.isFinal(modifiers) || isInterfaceField(member))
flags |= JavaElementImageDescriptor.FINAL;
if (Flags.isSynchronized(modifiers) && confirmSynchronized(member))
flags |= JavaElementImageDescriptor.SYNCHRONIZED;
if (Flags.isStatic(modifiers) || isInterfaceField(member))
flags |= JavaElementImageDescriptor.STATIC;
if (member.getElementType() == IJavaElement.TYPE) {
if (JavaModelUtil.hasMainMethod((IType) member)) {
flags |= JavaElementImageDescriptor.RUNNABLE;
}
}
} catch (JavaModelException e) {
// do nothing. Can't compute runnable adornment or get flags
}
}
return flags;
}
private static boolean confirmAbstract(IMember element) throws JavaModelException {
// never show the abstract symbol on interfaces or members in interfaces
if (element.getElementType() == IJavaElement.TYPE) {
return ((IType) element).isClass();
}
return element.getDeclaringType().isClass();
}
private static boolean isInterfaceField(IMember element) throws JavaModelException {
// always show the final && static symbol on interface fields
if (element.getElementType() == IJavaElement.FIELD) {
return element.getDeclaringType().isInterface();
}
return false;
}
private static boolean confirmSynchronized(IJavaElement member) {
// Synchronized types are allowed but meaningless.
return member.getElementType() != IJavaElement.TYPE;
}
public static ImageDescriptor getMethodImageDescriptor(boolean isInInterface, int flags) {
if (Flags.isPublic(flags) || isInInterface)
return JavaPluginImages.DESC_MISC_PUBLIC;
if (Flags.isProtected(flags))
return JavaPluginImages.DESC_MISC_PROTECTED;
if (Flags.isPrivate(flags))
return JavaPluginImages.DESC_MISC_PRIVATE;
return JavaPluginImages.DESC_MISC_DEFAULT;
}
public static ImageDescriptor getFieldImageDescriptor(boolean isInInterface, int flags) {
if (Flags.isPublic(flags) || isInInterface)
return JavaPluginImages.DESC_FIELD_PUBLIC;
if (Flags.isProtected(flags))
return JavaPluginImages.DESC_FIELD_PROTECTED;
if (Flags.isPrivate(flags))
return JavaPluginImages.DESC_FIELD_PRIVATE;
return JavaPluginImages.DESC_FIELD_DEFAULT;
}
public static ImageDescriptor getTypeImageDescriptor(boolean isInterface, boolean isInner, int flags) {
if (isInner) {
if (isInterface) {
return getInnerInterfaceImageDescriptor(flags);
} else {
return getInnerClassImageDescriptor(flags);
}
} else {
if (isInterface) {
return getInterfaceImageDescriptor(flags);
} else {
return getClassImageDescriptor(flags);
}
}
}
private static ImageDescriptor getClassImageDescriptor(int flags) {
if (Flags.isPublic(flags) || Flags.isProtected(flags) || Flags.isPrivate(flags))
return JavaPluginImages.DESC_OBJS_CLASS;
else
return JavaPluginImages.DESC_OBJS_CLASS_DEFAULT;
}
private static ImageDescriptor getInnerClassImageDescriptor(int flags) {
if (Flags.isPublic(flags))
return JavaPluginImages.DESC_OBJS_INNER_CLASS_PUBLIC;
else if (Flags.isPrivate(flags))
return JavaPluginImages.DESC_OBJS_INNER_CLASS_PRIVATE;
else if (Flags.isProtected(flags))
return JavaPluginImages.DESC_OBJS_INNER_CLASS_PROTECTED;
else
return JavaPluginImages.DESC_OBJS_INNER_CLASS_DEFAULT;
}
private static ImageDescriptor getInterfaceImageDescriptor(int flags) {
if (Flags.isPublic(flags) || Flags.isProtected(flags) || Flags.isPrivate(flags))
return JavaPluginImages.DESC_OBJS_INTERFACE;
else
return JavaPluginImages.DESC_OBJS_INTERFACE_DEFAULT;
}
private static ImageDescriptor getInnerInterfaceImageDescriptor(int flags) {
if (Flags.isPublic(flags))
return JavaPluginImages.DESC_OBJS_INNER_INTERFACE_PUBLIC;
else if (Flags.isPrivate(flags))
return JavaPluginImages.DESC_OBJS_INNER_INTERFACE_PRIVATE;
else if (Flags.isProtected(flags))
return JavaPluginImages.DESC_OBJS_INNER_INTERFACE_PROTECTED;
else
return JavaPluginImages.DESC_OBJS_INTERFACE_DEFAULT;
}
}
|
27,292 |
Bug 27292 FindActions should not call exists on selectionChanged
| null |
resolved fixed
|
e64822e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-13T09:58:14Z | 2002-11-28T10:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/FindAction.java
| |
27,429 |
Bug 27429 [Dialogs] Space usage of type info cache
| null |
closed fixed
|
3ae6b79
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-13T10:26:36Z | 2002-11-29T20:00:00Z |
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/TypeInfoTest.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.ui.tests.core;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipFile;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
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.testplugin.JavaProjectHelper;
import org.eclipse.jdt.testplugin.JavaTestPlugin;
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 suite() {
return new TestSuite(THIS);
}
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());
ZipFile zipfile= new ZipFile(junitSrcArchive);
JavaProjectHelper.addSourceContainerWithImport(fJProject2, "src", zipfile);
}
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);
}
}
}
}
|
27,429 |
Bug 27429 [Dialogs] Space usage of type info cache
| null |
closed fixed
|
3ae6b79
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-13T10:26:36Z | 2002-11-29T20:00:00Z |
org.eclipse.jdt.ui/core
| |
27,429 |
Bug 27429 [Dialogs] Space usage of type info cache
| null |
closed fixed
|
3ae6b79
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-13T10:26:36Z | 2002-11-29T20:00:00Z |
extension/org/eclipse/jdt/internal/corext/codemanipulation/OrganizeImportsOperation.java
| |
27,429 |
Bug 27429 [Dialogs] Space usage of type info cache
| null |
closed fixed
|
3ae6b79
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-13T10:26:36Z | 2002-11-29T20:00:00Z |
org.eclipse.jdt.ui/core
| |
27,429 |
Bug 27429 [Dialogs] Space usage of type info cache
| null |
closed fixed
|
3ae6b79
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-13T10:26:36Z | 2002-11-29T20:00:00Z |
extension/org/eclipse/jdt/internal/corext/util/AllTypesCache.java
| |
27,429 |
Bug 27429 [Dialogs] Space usage of type info cache
| null |
closed fixed
|
3ae6b79
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-13T10:26:36Z | 2002-11-29T20:00:00Z |
org.eclipse.jdt.ui/core
| |
27,429 |
Bug 27429 [Dialogs] Space usage of type info cache
| null |
closed fixed
|
3ae6b79
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-13T10:26:36Z | 2002-11-29T20:00:00Z |
extension/org/eclipse/jdt/internal/corext/util/IFileTypeInfo.java
| |
27,429 |
Bug 27429 [Dialogs] Space usage of type info cache
| null |
closed fixed
|
3ae6b79
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-13T10:26:36Z | 2002-11-29T20:00:00Z |
org.eclipse.jdt.ui/core
| |
27,429 |
Bug 27429 [Dialogs] Space usage of type info cache
| null |
closed fixed
|
3ae6b79
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-13T10:26:36Z | 2002-11-29T20:00:00Z |
extension/org/eclipse/jdt/internal/corext/util/JarFileEntryTypeInfo.java
| |
27,429 |
Bug 27429 [Dialogs] Space usage of type info cache
| null |
closed fixed
|
3ae6b79
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-13T10:26:36Z | 2002-11-29T20:00:00Z |
org.eclipse.jdt.ui/core
| |
27,429 |
Bug 27429 [Dialogs] Space usage of type info cache
| null |
closed fixed
|
3ae6b79
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-13T10:26:36Z | 2002-11-29T20:00:00Z |
extension/org/eclipse/jdt/internal/corext/util/Strings.java
| |
27,429 |
Bug 27429 [Dialogs] Space usage of type info cache
| null |
closed fixed
|
3ae6b79
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-12-13T10:26:36Z | 2002-11-29T20:00:00Z |
org.eclipse.jdt.ui/core
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.