KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > jdt > ui > actions > FindAction


1 /*******************************************************************************
2  * Copyright (c) 2000, 2007 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 JavaDoc;
14
15 import org.eclipse.core.runtime.IAdaptable;
16 import org.eclipse.core.runtime.IStatus;
17
18 import org.eclipse.jface.dialogs.ErrorDialog;
19 import org.eclipse.jface.dialogs.MessageDialog;
20 import org.eclipse.jface.viewers.IStructuredSelection;
21 import org.eclipse.jface.window.Window;
22
23 import org.eclipse.jface.text.ITextSelection;
24
25 import org.eclipse.ui.IWorkbenchSite;
26 import org.eclipse.ui.PlatformUI;
27 import org.eclipse.ui.dialogs.ElementListSelectionDialog;
28 import org.eclipse.ui.progress.IProgressService;
29
30 import org.eclipse.jdt.core.IClassFile;
31 import org.eclipse.jdt.core.ICompilationUnit;
32 import org.eclipse.jdt.core.IJavaElement;
33 import org.eclipse.jdt.core.ILocalVariable;
34 import org.eclipse.jdt.core.IMember;
35 import org.eclipse.jdt.core.IPackageFragment;
36 import org.eclipse.jdt.core.IType;
37 import org.eclipse.jdt.core.JavaCore;
38 import org.eclipse.jdt.core.JavaModelException;
39 import org.eclipse.jdt.core.search.IJavaSearchScope;
40
41 import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
42
43 import org.eclipse.jdt.ui.JavaElementLabelProvider;
44 import org.eclipse.jdt.ui.search.ElementQuerySpecification;
45 import org.eclipse.jdt.ui.search.QuerySpecification;
46
47 import org.eclipse.jdt.internal.ui.JavaPlugin;
48 import org.eclipse.jdt.internal.ui.actions.ActionUtil;
49 import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
50 import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
51 import org.eclipse.jdt.internal.ui.search.JavaSearchQuery;
52 import org.eclipse.jdt.internal.ui.search.JavaSearchScopeFactory;
53 import org.eclipse.jdt.internal.ui.search.SearchMessages;
54 import org.eclipse.jdt.internal.ui.search.SearchUtil;
55 import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
56
57 /**
58  * Abstract class for Java search actions.
59  * <p>
60  * Note: This class is for internal use only. Clients should not use this class.
61  * </p>
62  *
63  * @since 2.0
64  */

