KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > pde > internal > ui > launcher > SWTApplicationLaunchShortcut


1 /*******************************************************************************
2  * Copyright (c) 2005, 2006 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.pde.internal.ui.launcher;
12
13 import java.lang.reflect.InvocationTargetException JavaDoc;
14 import java.util.ArrayList JavaDoc;
15 import java.util.Collections JavaDoc;
16
17 import org.eclipse.core.resources.IResource;
18 import org.eclipse.core.runtime.CoreException;
19 import org.eclipse.core.runtime.IAdaptable;
20 import org.eclipse.debug.core.DebugPlugin;
21 import org.eclipse.debug.core.ILaunchConfiguration;
22 import org.eclipse.debug.core.ILaunchConfigurationType;
23 import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
24 import org.eclipse.debug.core.ILaunchManager;
25 import org.eclipse.debug.ui.DebugUITools;
26 import org.eclipse.debug.ui.IDebugModelPresentation;
27 import org.eclipse.debug.ui.ILaunchShortcut;
28 import org.eclipse.jdt.core.IClasspathEntry;
29 import org.eclipse.jdt.core.IJavaElement;
30 import org.eclipse.jdt.core.IJavaProject;
31 import org.eclipse.jdt.core.IMember;
32 import org.eclipse.jdt.core.IPackageFragmentRoot;
33 import org.eclipse.jdt.core.IType;
34 import org.eclipse.jdt.core.JavaModelException;
35 import org.eclipse.jdt.core.search.IJavaSearchScope;
36 import org.eclipse.jdt.core.search.SearchEngine;
37 import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
38 import org.eclipse.jdt.ui.IJavaElementSearchConstants;
39 import org.eclipse.jface.dialogs.ErrorDialog;
40 import org.eclipse.jface.dialogs.MessageDialog;
41 import org.eclipse.jface.viewers.ISelection;
42 import org.eclipse.jface.viewers.IStructuredSelection;
43 import org.eclipse.jface.window.Window;
44 import org.eclipse.pde.internal.ui.PDEPlugin;
45 import org.eclipse.pde.internal.ui.PDEUIMessages;
46 import org.eclipse.swt.widgets.Display;
47 import org.eclipse.swt.widgets.Shell;
48 import org.eclipse.ui.IEditorInput;
49 import org.eclipse.ui.IEditorPart;
50 import org.eclipse.ui.PlatformUI;
51 import org.eclipse.ui.dialogs.ElementListSelectionDialog;
52
53 public class SWTApplicationLaunchShortcut implements ILaunchShortcut {
54
55     /**
56      * @param search the java elements to search for a main type
57      * @param mode the mode to launch in
58      * @param editor activated on an editor (or from a selection in a viewer)
59      */

60     public void searchAndLaunch(Object JavaDoc[] search, String JavaDoc mode, boolean editor) {
61         IType[] types = null;
62         if (search != null) {
63             try {
64                 IJavaElement[] elements = getJavaElements(search);
65                 MainMethodSearchEngine engine = new MainMethodSearchEngine();
66                 IJavaSearchScope scope = SearchEngine.createJavaSearchScope(elements, false);
67                 types = engine.searchMainMethods(PlatformUI.getWorkbench().getProgressService(),
68                         scope, IJavaElementSearchConstants.CONSIDER_BINARIES | IJavaElementSearchConstants.CONSIDER_EXTERNAL_JARS,
69                         true);
70             } catch (InterruptedException JavaDoc e) {
71                 return;
72             } catch (InvocationTargetException JavaDoc e) {
73                 MessageDialog.openError(getShell(), PDEUIMessages.SWTApplicationLaunchShortcut_failed, e.getMessage());
74                 return;
75             }
76             IType type = null;
77             if (types.length == 0) {
78                 String JavaDoc message = null;
79                 if (editor) {
80                     message = PDEUIMessages.SWTApplicationLaunchShortcut_noMainInEditor;
81                 } else {
82                     message = PDEUIMessages.SWTApplicationLaunchShortcut_noMainInSelection;
83                 }
84                 MessageDialog.openError(getShell(), PDEUIMessages.SWTApplicationLaunchShortcut_failed, message);
85             } else if (types.length > 1) {
86                 type = chooseType(types, mode);
87             } else {
88                 type = types[0];
89             }
90             if (type != null) {
91                 launch(type, mode);
92             }
93         }
94
95     }
96     
97     /**
98      * Returns the Java elements corresponding to the given objects.
99      *
100      * @param objects selected objects
101      * @return corresponding Java elements
102      */

