How to set the background colour of elements according to their visibility modifier in Eclipse? - eclipse

I'd like to set the background colour of fields and methods (on the first level) according to their visibility modifier in Eclipse.
For example private fields and methods should get a red background, while public fields and methods get a green background:
Is there a way to configure this in Eclipse?

To get this sort of a colored background, you need to use Markers and MarkerAnnotationSpecification. You will find how to use them here: http://cubussapiens.hu/2011/05/custom-markers-and-annotations-the-bright-side-of-eclipse/
As for how to find the private, public fields, you need to use the JDT plugin and the AST parser to parse the Java file and find all the information that you want. I am adding a small code snippet to get you started on this.
ASTParser parser = ASTParser.newParser(AST_LEVEL);
parser.setSource(cmpUnit);
parser.setResolveBindings(true);
CompilationUnit astRoot = (CompilationUnit) parser.createAST(null);
AST ast = astRoot.getAST();
TypeDeclaration javaType = null;
Object type = astRoot.types().get(0);
if (type instanceof TypeDeclaration) {
javaType = ((TypeDeclaration) type);
}
List<FieldDeclarationInfo> fieldDeclarations = new ArrayList<FieldDeclarationInfo>();
// Get the field info
for (FieldDeclaration fieldDeclaration : javaType.getFields()) {
// From this object you can recover all the information that you want about the fields.
}
Here cmpUnit is the ICompilationUnit of the Java File.

Related

TextCellEditor with autocomplete in Eclipse SWT/JFace?

I'd like a TextCellEditor with the standard auto-complete behaviour, that that any user nowadays expects when typing inside an input cell with a list of suggested strings. For a good working example of what I'm after, in Javascript, see this jQuery autocomplete widget.
I couldn't find a good example.
I only found (aside from some tiny variations) this TextCellEditorWithContentProposal snippet. But that leaves a lot to be desired:
It lists all the words, irrespective of the "partial word" typed in the cell (no partial matching)
When the desired word is selected, it is appended to the partial word, instead of replacing it
The interaction is ugly and non-intuitive. For example, one would expect the
Escape key to tear off the list of suggestions; again, see the Javascript example; here, it also removes the typed letters.
It looks strange to me that such an standard and useful component is not available. Or perhaps it is available? Can someone point to me to a more apt snippet or example?
The example you are linking to is a code snippet intended to showcase the API and guide you toward customizing the control to your preference.
Some of your complaints are either invalid or can easily be fixed using public API.
Let's go through them in detail.
All proposals are listed, irrespective of typed text
Note that in the snippet an org.eclipse.jface.fieldassist.SimpleContentProposalProvider is used:
IContentProposalProvider contentProposalProvider = new SimpleContentProposalProvider(new String[] { "red",
"green", "blue" });
cellEditor = new TextCellEditorWithContentProposal(viewer.getTable(), contentProposalProvider, null, null);
As suggested in its javadoc it is:
designed to map a static list of Strings to content proposals
To enable a simple filtering of the contents for the snippet, you could call: contentProposalProvider.setFiltering(true);
For anything more complex you will have to replace this with your own implementation of org.eclipse.jface.fieldassist.IContentProposalProvider.
Selection is appended to cell contents, instead of replacing it
The content proposal behavior is defined in the org.eclipse.jface.fieldassist.ContentProposalAdapter. Again a simple method call to org.eclipse.jface.fieldassist.ContentProposalAdapter.setProposalAcceptanceStyle(int) will achieve your target behavior:
contentProposalAdapter = new ContentProposalAdapter(text, new TextContentAdapter(), contentProposalProvider, keyStroke, autoActivationCharacters);
contentProposalAdapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE);
Cancelling the proposal should not remove typed content
This is hard to do using just the API, since the ContentProposalAdapter does only propagate the key strokes to the opened ContentProposalPopup without storing them.
You would have to subclass ContentProposalAdapter, in order to have access to ContentProposalAdapter.ContentProposalPopup.filterText.
Most of the functionality in this snippet with sensible defaults can also be obtained in a more simple way by using an org.eclipse.jface.fieldassist.AutoCompleteField.
Here is a snippet showing you a simple implementation. You have to customize it but it give you the way.
Note, this is not a generic copy/paste of the documentation or an explanation about the doc.
String[] contentProposals = {"text", "test", "generated"};
// simple content provider based on string array
SimpleContentProposalProvider provider = new SimpleContentProposalProvider(contentProposals);
// enable filtering or disabled it if you are using your own implementation
provider.setFiltering(false);
// content adapter with no keywords and caracters filtering
ContentProposalAdapter adapter = new ContentProposalAdapter(yourcontrolswt, new TextContentAdapter(), provider, null, null);
// you should not replace text content, you will to it bellow
adapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_IGNORE);
// now just put your implementation
adapter.addContentProposalListener(new IContentProposalListener() {
#Override
public void proposalAccepted(IContentProposal proposal) {
if(proposal != null && StringUtils.isNotBlank(proposal.getContent())){
// you need filter with blank spaces
String contentTextField = getFilterControl().getText();
String[] currentWords = getFilterControl().getText().split(" ");
StringBuilder textToDisplay = new StringBuilder();
if(currentWords.length > 1) {
// delete and replace last word
String lastWord = currentWords[currentWords.length-1];
textToDisplay.append(contentTextField.substring(0, contentTextField.length()-1-lastWord.length()));
textToDisplay.append(" ");
}
// add current proposal to control text content
textToDisplay.append(proposal.getContent());
yourcontrolswt.setText(textToDisplay.toString());
}
}
});
If you want more you can also have your own content proposal provider If you need a particular object instead of string or something like.
public class SubstringMatchContentProposalProvider implements IContentProposalProvider {
private List<String> proposals = Collections.emptyList();
#Override
public IContentProposal[] getProposals(String contents, int position) {
if (position == 0) {
return null;
}
String[] allWords = contents.split(" ");
// no words available
if(allWords.length == 0 || StringUtils.isBlank(allWords[allWords.length-1]))
return null;
// auto completion on last word found
String lastWordFound = allWords[allWords.length-1];
Pattern pattern = Pattern.compile(lastWordFound,
Pattern.LITERAL | Pattern.CASE_INSENSITIVE /*| Pattern.UNICODE_CASE*/); // this should be not used for better performances
IContentProposal[] filteredProposals = proposals.stream()
.filter(proposal -> proposal.length() >= lastWordFound.length() && pattern.matcher(proposal).find())
.map(ContentProposal::new).toArray(IContentProposal[]::new);
// no result
return filteredProposals.length == 0 ? null : filteredProposals;
}
public void setProposals(List<String> proposals) {
this.proposals = proposals;
}
}