65 public abstract class FindAction extends SelectionDispatchAction {
66
67     // A dummy which can't be selected in the UI
68
private static final IJavaElement RETURN_WITHOUT_BEEP= JavaCore.create(JavaPlugin.getWorkspace().getRoot());
69         
70     private Class JavaDoc[] fValidTypes;
71     private JavaEditor fEditor;
72
73
74     FindAction(IWorkbenchSite site) {
75         super(site);
76         fValidTypes= getValidTypes();
77         init();
78     }
79
80     FindAction(JavaEditor editor) {
81         this(editor.getEditorSite());
82         fEditor= editor;
83         setEnabled(SelectionConverter.canOperateOn(fEditor));
84     }
85     
86     /**
87      * Called once by the constructors to initialize label, tooltip, image and help support of the action.
88      * To be overridden by implementors of this action.
89      */

90     abstract void init();
91
92     /**
93      * Called once by the constructors to get the list of the valid input types of the action.
94      * To be overridden by implementors of this action.
95      * @return the valid input types of the action
96      */

97     abstract Class JavaDoc[] getValidTypes();
98     
99     private boolean canOperateOn(IStructuredSelection sel) {
100         return sel != null && !sel.isEmpty() && canOperateOn(getJavaElement(sel, true));
101     }
102         
103     boolean canOperateOn(IJavaElement element) {
104         if (element == null || fValidTypes == null || fValidTypes.length == 0 || !ActionUtil.isOnBuildPath(element))
105             return false;
106
107         for (int i= 0; i < fValidTypes.length; i++) {
108             if (fValidTypes[i].isInstance(element)) {
109                 if (element.getElementType() == IJavaElement.PACKAGE_FRAGMENT)
110                     return hasChildren((IPackageFragment)element);
111                 else
112                     return true;
113             }
114         }
115         return false;
116     }
117     
118     private boolean hasChildren(IPackageFragment packageFragment) {
119         try {
120             return packageFragment.hasChildren();
121         } catch (JavaModelException ex) {
122             return false;
123         }
124     }
125
126     private IJavaElement getTypeIfPossible(IJavaElement o, boolean silent) {
127         switch (o.getElementType()) {
128             case IJavaElement.COMPILATION_UNIT:
129                 if (silent)
130                     return o;
131                 else
132                     return findType((ICompilationUnit)o, silent);
133             case IJavaElement.CLASS_FILE:
134                 return ((IClassFile)o).getType();
135             default:
136                 return o;
137         }
138     }
139
140     IJavaElement getJavaElement(IStructuredSelection selection, boolean silent) {
141         if (selection.size() == 1) {
142             Object JavaDoc firstElement= selection.getFirstElement();
143             IJavaElement elem= null;
144             if (firstElement instanceof IJavaElement)
145                 elem= (IJavaElement) firstElement;
146             else if (firstElement instanceof IAdaptable)
147                 elem= (IJavaElement) ((IAdaptable) firstElement).getAdapter(IJavaElement.class);
148             if (elem != null) {
149                 return getTypeIfPossible(elem, silent);
150             }
151             
152         }
153         return null;
154     }
155
156     private void showOperationUnavailableDialog() {
157         MessageDialog.openInformation(getShell(), SearchMessages.JavaElementAction_operationUnavailable_title, getOperationUnavailableMessage());
158     }
159
160     String JavaDoc getOperationUnavailableMessage() {
161         return SearchMessages.JavaElementAction_operationUnavailable_generic;
162     }
163
164     private IJavaElement findType(ICompilationUnit cu, boolean silent) {
165         IType[] types= null;
166         try {
167             types= cu.getAllTypes();
168         } catch (JavaModelException ex) {
169             if (JavaModelUtil.isExceptionToBeLogged(ex))
170                 ExceptionHandler.log(ex, SearchMessages.JavaElementAction_error_open_message);
171             if (silent)
172                 return RETURN_WITHOUT_BEEP;
173             else
174                 return null;
175         }
176         if (types.length == 1 || (silent && types.length > 0))
177             return types[0];
178         if (silent)
179             return RETURN_WITHOUT_BEEP;
180         if (types.length == 0)
181             return null;
182         String JavaDoc title= SearchMessages.JavaElementAction_typeSelectionDialog_title;
183         String JavaDoc message = SearchMessages.JavaElementAction_typeSelectionDialog_message;
184         int flags= (JavaElementLabelProvider.SHOW_DEFAULT);
185
186         ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), new JavaElementLabelProvider(flags));
187         dialog.setTitle(title);
188         dialog.setMessage(message);
189         dialog.setElements(types);
190         
191         if (dialog.open() == Window.OK)
192             return (IType)dialog.getFirstResult();
193         else
194             return RETURN_WITHOUT_BEEP;
195     }
196
197     /*
198      * Method declared on SelectionChangedAction.
199      */

200     public void run(IStructuredSelection selection) {
201         IJavaElement element= getJavaElement(selection, false);
202         if (element == null || !element.exists()) {
203             showOperationUnavailableDialog();
204             return;
205         }
206         else if (element == RETURN_WITHOUT_BEEP)
207             return;
208         
209         run(element);
210     }
211
212     /*
213      * Method declared on SelectionChangedAction.
214      */

