18

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 ?

Fabian Steeg
  • 44,988
  • 7
  • 85
  • 112
Benjamin
  • 539
  • 2
  • 6
  • 16

2 Answers2

33

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.

Community
  • 1
  • 1
Fabian Steeg
  • 44,988
  • 7
  • 85
  • 112
  • 1
    "viewed 9 times"... nobody look those questions ;) Anyway, well detailed answer. +1 – VonC Feb 25 '09 at 17:52
  • 4
    When getting the selection from the package explorer, the elements are not instances if IFile. You need to perform JDT->resource conversions. – kberg Mar 22 '12 at 23:30
  • @kberg The cast throws an exception indeed. But what do you mean perform JDT->resource conversion – Fofole Nov 22 '12 at 14:34
  • Where is "org.eclipse.jdt.ui.PackageExplorer" defined as a constant? Dont like magic strings. – Pétur Ingi Egilsson Jun 02 '16 at 06:33
16

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.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • Your link to LuaFileWizardAction class seems to be broken. It redirects to http://www.blackducksoftware.com/ – David Feb 04 '13 at 18:02