]> git.uio.no Git - ifi-stolz-refaktor.git/blob - case-study/jdt-before/ui/org/eclipse/jdt/ui/actions/OverrideMethodsAction.java
Case Study: adding data and statistics
[ifi-stolz-refaktor.git] / case-study / jdt-before / ui / org / eclipse / jdt / ui / actions / OverrideMethodsAction.java
1 /*******************************************************************************
2  * Copyright (c) 2000, 2011 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  *     IBM Corporation - initial API and implementation
10  *******************************************************************************/
11 package org.eclipse.jdt.ui.actions;
12
13 import java.lang.reflect.InvocationTargetException;
14 import java.util.ArrayList;
15
16 import org.eclipse.swt.widgets.Shell;
17
18 import org.eclipse.core.runtime.CoreException;
19
20 import org.eclipse.core.resources.IWorkspaceRunnable;
21
22 import org.eclipse.jface.dialogs.MessageDialog;
23 import org.eclipse.jface.operation.IRunnableContext;
24 import org.eclipse.jface.viewers.IStructuredSelection;
25 import org.eclipse.jface.window.Window;
26
27 import org.eclipse.jface.text.IRewriteTarget;
28 import org.eclipse.jface.text.ITextSelection;
29
30 import org.eclipse.ui.IEditorPart;
31 import org.eclipse.ui.IWorkbenchSite;
32 import org.eclipse.ui.PlatformUI;
33
34 import org.eclipse.jdt.core.ICompilationUnit;
35 import org.eclipse.jdt.core.IType;
36 import org.eclipse.jdt.core.JavaModelException;
37 import org.eclipse.jdt.core.dom.ASTParser;
38 import org.eclipse.jdt.core.dom.CompilationUnit;
39 import org.eclipse.jdt.core.dom.IMethodBinding;
40 import org.eclipse.jdt.core.dom.ITypeBinding;
41
42 import org.eclipse.jdt.internal.corext.codemanipulation.AddUnimplementedMethodsOperation;
43 import org.eclipse.jdt.internal.corext.dom.ASTNodes;
44 import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
45
46 import org.eclipse.jdt.ui.JavaUI;
47
48 import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
49 import org.eclipse.jdt.internal.ui.JavaPlugin;
50 import org.eclipse.jdt.internal.ui.actions.ActionMessages;
51 import org.eclipse.jdt.internal.ui.actions.ActionUtil;
52 import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
53 import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter;
54 import org.eclipse.jdt.internal.ui.dialogs.OverrideMethodDialog;
55 import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
56 import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
57 import org.eclipse.jdt.internal.ui.util.ElementValidator;
58 import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
59
60 /**
61  * Adds unimplemented methods of a type. The action opens a dialog from which the user can
62  * choose the methods to be added.
63  * <p>
64  * Will open the parent compilation unit in a Java editor. The result is unsaved, so the
65  * user can decide if the changes are acceptable.
66  * <p>
67  * The action is applicable to structured selections containing elements of type
68  * {@link org.eclipse.jdt.core.IType}.
69  *
70  * <p>
71  * This class may be instantiated; it is not intended to be subclassed.
72  * </p>
73  *
74  * @since 2.0
75  *
76  * @noextend This class is not intended to be subclassed by clients.
77  */
78 public class OverrideMethodsAction extends SelectionDispatchAction {
79
80         /** The dialog title */
81         private static final String DIALOG_TITLE= ActionMessages.OverrideMethodsAction_error_title;
82
83         /** The compilation unit editor */
84         private CompilationUnitEditor fEditor;
85
86         /**
87          * Note: This constructor is for internal use only. Clients should not call this
88          * constructor.
89          * @param editor the compilation unit editor
90          *
91          * @noreference This constructor is not intended to be referenced by clients.
92          */
93         public OverrideMethodsAction(final CompilationUnitEditor editor) {
94                 this(editor.getEditorSite());
95                 fEditor= editor;
96                 setEnabled(checkEnabledEditor());
97         }
98
99         /**
100          * Creates a new override method action.
101          * <p>
102          * The action requires that the selection provided by the site's selection provider is
103          * of type {@link org.eclipse.jface.viewers.IStructuredSelection}.
104          *
105          * @param site the workbench site providing context information for this action
106          */
107         public OverrideMethodsAction(final IWorkbenchSite site) {
108                 super(site);
109                 setText(ActionMessages.OverrideMethodsAction_label);
110                 setDescription(ActionMessages.OverrideMethodsAction_description);
111                 setToolTipText(ActionMessages.OverrideMethodsAction_tooltip);
112                 PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.ADD_UNIMPLEMENTED_METHODS_ACTION);
113         }
114
115         private boolean canEnable(IStructuredSelection selection) throws JavaModelException {
116                 if ((selection.size() == 1) && (selection.getFirstElement() instanceof IType)) {
117                         final IType type= (IType) selection.getFirstElement();
118                         return type.getCompilationUnit() != null && !type.isInterface();
119                 }
120                 if ((selection.size() == 1) && (selection.getFirstElement() instanceof ICompilationUnit))
121                         return true;
122                 return false;
123         }
124
125         private boolean checkEnabledEditor() {
126                 return fEditor != null && SelectionConverter.canOperateOn(fEditor);
127         }
128
129         private String getDialogTitle() {
130                 return DIALOG_TITLE;
131         }
132
133         private IType getSelectedType(IStructuredSelection selection) throws JavaModelException {
134                 final Object[] elements= selection.toArray();
135                 if (elements.length == 1 && (elements[0] instanceof IType)) {
136                         final IType type= (IType) elements[0];
137                         if (type.getCompilationUnit() != null && !type.isInterface()) {
138                                 return type;
139                         }
140                 } else if (elements[0] instanceof ICompilationUnit) {
141                         final IType type= ((ICompilationUnit) elements[0]).findPrimaryType();
142                         if (type != null && !type.isInterface())
143                                 return type;
144                 }
145                 return null;
146         }
147
148         /*
149          * @see org.eclipse.jdt.ui.actions.SelectionDispatchAction#run(org.eclipse.jface.viewers.IStructuredSelection)
150          */
151         @Override
152         public void run(IStructuredSelection selection) {
153                 try {
154                         final IType type= getSelectedType(selection);
155                         if (type == null) {
156                                 MessageDialog.openInformation(getShell(), getDialogTitle(), ActionMessages.OverrideMethodsAction_not_applicable);
157                                 notifyResult(false);
158                                 return;
159                         }
160                         if (!ElementValidator.check(type, getShell(), getDialogTitle(), false) || !ActionUtil.isEditable(getShell(), type)) {
161                                 notifyResult(false);
162                                 return;
163                         }
164                         run(getShell(), type);
165                 } catch (CoreException exception) {
166                         ExceptionHandler.handle(exception, getShell(), getDialogTitle(), ActionMessages.OverrideMethodsAction_error_actionfailed);
167                 }
168         }
169
170         /*
171          * @see org.eclipse.jdt.ui.actions.SelectionDispatchAction#run(org.eclipse.jface.text.ITextSelection)
172          */
173         @Override
174         public void run(ITextSelection selection) {
175                 try {
176                         final IType type= SelectionConverter.getTypeAtOffset(fEditor);
177                         if (type != null) {
178                                 if (!ElementValidator.check(type, getShell(), getDialogTitle(), false) || !ActionUtil.isEditable(fEditor, getShell(), type)) {
179                                         notifyResult(false);
180                                         return;
181                                 }
182                                 if (type.isAnnotation()) {
183                                         MessageDialog.openInformation(getShell(), getDialogTitle(), ActionMessages.OverrideMethodsAction_annotation_not_applicable);
184                                         notifyResult(false);
185                                         return;
186                                 }
187                                 if (type.isInterface()) {
188                                         MessageDialog.openInformation(getShell(), getDialogTitle(), ActionMessages.OverrideMethodsAction_interface_not_applicable);
189                                         notifyResult(false);
190                                         return;
191                                 }
192                                 run(getShell(), type);
193                         } else {
194                                 MessageDialog.openInformation(getShell(), getDialogTitle(), ActionMessages.OverrideMethodsAction_not_applicable);
195                         }
196                 } catch (JavaModelException e) {
197                         ExceptionHandler.handle(e, getShell(), getDialogTitle(), null);
198                 } catch (CoreException e) {
199                         ExceptionHandler.handle(e, getShell(), getDialogTitle(), ActionMessages.OverrideMethodsAction_error_actionfailed);
200                 }
201         }
202
203         private void run(Shell shell, IType type) throws CoreException {
204                 final OverrideMethodDialog dialog= new OverrideMethodDialog(shell, fEditor, type, false);
205                 if (!dialog.hasMethodsToOverride()) {
206                         MessageDialog.openInformation(shell, getDialogTitle(), ActionMessages.OverrideMethodsAction_error_nothing_found);
207                         notifyResult(false);
208                         return;
209                 }
210                 if (dialog.open() != Window.OK) {
211                         notifyResult(false);
212                         return;
213                 }
214
215                 final Object[] selected= dialog.getResult();
216                 if (selected == null) {
217                         notifyResult(false);
218                         return;
219                 }
220
221                 ArrayList<IMethodBinding> methods= new ArrayList<IMethodBinding>();
222                 for (int i= 0; i < selected.length; i++) {
223                         Object elem= selected[i];
224                         if (elem instanceof IMethodBinding) {
225                                 methods.add((IMethodBinding) elem);
226                         }
227                 }
228                 IMethodBinding[] methodToOverride= methods.toArray(new IMethodBinding[methods.size()]);
229
230
231                 final IEditorPart editor= JavaUI.openInEditor(type.getCompilationUnit());
232                 final IRewriteTarget target= editor != null ? (IRewriteTarget) editor.getAdapter(IRewriteTarget.class) : null;
233                 if (target != null)
234                         target.beginCompoundChange();
235                 try {
236                         CompilationUnit astRoot= dialog.getCompilationUnit();
237                         final ITypeBinding typeBinding= ASTNodes.getTypeBinding(astRoot, type);
238                         int insertPos= dialog.getInsertOffset();
239
240                         AddUnimplementedMethodsOperation operation= (AddUnimplementedMethodsOperation) createRunnable(astRoot, typeBinding, methodToOverride, insertPos, dialog.getGenerateComment());
241                         IRunnableContext context= JavaPlugin.getActiveWorkbenchWindow();
242                         if (context == null)
243                                 context= new BusyIndicatorRunnableContext();
244                         PlatformUI.getWorkbench().getProgressService().runInUI(context, new WorkbenchRunnableAdapter(operation, operation.getSchedulingRule()), operation.getSchedulingRule());
245                         final String[] created= operation.getCreatedMethods();
246                         if (created == null || created.length == 0)
247                                 MessageDialog.openInformation(shell, getDialogTitle(), ActionMessages.OverrideMethodsAction_error_nothing_found);
248                 } catch (InvocationTargetException exception) {
249                         ExceptionHandler.handle(exception, shell, getDialogTitle(), null);
250                 } catch (InterruptedException exception) {
251                         // Do nothing. Operation has been canceled by user.
252                 } finally {
253                         if (target != null)
254                                 target.endCompoundChange();
255                 }
256                 notifyResult(true);
257         }
258
259         /**
260          * Returns a runnable that creates the method stubs for overridden methods.
261          *
262          * @param astRoot the AST of the compilation unit to work on. The AST must have been created from a {@link ICompilationUnit}, that
263          * means {@link ASTParser#setSource(ICompilationUnit)} was used.
264          * @param type the binding of the type to add the new methods to. The type binding must correspond to a type declaration in the AST.
265          * @param methodToOverride the bindings of methods to override or <code>null</code> to implement all unimplemented, abstract methods from super types.
266          * @param insertPos a hint for a location in the source where to insert the new methods or <code>-1</code> to use the default behavior.
267          * @param createComments if set, comments will be added to the new methods.
268          * @return returns a runnable that creates the methods stubs.
269          * @throws IllegalArgumentException a {@link IllegalArgumentException} is thrown if the AST passed has not been created from a {@link ICompilationUnit}.
270          *
271          * @since 3.2
272          */
273         public static IWorkspaceRunnable createRunnable(CompilationUnit astRoot, ITypeBinding type, IMethodBinding[] methodToOverride, int insertPos, boolean createComments) {
274                 AddUnimplementedMethodsOperation operation= new AddUnimplementedMethodsOperation(astRoot, type, methodToOverride, insertPos, true, true, false);
275                 operation.setCreateComments(createComments);
276                 return operation;
277         }
278
279         /*
280          * @see org.eclipse.jdt.ui.actions.SelectionDispatchAction#selectionChanged(org.eclipse.jface.viewers.IStructuredSelection)
281          */
282         @Override
283         public void selectionChanged(IStructuredSelection selection) {
284                 try {
285                         setEnabled(canEnable(selection));
286                 } catch (JavaModelException exception) {
287                         if (JavaModelUtil.isExceptionToBeLogged(exception))
288                                 JavaPlugin.log(exception);
289                         setEnabled(false);
290                 }
291         }
292
293         /*
294          * @see org.eclipse.jdt.ui.actions.SelectionDispatchAction#run(org.eclipse.jface.text.ITextSelection)
295          */
296         @Override
297         public void selectionChanged(ITextSelection selection) {
298                 // Do nothing
299         }
300 }