215     public void run(ITextSelection selection) {
216         if (!ActionUtil.isProcessable(fEditor))
217             return;
218         try {
219             String JavaDoc title= SearchMessages.SearchElementSelectionDialog_title;
220             String JavaDoc message= SearchMessages.SearchElementSelectionDialog_message;
221             
222             IJavaElement[] elements= SelectionConverter.codeResolveForked(fEditor, true);
223             if (elements.length > 0 && canOperateOn(elements[0])) {
224                 IJavaElement element= elements[0];
225                 if (elements.length > 1)
226                     element= SelectionConverter.selectJavaElement(elements, getShell(), title, message);
227                 if (element != null)
228                     run(element);
229             }
230             else
231                 showOperationUnavailableDialog();
232         } catch (InvocationTargetException JavaDoc ex) {
233             String JavaDoc title= SearchMessages.Search_Error_search_title;
234             String JavaDoc message= SearchMessages.Search_Error_codeResolve;
235             ExceptionHandler.handle(ex, getShell(), title, message);
236         } catch (InterruptedException JavaDoc e) {
237             // ignore
238
}
239     }
240
241     /*
242      * Method declared on SelectionChangedAction.
243      */

244     public void selectionChanged(IStructuredSelection selection) {
245         setEnabled(canOperateOn(selection));
246     }
247
248     /*
249      * Method declared on SelectionChangedAction.
250      */

251     public void selectionChanged(ITextSelection selection) {
252     }
253
254     /**
255      * Executes this action for the given java element.
256      * @param element The java element to be found.
257      */

258     public void run(IJavaElement element) {
259         
260         if (!ActionUtil.isProcessable(getShell(), element))
261             return;
262         
263         // will return true except for debugging purposes.
264
try {
265             performNewSearch(element);
266         } catch (JavaModelException ex) {
267             ExceptionHandler.handle(ex, getShell(), SearchMessages.Search_Error_search_notsuccessful_title, SearchMessages.Search_Error_search_notsuccessful_message);
268         } catch (InterruptedException JavaDoc e) {
269             // cancelled
270
}
271     }
272
273     private void performNewSearch(IJavaElement element) throws JavaModelException, InterruptedException JavaDoc {
274         JavaSearchQuery query= new JavaSearchQuery(createQuery(element));
275         if (query.canRunInBackground()) {
276             /*
277              * This indirection with Object as parameter is needed to prevent the loading
278              * of the Search plug-in: the VM verifies the method call and hence loads the
279              * types used in the method signature, eventually triggering the loading of
280              * a plug-in (in this case ISearchQuery results in Search plug-in being loaded).
281              */

282             SearchUtil.runQueryInBackground(query);
283         } else {
284             IProgressService progressService= PlatformUI.getWorkbench().getProgressService();
285             /*
286              * This indirection with Object as parameter is needed to prevent the loading
287              * of the Search plug-in: the VM verifies the method call and hence loads the
288              * types used in the method signature, eventually triggering the loading of
289              * a plug-in (in this case it would be ISearchQuery).
290              */

291             IStatus status= SearchUtil.runQueryInForeground(progressService, query);
292             if (status.matches(IStatus.ERROR | IStatus.INFO | IStatus.WARNING)) {
293                 ErrorDialog.openError(getShell(), SearchMessages.Search_Error_search_title, SearchMessages.Search_Error_search_message, status);
294             }
295         }
296     }
297     
298     QuerySpecification createQuery(IJavaElement element) throws JavaModelException, InterruptedException JavaDoc {
299         JavaSearchScopeFactory factory= JavaSearchScopeFactory.getInstance();
300         IJavaSearchScope scope= factory.createWorkspaceScope(true);
301         String JavaDoc description= factory.getWorkspaceScopeDescription(true);
302         return new ElementQuerySpecification(element, getLimitTo(), scope, description);
303     }
304
305     abstract int getLimitTo();
306
307     IType getType(IJavaElement element) {
308         if (element == null)
309             return null;
310         
311         IType type= null;
312         if (element.getElementType() == IJavaElement.TYPE)
313             type= (IType)element;
314         else if (element instanceof IMember)
315             type= ((IMember)element).getDeclaringType();
316         else if (element instanceof ILocalVariable) {
317             type= (IType)element.getAncestor(IJavaElement.TYPE);
318         }
319         return type;
320     }
321     
322     JavaEditor getEditor() {
323         return fEditor;
324     }
325         
326 }
327
Popular Tags