Eclipse JDT static field modifiers

I want to get the information about a field modifier. To be precise, I want to find out is the field a static one. For example, I want to examine the following code:
ASTParser parser = ASTParser.newParser(AST.JLS3);
How can I infer that the JLS3 is static field? I used getModifiers with Modifier.isStatic when analyzing methods and it worked fine. However, now I am not able to get the information that JLS3 in above code snippet is a static field. Is there something I am missing?
EDIT:
This is the code that I am using:
private boolean visit(SimpleName name){
boolean isStatic = Modifier.isStatic(name.resolveTypeBinding().getModifiers());
...
return true;
}
isStatic is false in the case of JLS3.
That's obviously wrong, use name.resolveBinding() instead of name.resolveTypeBinding() --- so you should get an object of type IVariableBinding.
name.resolveTypeBinding() returns the binding for the type of the field, but not the binding of field itself, which is not what you want here.

Display all enums from an EMF model in a CheckBoxTable ?

I am trying to display a CheckBoxTable in an Eclipse page which enables the user to select any one of a number of items - the items that are available come from an EMF model and are enums.
I've got the content provider and the label provider set up correctly (I think) but I can't figure what to use to set the input in order to display the full list of enums.
So say my model has an enum called MyEnum which has values of ONE, TWO and THREE - I want to be able to display all three of those enums to the user as check boxes.
I need to call setInput(...) on the viewer but what do I pass into it to get those enums?
Although I've never done it for a CheckboxTableViewer, I have set an EEnum as the source of values for other StructuredViewer classes like ComboViewer. What I did was create a custom IStructuredContentProvider that is a subclass of ArrayList and takes the EEnum as a constructor argument (call this class EEnumContentProvider). In the constructor, I iterate over the EEnum's getELiterals() and call add() on each of their getInstance() values. Like this:
public EEnumContentProvider(EEnum source) {
List<EEnumLiteral> literals = source.getELiterals();
for (EEnumLiteral aLiteral : literals) {
add(aLiteral.getInstance());
}
}
You can easily implement IStructuredContentProvider.getElements(Object) by using returning the result of toArray() and you don't care about IContentProvider.setInput() because the contents aren't based on the input, they're static.
Then you can set an instance of EEnumContentProvider as the content provider for the viewer.
Simply you need to get the literals and add them to the control as follows:
/* Populate the Combo Box with the Literals */
EEnum cFEnum = Package.Literals.LITERAL_ENUMERATION;
/*
* Add an EMPTY item value so that the user can disable the specific
* feature
*/
this.cmbNames.add( EMPTY_STRING );
/*
* Add the Enumeration Literals to the
* appropriate SWT Combo widget.
*/
for (int i=0; i<cFEnum.getELiterals().size(); i++){
this.cmbNames.add( cFEnum.getEEnumLiteral( i ).toString() );
}
cFEnum = null;
String[] sortedTypes = this.cmbNames.getItems();
Arrays.sort( sortedTypes );
this.cmbNames.setItems( sortedTypes );