103     private IJavaElement[] getJavaElements(Object JavaDoc[] objects) {
104         ArrayList JavaDoc list= new ArrayList JavaDoc(objects.length);
105         for (int i = 0; i < objects.length; i++) {
106             Object JavaDoc object = objects[i];
107             if (object instanceof IAdaptable) {
108                 IJavaElement element = (IJavaElement) ((IAdaptable)object).getAdapter(IJavaElement.class);
109                 if (element != null) {
110                     if (element instanceof IMember) {
111                         // Use the declaring type if available
112
IJavaElement type= ((IMember)element).getDeclaringType();
113                         if (type != null) {
114                             element= type;
115                         }
116                     }
117                     // for projects consider only src and not external libs
118
if (element instanceof IJavaProject) {
119                         IJavaProject project = (IJavaProject) element;
120                         try {
121                             IClasspathEntry[] cpEntries = project
122                                     .getRawClasspath();
123                             for (int j = 0; j < cpEntries.length; j++) {
124                                 if (cpEntries[j].getEntryKind() == IClasspathEntry.CPE_SOURCE
125                                         || cpEntries[j].getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
126                                     IPackageFragmentRoot[] roots = project.findPackageFragmentRoots(cpEntries[j]);
127                                     for(int r=0; r< roots.length; r++){
128                                         list.add(roots[r]);
129                                     }
130                                 }
131                             }
132                         } catch (JavaModelException jme) {
133                         }
134                     } else {
135                         list.add(element);
136                     }
137                 }
138             }
139         }
140         return (IJavaElement[]) list.toArray(new IJavaElement[list.size()]);
141     }
142
143     /**
144      * Prompts the user to select a type
145      *
146      * @return the selected type or <code>null</code> if none.
147      */

148     protected IType chooseType(IType[] types, String JavaDoc mode) {
149         MainTypeSelectionDialog dialog= new MainTypeSelectionDialog(getShell(), types);
150         if (mode.equals(ILaunchManager.DEBUG_MODE)) {
151             dialog.setTitle(PDEUIMessages.SWTApplicationLaunchShortcut_debug);
152         } else {
153             dialog.setTitle(PDEUIMessages.SWTApplicationLaunchShortcut_run);
154         }
155         dialog.setMultipleSelection(false);
156         if (dialog.open() == Window.OK) {
157             return (IType)dialog.getFirstResult();
158         }
159         return null;
160     }
161     
162     /**
163      * Launches a configuration for the given type
164      */

165     protected void launch(IType type, String JavaDoc mode) {
166         ILaunchConfiguration config = findLaunchConfiguration(type, mode);
167         if (config != null) {
168             DebugUITools.launch(config, mode);
169         }
170     }
171     
172     /**
173      * Locate a configuration to relaunch for the given type. If one cannot be found, create one.
174      *
175      * @return a re-useable config or <code>null</code> if none
176      */

177     protected ILaunchConfiguration findLaunchConfiguration(IType type, String JavaDoc mode) {
178         ILaunchConfigurationType configType = getSWTLaunchConfigType();
179         java.util.List JavaDoc candidateConfigs = Collections.EMPTY_LIST;
180         try {
181             ILaunchConfiguration[] configs = DebugPlugin.getDefault().getLaunchManager().getLaunchConfigurations(configType);
182             candidateConfigs = new ArrayList JavaDoc(configs.length);
183             for (int i = 0; i < configs.length; i++) {
184                 ILaunchConfiguration config = configs[i];
185                 if (config.getAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, "").equals(type.getFullyQualifiedName())) { //$NON-NLS-1$
186
if (config.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, "").equals(type.getJavaProject().getElementName())) { //$NON-NLS-1$
187
candidateConfigs.add(config);
188                     }
189                 }
190             }
191         } catch (CoreException e) {
192             PDEPlugin.log(e);
193         }
194         
195         // If there are no existing configs associated with the IType, create one.
196
// If there is exactly one config associated with the IType, return it.
197
// Otherwise, if there is more than one config associated with the IType, prompt the
198
// user to choose one.
199
int candidateCount = candidateConfigs.size();
200         if (candidateCount < 1) {
201             return createConfiguration(type);
202         } else if (candidateCount == 1) {
203             return (ILaunchConfiguration) candidateConfigs.get(0);
204         } else {
205             // Prompt the user to choose a config. A null result means the user
206
// cancelled the dialog, in which case this method returns null,
207
// since cancelling the dialog should also cancel launching anything.
208
ILaunchConfiguration config = chooseConfiguration(candidateConfigs, mode);
209             if (config != null) {
210                 return config;
211             }
212         }
213         
214         return null;
215     }
216     
217     /**
218      * Show a selection dialog that allows the user to choose one of the specified
219      * launch configurations. Return the chosen config, or <code>null</code> if the
220      * user cancelled the dialog.
221      */

