Eclipse plugin : Get the enclosing class and member name - eclipse

I have created a Eclipse plug in to printout the object in selection on press of a short cut key.
I have been able to do this ,but i also would like to add the current method and current class name in the log. I am not sure how to proceede further. I tried to search for breadcrumb API but i was not able to reference the package from my project. I am quite new to plugin developement could someone guide me as to how to achive my goal. Thanks in advance.

It really hard to get that stuff from Breadcrumb, you would have to use reflection to get it.
Here is the code to get current method from editor.
ITextEditor editor = (ITextEditor) PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage().getActiveEditor();
ITextSelection selection = (ITextSelection) editor
.getSelectionProvider().getSelection();
IEditorInput editorInput = editor.getEditorInput();
IJavaElement elem = JavaUI.getEditorInputJavaElement(editorInput);
if (elem instanceof ICompilationUnit) {
ICompilationUnit unit = (ICompilationUnit) elem;
IJavaElement selected = unit.getElementAt(selection.getOffset());
System.out.println("selected=" + selected);
System.out.println("selected.class=" + selected.getClass());
}

Related

Open DialectEditor programmatically outside of main editor area (E3/E4 hybrid)

what I want to do:
In my RCP an E3/E4 hybrid I have a project and library based on sirius tree. The User can drag an drop item from the library tree to the project tree. This works fine and was no great problem to build in. So now I want to make the UI more usable. It should looks like this layout:
what works:
After application startup I open my library presentation with the DialectUIManager.
final DialectEditor editor = (DialectEditor)
DialectUIManager.INSTANCE.openEditor(siriusSession, description, monitor);
Okay, this works. But it open it in the editor in the part market as org.eclipse.ui.editorss. This it not what I want
what does not work:
I want to show it in the "Library Part". I can move it manually with the mouse after open the editor, but how can i tell DialectUIManager to open it direct there. Or how can I programmatically it move there.
I do a lot of google research but i don't found a solution. The only thing I found was a hint Pierre-Charles David https:// www. eclipse.org/forums/index.php?t=msg&th=998476&goto=1631138&#msg_1631138
If you need is simply to show the editor outside of the main editor
area, this is possible since Eclipse 4.2 (e4 does not really treat the
main editor area as something special), so you can have your editor
"around" another editor in the middle of other views.
But at this step I stuck. I also ask it in the Sirius Forum but they say its a Eclipse E4 problem
Thanks for help, code snippets or links to correct part of manual.
I've found a solution. It's not very nice, but it works. I execute these code here after the editors have opened.
What the code does:
He is looking for the MPlaceholder which has the ID: org. eclipse. ui. editorss. There he descends until he is with the parts. These are in the Compatibly editor mode. Then he chooses the part we wants to move out of and Attach them to the MPartStack target.
public static void movePart(MApplication application,
EModelService modelService) {
MPart partToMove = null;
MUIElement muiElement =
modelService.find("org.eclipse.ui.editorss", application);
if (muiElement instanceof MPlaceholder) {
MPlaceholder placeholder = (MPlaceholder) muiElement;
MUIElement ref = placeholder.getRef();
if (ref instanceof MArea) {
MArea area = (MArea) ref;
List<MPartSashContainerElement> children = area.getChildren();
for (MPartSashContainerElement mPartSashContainerElement
: children) {
if (mPartSashContainerElement instanceof MPartStack) {
MPartStack partStack = (MPartStack) mPartSashContainerElement;
List<MStackElement> children2 = partStack.getChildren();
for (MStackElement mStackElement : children2) {
if (mStackElement instanceof MPart) {
MPart part = (MPart) mStackElement;
// Library is the Editor Name wiche I want to move
if (part.getLabel().equals("Library")) {
partToMove = part;
break;
}
}
}
}
}
}
}
if (partToMove != null) {
moveElement(modelService, application, partToMove);
}
}
private static void moveElement(EModelService modelService,
MApplication application, MPart part) {
// target PartStack
MUIElement find = modelService.find("de.bsg.onesps.rcp.
partstack.library", application);
if (find instanceof MPartStack) {
MPartStack mPartStack = (MPartStack) find;
mPartStack.getChildren().add(part);
mPartStack.setSelectedElement(part);
}
}

How to pass an object from one part to another part in Eclispe e4 RCP?

I am building an application with eclipse e4 RCP. I have a navigator (similar to Navigator in eclipse IDE) and I would like to link it to an editor (similar to how a file in Navigator in eclipse IDE is linked to an editor). Currently I am using EPartService to open up my editor Part (by creating a new instance) when the user double clicks on a file in the Navigator tree. But I would like to pass it a parameter (a String or an Object) to let it know which file to open in the editor. I want to be able to open multiple editors for different nodes of the Navigator tree. I have done a lot of research on internet but could not find a solution. I think its a common problem and the e4 framework should provide an mechanism to pass such parameters from one Part to another Part. Current code is as below:
viewer.addDoubleClickListener(event -> {
final IStructuredSelection selection = (IStructuredSelection) event.getSelection();
FileNode file = null;
boolean partExists = false;
if (selection.getFirstElement() instanceof FileNode ) {
file = (FileNode ) selection.getFirstElement();
for (MPart part1 : partService.getParts()) {
if (part1.getLabel().equals(file.getName())) {
partService.showPart(part1, PartState.ACTIVATE);
partExists = true;
break;
}
}
if (!partExists) {
MPart part2 = partService
.createPart("com.parts.partdescriptor.fileeditor");
part2.setLabel(file.getName());
partService.showPart(part2, PartState.ACTIVATE);
}
}
});
Is it possible to say something like part2.setParameter("PARAM_NAME", "FILE_NAME"); ?
When you have an MPart you can call:
MPart mpart = ...
MyClass myClass = (MyClass)mpart.getObject();
to get your class for the part (the class defined in the 'Class URI' for the part in the Application.e4xmi). You can then call any methods you have defined on your part class.
You can also set data in the 'transient data' area of a part:
mpart.getTransientData().put("key", "data");
Object data = mpart.getTransientData().get("key");

Extraction of images present inside a paragraph

I am building an application where i need to parse a pdf which is generated by a system and with that parsed information i need to populate my applications database columns but unfortunaltely the pdf structure that i am dealing with is having a column called comments which has both text and image. I found the way of reading the images and text separately from the pdf but my ultimate aim was to add a place holder something like {2} in the place of image inside the parsed content and whenever my parser ( the application code ) parse this line the system will render the appropriate image in that area which is also stored in a separate table inside my application.
Please help me with resolving this problem.
Thanks in advance.
As already mentioned in comments, a solution would be to essentially use a customized text extraction strategy to insert a "[ 2]" text chunk at the coordinates of the image.
Code
You can e.g. extend the LocationTextExtractionStrategy like this:
class SimpleMixedExtractionStrategy extends LocationTextExtractionStrategy
{
SimpleMixedExtractionStrategy(File outputPath, String name)
{
this.outputPath = outputPath;
this.name = name;
}
#Override
public void renderImage(final ImageRenderInfo renderInfo)
{
try
{
PdfImageObject image = renderInfo.getImage();
if (image == null) return;
int number = counter++;
final String filename = String.format("%s-%s.%s", name, number, image.getFileType());
Files.write(new File(outputPath, filename).toPath(), image.getImageAsBytes());
LineSegment segment = UNIT_LINE.transformBy(renderInfo.getImageCTM());
TextChunk location = new TextChunk("[" + filename + "]", segment.getStartPoint(), segment.getEndPoint(), 0f);
Field field = LocationTextExtractionStrategy.class.getDeclaredField("locationalResult");
field.setAccessible(true);
List<TextChunk> locationalResult = (List<TextChunk>) field.get(this);
locationalResult.add(location);
}
catch (IOException | NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ioe)
{
ioe.printStackTrace();
}
}
final File outputPath;
final String name;
int counter = 0;
final static LineSegment UNIT_LINE = new LineSegment(new Vector(0, 0, 1) , new Vector(1, 0, 1));
}
(Unfortunately for this kind of work, some members of LocationTextExtractionStrategy are private. Thus, I used some Java reflection. Alternatively you can copy the whole class and change your copy accordingly.)
Example
Using that strategy you can extract mixed contents like this:
#Test
public void testSimpleMixedExtraction() throws IOException
{
InputStream resourceStream = getClass().getResourceAsStream("book-of-vaadin-page14.pdf");
try
{
PdfReader reader = new PdfReader(resourceStream);
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
SimpleMixedExtractionStrategy listener = new SimpleMixedExtractionStrategy(OUTPUT_PATH, "book-of-vaadin-page14");
parser.processContent(1, listener);
Files.write(new File(OUTPUT_PATH, "book-of-vaadin-page14.txt").toPath(), listener.getResultantText().getBytes());
}
finally
{
if (resourceStream != null)
resourceStream.close();
}
}
E.g. for my test file (which contains page 14 of the Book of Vaadin):
You get this text
Getting Started with Vaadin
• A version of Book of Vaadin that you can browse in the Eclipse Help system.
You can install the plugin as follows:
1. Start Eclipse.
2. Select Help   Software Updates....
3. Select the Available Software tab.
4. Add the Vaadin plugin update site by clicking Add Site....
[book-of-vaadin-page14-0.png]
Enter the URL of the Vaadin Update Site: http://vaadin.com/eclipse and click OK. The
Vaadin site should now appear in the Software Updates window.
5. Select all the Vaadin plugins in the tree.
[book-of-vaadin-page14-1.png]
Finally, click Install.
Detailed and up-to-date installation instructions for the Eclipse plugin can be found at http://vaad-
in.com/eclipse.
Updating the Vaadin Plugin
If you have automatic updates enabled in Eclipse (see Window   Preferences   Install/Update
  Automatic Updates), the Vaadin plugin will be updated automatically along with other plugins.
Otherwise, you can update the Vaadin plugin (there are actually multiple plugins) manually as
follows:
1. Select Help   Software Updates..., the Software Updates and Add-ons window will
open.
2. Select the Installed Software tab.
14 Vaadin Plugin for Eclipse
and two images book-of-vaadin-page14-0.png
and book-of-vaadin-page14-1.png
in OUTPUT_PATH.
Improvements to make
As also already mentioned in comments, this solution is for the easy situation in which the image has text above and/or below but neither left nor right.
If there is text left and/or right, too, there is the problem that the code above calculates LineSegment segment as the bottom line of the image but the text strategy usually works with the base line of text which is above the bottom line.
But in this case one first has to decide at which position on which line one wants the marker in the text to be anyways. Having decided that, one can adapt the source above.

Grab selected text from Eclipse Java editor

I'm developing an Eclipse plug-in where upon pressing a button, the plug-in takes the selected text in the Java editor and puts in a text box which appears.
My code looks like this: I got it from here: http://dev.eclipse.org/newslists/news.eclipse.newcomer/msg02200.html
private ITextSelection getSelection(ITextEditor editor) {
ISelection selection = editor.getSelectionProvider()
.getSelection();
return (ITextSelection) selection;
}
private String getSelectedText(ITextEditor editor) {
return getSelection(editor).getText();
}
The problem is how will I get the ITextEditor of the Java editor being displayed. Coincidentally it's the next question in the thread in the link I posted but it's unanswered :(
You could ask for the ActiveEditor, as in this thread:
IEditorPart part;
part =
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().get
ActiveEditor();
if(part instanceof ITextEditor){
ITextEditor editor = (ITextEditor)part;
IDocumentProvider provider = editor.getDocumentProvider();
IDocument document = provider.getDocument(editor.getEditorInput());
The OP Krt_Malta mentions this blog entry "Programmatically query current text selection", which is similar to this other SO answer (written before the blog entry) "Replace selected code from eclipse editor through plugin command".
I'd like to add one thing to VonCs answer. The technique he describes to get the selection is useful for all kinds of text editors, not only Java editors as this questions is about. But his solution does not work in the case that the workspace part is a MultiPageEditorPart, since that is not a ITextEditor.
But in many cases (for example with the standard XML editor) a MultiPageEditorPart has pages which are ITextEditors. In those cases you can get the active page from a MultiPageEditorPart and get the selection from that.
This can be done with the following code:
ITextEditor editor = null;
if (part instanceof ITextEditor) {
editor = (ITextEditor) part;
} else if (part instanceof MultiPageEditorPart) {
Object page = ((MultiPageEditorPart) part).getSelectedPage();
if (page instanceof ITextEditor) editor = (ITextEditor) page;
}
if (editor != null) {
IDocumentProvider provider = editor.getDocumentProvider();
IDocument document = provider.getDocument(editor.getEditorInput());
}

get ITextViewer from IEDitorPart (Eclipse)

Eclipse RCP question
I open file with:
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
IEditorPart editorPart = IDE.openEditor(page, file);
I also get document with:
IDocument doc = ((ITextEditor)editorPart).getDocumentProvider().getDocument(editorPart.getEditorInput());
I need to get to text viewer of that document (for creating LinkedModeUI), is there any way to do this?
The following worked for me:
IEditorPart editorPart = getSite().getPage().getActiveEditor();
if (editorPart != null) {
ITextOperationTarget target =
(ITextOperationTarget)editorPart.getAdapter(ITextOperationTarget.class);
if (target instanceof ITextViewer) {
ITextViewer textViewer = (ITextViewer)target;
// ...
}
}
1) One document can be opened with more than one editor. You'll have to iterate all editors to look for your file's editors.
2) Viewer is encapsulated in editor. I think the only way is extend editor class to add getter. Or redefine it, if viewer is inaccessible from inheritors.