Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the selected node in the package explorer from an Eclipse plugin

I'm writing an Eclipse command plugin and want to retrieve the currently selected node in the package explorer view. I want to be able to get the absolute filepath, where the selected node resides on the filesystem (i.e. c:\eclipse\test.html), from the returned result.

How do I do this ?

like image 831
Benjamin Avatar asked Feb 25 '09 12:02

Benjamin


People also ask

How do I pull up Package Explorer in Eclipse?

To view the project explorer, click on Window menu then, click on Show View and select Project Explorer. There is simpler way to open project explorer, when you are in the editor press alt + shift + w and select project explorer.

What is Package Explorer?

The Package Explorer provides a hierarchical tree view of the projects and files in your workspace, and works just like the standard Eclipse Project Explorer. The Force.com IDE provides additional menu options; for details, see Force.com Context (Right-Click) Menu.

How do I select a file in Eclipse?

Loading (importing) an entire project Start Eclipse. Select File and then Import. From the pop up window expand the General option, select Existing Projects into Workspace and click the Next > button. In the next window select the Browse button and browse to the location of the project.


2 Answers

The first step is to get a selection service, e.g. from any view or editor like this:

ISelectionService service = getSite().getWorkbenchWindow()
            .getSelectionService();

Or, as VonC wrote, you could get it via the PlatformUI, if you are neither in a view or an editor.

Then, get the selection for the Package Explorer and cast it to an IStructuredSelection:

IStructuredSelection structured = (IStructuredSelection) service
            .getSelection("org.eclipse.jdt.ui.PackageExplorer");

From that, you can get your selected IFile:

IFile file = (IFile) structured.getFirstElement();

Now to get the full path, you will have to get the location for the IFile:

IPath path = file.getLocation();

Which you then can finally use to get the real full path to your file (among other things):

System.out.println(path.toPortableString());

You can find more information on the selection service here: Using the Selection Service.

like image 146
Fabian Steeg Avatar answered Oct 03 '22 05:10

Fabian Steeg


The code would be like:

IWorkbenchWindow window =
    PlatformUI.getWorkbench().getActiveWorkbenchWindow();
ISelection selection = window.getSelectionService().getSelection("org.eclipse.jdt.ui.PackageExplorer");

You view an example in an Action like this LuaFileWizardAction class.

like image 22
VonC Avatar answered Oct 03 '22 05:10

VonC