222     protected ILaunchConfiguration chooseConfiguration(java.util.List JavaDoc configList, String JavaDoc mode) {
223         IDebugModelPresentation labelProvider = DebugUITools.newDebugModelPresentation();
224         ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), labelProvider);
225         dialog.setElements(configList.toArray());
226         dialog.setTitle(PDEUIMessages.SWTApplicationLaunchShortcut_launch);
227         if (mode.equals(ILaunchManager.DEBUG_MODE)) {
228             dialog.setMessage(PDEUIMessages.SWTApplicationLaunchShortcut_chooseRun);
229         } else {
230             dialog.setMessage(PDEUIMessages.SWTApplicationLaunchShortcut_chooseDebug);
231         }
232         dialog.setMultipleSelection(false);
233         int result = dialog.open();
234         labelProvider.dispose();
235         if (result == Window.OK) {
236             return (ILaunchConfiguration) dialog.getFirstResult();
237         }
238         return null;
239     }
240     
241     /**
242      * Create & return a new configuration based on the specified <code>IType</code>.
243      */

244     protected ILaunchConfiguration createConfiguration(IType type) {
245         ILaunchConfiguration config = null;
246         ILaunchConfigurationWorkingCopy wc = null;
247         try {
248             ILaunchConfigurationType configType = getSWTLaunchConfigType();
249             wc = configType.newInstance(null, getLaunchManager().generateUniqueLaunchConfigurationNameFrom(type.getElementName()));
250         } catch (CoreException exception) {
251             reportCreatingConfiguration(exception);
252             return null;
253         }
254         wc.setAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, type.getFullyQualifiedName());
255         wc.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, type.getJavaProject().getElementName());
256         wc.setMappedResources(new IResource[] {type.getJavaProject().getProject()});
257         try {
258             config = wc.doSave();
259         } catch (CoreException exception) {
260             reportCreatingConfiguration(exception);
261         }
262         return config;
263     }
264     
265     protected void reportCreatingConfiguration(final CoreException exception) {
266         Display.getDefault().asyncExec(new Runnable JavaDoc() {
267             public void run() {
268                 ErrorDialog.openError(getShell(), PDEUIMessages.SWTApplicationLaunchShortcut_error, PDEUIMessages.SWTApplicationLaunchShortcut_exception, exception.getStatus()); //
269
}
270         });
271     }
272     
273     /**
274      * Returns the local java launch config type
275      */

276     protected ILaunchConfigurationType getSWTLaunchConfigType() {
277         return getLaunchManager().getLaunchConfigurationType("org.eclipse.pde.ui.swtLaunchConfig"); //$NON-NLS-1$
278
}
279     
280     protected ILaunchManager getLaunchManager() {
281         return DebugPlugin.getDefault().getLaunchManager();
282     }
283     
284     /**
285      * Convenience method to get the window that owns this action's Shell.
286      */

287     protected Shell getShell() {
288         return PDEPlugin.getActiveWorkbenchShell();
289     }
290     
291     /**
292      * @see ILaunchShortcut#launch(IEditorPart, String)
293      */

294     public void launch(IEditorPart editor, String JavaDoc mode) {
295         IEditorInput input = editor.getEditorInput();
296         IJavaElement je = (IJavaElement) input.getAdapter(IJavaElement.class);
297         if (je != null) {
298             searchAndLaunch(new Object JavaDoc[] {je}, mode, true);
299         } else {
300             MessageDialog.openError(getShell(), PDEUIMessages.SWTApplicationLaunchShortcut_failed, PDEUIMessages.SWTApplicationLaunchShortcut_noMainInEditor);
301         }
302         
303     }
304
305     /**
306      * @see ILaunchShortcut#launch(ISelection, String)
307      */

308     public void launch(ISelection selection, String JavaDoc mode) {
309         if (selection instanceof IStructuredSelection) {
310             searchAndLaunch(((IStructuredSelection)selection).toArray(), mode, false);
311         } else {
312             MessageDialog.openError(getShell(), PDEUIMessages.SWTApplicationLaunchShortcut_failed, PDEUIMessages.SWTApplicationLaunchShortcut_noMainInSelection);
313         }
314     }
315
316 }
317
Popular Tags