1 package $packageName$; 2 3 import java.util.Iterator ; 4 5 import org.eclipse.core.resources.IProject; 6 import org.eclipse.core.resources.IProjectDescription; 7 import org.eclipse.core.runtime.CoreException; 8 import org.eclipse.core.runtime.IAdaptable; 9 import org.eclipse.jface.action.IAction; 10 import org.eclipse.jface.viewers.ISelection; 11 import org.eclipse.jface.viewers.IStructuredSelection; 12 import org.eclipse.ui.IObjectActionDelegate; 13 import org.eclipse.ui.IWorkbenchPart; 14 15 public class ToggleNatureAction implements IObjectActionDelegate { 16 17 private ISelection selection; 18 19 24 public void run(IAction action) { 25 if (selection instanceof IStructuredSelection) { 26 for (Iterator it = ((IStructuredSelection) selection).iterator(); it 27 .hasNext();) { 28 Object element = it.next(); 29 IProject project = null; 30 if (element instanceof IProject) { 31 project = (IProject) element; 32 } else if (element instanceof IAdaptable) { 33 project = (IProject) ((IAdaptable) element) 34 .getAdapter(IProject.class); 35 } 36 if (project != null) { 37 toggleNature(project); 38 } 39 } 40 } 41 } 42 43 49 public void selectionChanged(IAction action, ISelection selection) { 50 this.selection = selection; 51 } 52 53 59 public void setActivePart(IAction action, IWorkbenchPart targetPart) { 60 } 61 62 68 private void toggleNature(IProject project) { 69 try { 70 IProjectDescription description = project.getDescription(); 71 String [] natures = description.getNatureIds(); 72 73 for (int i = 0; i < natures.length; ++i) { 74 if ($natureClassName$.NATURE_ID.equals(natures[i])) { 75 String [] newNatures = new String [natures.length - 1]; 77 System.arraycopy(natures, 0, newNatures, 0, i); 78 System.arraycopy(natures, i + 1, newNatures, i, 79 natures.length - i - 1); 80 description.setNatureIds(newNatures); 81 project.setDescription(description, null); 82 return; 83 } 84 } 85 86 String [] newNatures = new String [natures.length + 1]; 88 System.arraycopy(natures, 0, newNatures, 0, natures.length); 89 newNatures[natures.length] = $natureClassName$.NATURE_ID; 90 description.setNatureIds(newNatures); 91 project.setDescription(description, null); 92 } catch (CoreException e) { 93 } 94 } 95 96 } 97 | Popular Tags |