01: package gui.actions;
02:
03: import gui.RefactoringNature;
04:
05: import java.util.Iterator;
06:
07: import org.eclipse.core.resources.IProject;
08: import org.eclipse.core.resources.IProjectDescription;
09: import org.eclipse.core.runtime.CoreException;
10: import org.eclipse.core.runtime.IAdaptable;
11: import org.eclipse.jface.action.IAction;
12: import org.eclipse.jface.viewers.ISelection;
13: import org.eclipse.jface.viewers.IStructuredSelection;
14: import org.eclipse.ui.IObjectActionDelegate;
15: import org.eclipse.ui.IWorkbenchPart;
16:
17: public class ToggleNatureAction implements IObjectActionDelegate {
18:
19: private ISelection selection;
20:
21: /*
22: * (non-Javadoc)
23: *
24: * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
25: */
26: public void run(IAction action) {
27: if (selection instanceof IStructuredSelection) {
28: for (Iterator it = ((IStructuredSelection) selection)
29: .iterator(); it.hasNext();) {
30: Object element = it.next();
31: IProject project = null;
32: if (element instanceof IProject) {
33: project = (IProject) element;
34: } else if (element instanceof IAdaptable) {
35: project = (IProject) ((IAdaptable) element)
36: .getAdapter(IProject.class);
37: }
38: if (project != null) {
39: toggleNature(project);
40: }
41: }
42: }
43: }
44:
45: /*
46: * (non-Javadoc)
47: *
48: * @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction,
49: * org.eclipse.jface.viewers.ISelection)
50: */
51: public void selectionChanged(IAction action, ISelection selection) {
52: this .selection = selection;
53: }
54:
55: /*
56: * (non-Javadoc)
57: *
58: * @see org.eclipse.ui.IObjectActionDelegate#setActivePart(org.eclipse.jface.action.IAction,
59: * org.eclipse.ui.IWorkbenchPart)
60: */
61: public void setActivePart(IAction action, IWorkbenchPart targetPart) {
62: }
63:
64: /**
65: * Toggles refactoring nature on a project
66: *
67: * @param project
68: * to have refactoring nature added or removed
69: */
70: private void toggleNature(IProject project) {
71: try {
72: IProjectDescription description = project.getDescription();
73: String[] natures = description.getNatureIds();
74:
75: for (int i = 0; i < natures.length; ++i) {
76: if (RefactoringNature.NATURE_ID.equals(natures[i])) {
77: // Remove the nature
78: String[] newNatures = new String[natures.length - 1];
79: System.arraycopy(natures, 0, newNatures, 0, i);
80: System.arraycopy(natures, i + 1, newNatures, i,
81: natures.length - i - 1);
82: description.setNatureIds(newNatures);
83: project.setDescription(description, null);
84: return;
85: }
86: }
87:
88: // Add the nature
89: String[] newNatures = new String[natures.length + 1];
90: System.arraycopy(natures, 0, newNatures, 0, natures.length);
91: newNatures[natures.length] = RefactoringNature.NATURE_ID;
92: description.setNatureIds(newNatures);
93: project.setDescription(description, null);
94: } catch (CoreException e) {
95: }
96: }
97:
98: }
|