package eu.scasefp7.eclipse.core.handlers;

import java.util.List;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.handlers.HandlerUtil;

/**
 * Abstract handler with a convenience method to get the project out of selection list.
 * 
 * @author themis
 */
public abstract class ProjectAwareHandler extends AbstractHandler {

	/**
	 * Returns the project that the event belongs to.
	 * 
	 * @param event the given event of this handler.
	 * @return the project that the event belongs to, or null if there is no project.
	 */
	@SuppressWarnings("unchecked")
	protected IProject getProjectOfExecutionEvent(ExecutionEvent event) {
		IProject project = null;
		ISelection selection = HandlerUtil.getCurrentSelection(event);
		if (selection instanceof IStructuredSelection) {
			IStructuredSelection structuredSelection = (IStructuredSelection) selection;
			List<Object> selectionList = structuredSelection.toList();
			project = getProjectOfSelectionList(selectionList);
		}
		return project;
	}

	/**
	 * Returns the project that the selected file(s) belong to.
	 * 
	 * @param selectionList the selected file(s).
	 * @return the project that the selected file(s) belong to.
	 */
	protected IProject getProjectOfSelectionList(List<Object> selectionList) {
		IProject project = null;
		for (Object object : selectionList) {
			IFile file = (IFile) Platform.getAdapterManager().getAdapter(object, IFile.class);
			IProject theproject = null;
			if (file != null) {
				theproject = file.getProject();
			} else {
				theproject = (IProject) Platform.getAdapterManager().getAdapter(object, IProject.class);
			}
			if (theproject != null) {
				if (project == null) {
					project = theproject;
				} else {
					if (!project.equals(theproject)) {
						return null;
					}
				}
			}
		}
		return project;
	}

}

@@ -195,20 +195,23 @@
 ources.I
-File
+Project
 ;%0Aimport
@@ -231,39 +231,40 @@
 core.resources.I
-Project
+Resource
 ;%0Aimport org.ecl
@@ -1330,35 +1330,39 @@
 at the selected 
-fil
+resourc
 e(s) belong to.%0A
@@ -1400,27 +1400,31 @@
 he selected 
-fil
+resourc
 e(s).%0A%09 * @r
@@ -1459,19 +1459,23 @@
 elected 
-fil
+resourc
 e(s) bel
@@ -1638,25 +1638,37 @@
 %09%09%09I
-File file = (IFil
+Resource resource = (IResourc
 e) P
@@ -1719,11 +1719,15 @@
 t, I
-Fil
+Resourc
 e.cl
@@ -1770,19 +1770,23 @@
 %0A%09%09%09if (
-fil
+resourc
 e != nul
@@ -1811,11 +1811,15 @@
 t = 
-fil
+resourc
 e.ge

Update project-aware handler to support also selecting folders