How could I search references to a field on a AST or a CompilationUnit in eclipse?

Hi,
I'm developing an Eclipse plugin. I
need to find all the references in the
source using AST's or jdt.core.dom
or something like that. I need this
references like ASTNodes in order to
get the parent node and check several
things in the expression where
references are involved.
Thanks beforehand.
Edited:
I want to concrete a little more, My problem is that I try to catch some references to a constant but... I have not idea how I can do to catch in the matches this references. I need check the expressions which the references to a determined constant are involved. I only get the source of the method where they are used.
I think the problem is the scope or the pattern:
pattern = SearchPattern.createPattern(field, IJavaSearchConstants.REFERENCES);
scope = SearchEngine.createJavaSearchScope(declaringType.getMethods());
Thanks beforehand!
I used something like:
Search for the declaration of an
method, returns an IMethod
Search for references to the
IMethod, record those IMethods
For each IMethod returned, create an
AST from its compilation unit
Searching for declarations or references looks like the following code.
SearchRequestor findMethod = ...; // do something with the search results
SearchEngine engine = new SearchEngine();
IJavaSearchScope workspaceScope = SearchEngine.createWorkspaceScope();
SearchPattern pattern = SearchPattern.createPattern(searchString,
IJavaSearchConstants.METHOD, IJavaSearchConstants.DECLARATIONS,
SearchPattern.R_EXACT_MATCH);
SearchParticipant[] participant = new SearchParticipant[] { SearchEngine
.getDefaultSearchParticipant() };
engine.search(pattern, participant, workspaceScope, findMethod,
monitor);
Once you have your IMethod references, you can get to the AST using:
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setResolveBindings(true);
if (methodToSearch.isBinary()) {
parser.setSource(methodToSearch.getClassFile());
} else {
parser.setSource(methodToSearch.getCompilationUnit());
}
CompilationUnit cu = (CompilationUnit) parser.createAST(null);
See http://help.eclipse.org/helios/index.jsp?topic=/org.eclipse.jdt.doc.isv/guide/jdt_int_core.htm for more details on java search, the java model, and the AST.

How to filter files when opening using NetBeans?

I'm looking for a way to filter files in an "Open" window. I'm using NetBeans IDE 6.5.
I did some research, and this is what i came up with, but for some reason it's not working.
//global variable
protected static FileFilter myfilter;
//in declaration of variables
fchoLoad.setFileFilter(myfilter);
//inside main
myfilter = .... (i actually delted this part by accident, i need to filter only .fwd files. can anybody tell me what goes here?)
If I understand it correctly, you want to create your own file chooser and be able to filter just some files (.fwd in your case). I guess this is more general Java question (not only NetBeans) and I suggest reading this tutorial
Anyway, your "myfilter" should look like this:
myfilter = new FileFilter() {
public boolean accept(File f) {
return f.getName().toLowerCase().endsWith(".fwd")
|| f.isDirectory();
}
public String getDescription() {
return "FWD Files"; //type any description you want to display
}
};
Hope that helps