Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Universal way to get the current project in eclipse plugin

I am creating an eclipse plugin which should deal with all opened projects inside Project explorer. It will create an file inside the selected project.

I am using the bellow logic to get the current project.

public IProject getCurrentProject() {
    IProject project = null;
    IWorkbenchWindow window = PlatformUI.getWorkbench()
            .getActiveWorkbenchWindow();
    if (window != null) {
        ISelection iselection = window.getSelectionService().getSelection();
        IStructuredSelection selection = (IStructuredSelection) iselection;
        if (selection == null) {
            return null;
        }

        Object firstElement = selection.getFirstElement();
        if (firstElement instanceof IResource) {
            project = ((IResource) firstElement).getProject();
        } else if (firstElement instanceof PackageFragmentRoot) {
            IJavaProject jProject = ((PackageFragmentRoot) firstElement)
                    .getJavaProject();
            project = jProject.getProject();
        } else if (firstElement instanceof IJavaElement) {
            IJavaProject jProject = ((IJavaElement) firstElement)
                    .getJavaProject();
            project = jProject.getProject();
        }
    }
    return project;
}

This is working in the developer mode. But after I export as a plugin and install, the following error occurred.

org.eclipse.e4.core.di.InjectionException: java.lang.ClassCastException: org.eclipse.jface.text.TextSelection cannot be cast to org.eclipse.jface.viewers.IStructuredSelection

It looks like selection has switched to editor since it has been focused. Is there any universal way to get the current project?

like image 965
Tharaka Deshan Avatar asked Dec 23 '22 17:12

Tharaka Deshan


1 Answers

Eclipse doesn't have a concept of 'current project'. The selection service gives you the selection for the currently active part which may be an editor or a view.

If the selection you get back from ISelectionService.getSelection is not an IStructuredSelection then the active part is probably an editor. So in that case you can try and get the current project from the active editor using something like:

IWorkbenchPage activePage = window.getActivePage();

IEditorPart activeEditor = activePage.getActiveEditor();

if (activeEditor != null) {
   IEditorInput input = activeEditor.getEditorInput();

   IProject project = input.getAdapter(IProject.class);
   if (project == null) {
      IResource resource = input.getAdapter(IResource.class);
      if (resource != null) {
         project = resource.getProject();
      }
   }
}
like image 140
greg-449 Avatar answered Mar 04 '23 01:03

greg-449