View | Details | Raw Unified | Return to bug 240665 | Differences between
and this patch

Collapse All | Expand All

(-)plugin.xml (-20 / +9 lines)
Lines 334-340 Link Here
334
   <extension
334
   <extension
335
         point="org.eclipse.debug.ui.launchShortcuts">
335
         point="org.eclipse.debug.ui.launchShortcuts">
336
      <shortcut
336
      <shortcut
337
            class="org.eclipse.mtj.ui.internal.launching.EmulatorLaunchShortcut"
337
            class="org.eclipse.mtj.ui.internal.launching.MidletLaunchShortcut"
338
            icon="icons/cellphone_icon.gif"
338
            icon="icons/cellphone_icon.gif"
339
            id="org.eclipse.mtj.launchShortcuts"
339
            id="org.eclipse.mtj.launchShortcuts"
340
            label="%launch.emulator.shortcut"
340
            label="%launch.emulator.shortcut"
Lines 347-356 Link Here
347
               		<iterate>
347
               		<iterate>
348
		             <and>
348
		             <and>
349
		               <adapt type="org.eclipse.jdt.core.IJavaElement">
349
		               <adapt type="org.eclipse.jdt.core.IJavaElement">
350
		                 <test property="org.eclipse.jdt.core.isInJavaProject"/>
350
		                 <test property="org.eclipse.jdt.launching.hasProjectNature" args="org.eclipse.mtj.core.nature"/>
351
		               </adapt>
351
		               </adapt>
352
		               <test property="org.eclipse.jdt.launching.extendsClass" args="javax.microedition.midlet.MIDlet"/>
352
		               <or>
353
		              </and>
353
		                 <test property="org.eclipse.jdt.launching.extendsClass" args="javax.microedition.midlet.MIDlet"/>
354
		               	 <test property="org.eclipse.jdt.launching.isContainer"/>
355
		               	 <test property="org.eclipse.jdt.launching.isPackageFragment"/>
356
		               	 <test property="org.eclipse.jdt.launching.isPackageFragmentRoot"/>
357
		               </or>
358
		             </and>
354
               		</iterate>
359
               		</iterate>
355
               </with>
360
               </with>
356
            </enablement>
361
            </enablement>
Lines 355-376 Link Here
355
               </with>
360
               </with>
356
            </enablement>
361
            </enablement>
357
         </contextualLaunch>
362
         </contextualLaunch>
358
         <perspective
359
               id="org.eclipse.mtj.ui.MtjPerspective">
360
         </perspective>
361
         
362
         <perspective
363
               id="org.eclipse.jdt.ui.JavaPerspective">
364
         </perspective>
365
         <perspective
366
               id="org.eclipse.jdt.ui.JavaHierarchyPerspective">
367
         </perspective>
368
         <perspective
369
               id="org.eclipse.jdt.ui.JavaBrowsingPerspective">
370
         </perspective>
371
         <perspective
372
               id="org.eclipse.debug.ui.DebugPerspective">
373
         </perspective>
374
      </shortcut>
363
      </shortcut>
375
      <shortcut
364
      <shortcut
376
            label="%launch.emulator.shortcut.jad"
365
            label="%launch.emulator.shortcut.jad"
(-)src/org/eclipse/mtj/ui/internal/launching/EmulatorLaunchShortcut.java (-411 lines)
Lines 1-411 Link Here
1
/**
2
 * Copyright (c) 2003,2008 Craig Setera and others.
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 * 
9
 * Contributors:
10
 *     Craig Setera (EclipseME) - Initial implementation
11
 *     Diego Sandin (Motorola)  - Refactoring package name to follow eclipse
12
 *                                standards
13
 *     Gang Ma      (Sybase)	- Moving debugger settings verification to a
14
 *                                more appropriate location
15
 */
16
package org.eclipse.mtj.ui.internal.launching;
17
18
import java.lang.reflect.InvocationTargetException;
19
import java.util.ArrayList;
20
import java.util.Collections;
21
import java.util.HashSet;
22
import java.util.List;
23
import java.util.Set;
24
25
import org.eclipse.core.resources.IResource;
26
import org.eclipse.core.runtime.CoreException;
27
import org.eclipse.core.runtime.IProgressMonitor;
28
import org.eclipse.core.runtime.IStatus;
29
import org.eclipse.core.runtime.SubProgressMonitor;
30
import org.eclipse.debug.core.DebugPlugin;
31
import org.eclipse.debug.core.ILaunchConfiguration;
32
import org.eclipse.debug.core.ILaunchConfigurationType;
33
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
34
import org.eclipse.debug.core.ILaunchManager;
35
import org.eclipse.debug.ui.DebugUITools;
36
import org.eclipse.debug.ui.IDebugModelPresentation;
37
import org.eclipse.debug.ui.IDebugUIConstants;
38
import org.eclipse.debug.ui.ILaunchShortcut;
39
import org.eclipse.jdt.core.IClassFile;
40
import org.eclipse.jdt.core.ICompilationUnit;
41
import org.eclipse.jdt.core.IJavaElement;
42
import org.eclipse.jdt.core.IType;
43
import org.eclipse.jdt.core.JavaCore;
44
import org.eclipse.jdt.core.JavaModelException;
45
import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
46
import org.eclipse.jdt.ui.JavaElementLabelProvider;
47
import org.eclipse.jface.dialogs.ErrorDialog;
48
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
49
import org.eclipse.jface.operation.IRunnableWithProgress;
50
import org.eclipse.jface.viewers.ISelection;
51
import org.eclipse.jface.viewers.IStructuredSelection;
52
import org.eclipse.mtj.core.internal.MTJCorePlugin;
53
import org.eclipse.mtj.core.internal.utils.Utils;
54
import org.eclipse.mtj.core.launching.ILaunchConstants;
55
import org.eclipse.mtj.ui.internal.MTJUIPlugin;
56
import org.eclipse.swt.widgets.Shell;
57
import org.eclipse.ui.IEditorInput;
58
import org.eclipse.ui.IEditorPart;
59
import org.eclipse.ui.IWorkbenchWindow;
60
import org.eclipse.ui.dialogs.ElementListSelectionDialog;
61
62
63
/**
64
 * Emulator launch shortcut implementation.
65
 * 
66
 * @author Craig Setera
67
 */
68
public class EmulatorLaunchShortcut implements ILaunchShortcut {
69
70
    /**
71
     * Default constructor.
72
     */
73
    public EmulatorLaunchShortcut() {
74
        super();
75
    }
76
77
    /**
78
     * @see org.eclipse.debug.ui.ILaunchShortcut#launch(org.eclipse.jface.viewers.ISelection,
79
     *      java.lang.String)
80
     */
81
    public void launch(ISelection selection, String mode) {
82
        if (selection instanceof IStructuredSelection) {
83
            launch(((IStructuredSelection) selection).toArray(), mode);
84
        }
85
    }
86
87
    /**
88
     * @see org.eclipse.debug.ui.ILaunchShortcut#launch(org.eclipse.ui.IEditorPart,
89
     *      java.lang.String)
90
     */
91
    public void launch(IEditorPart editor, String mode) {
92
        IEditorInput input = editor.getEditorInput();
93
        IJavaElement javaElement = (IJavaElement) input
94
                .getAdapter(IJavaElement.class);
95
        if (javaElement != null) {
96
            launch(new Object[] { javaElement }, mode);
97
        }
98
    }
99
100
    /**
101
     * Show a selection dialog that allows the user to choose one of the
102
     * specified launch configurations. Return the chosen config, or
103
     * <code>null</code> if the user canceled the dialog.
104
     */
105
    private ILaunchConfiguration chooseConfiguration(List configList,
106
            String mode) {
107
        IDebugModelPresentation labelProvider = DebugUITools
108
                .newDebugModelPresentation();
109
        ElementListSelectionDialog dialog = new ElementListSelectionDialog(
110
                getShell(), labelProvider);
111
        dialog.setElements(configList.toArray());
112
        dialog.setTitle("Launch configuration");
113
        dialog.setMessage("Select launch configuration");
114
        dialog.setMultipleSelection(false);
115
116
        int result = dialog.open();
117
        labelProvider.dispose();
118
        if (result == ElementListSelectionDialog.OK) {
119
            return (ILaunchConfiguration) dialog.getFirstResult();
120
        }
121
        return null;
122
    }
123
124
    /**
125
     * Prompts the user to select a type
126
     * 
127
     * @return the selected type or <code>null</code> if none.
128
     */
129
    private IType chooseType(IType[] types, String mode) {
130
        IType selectedType = null;
131
132
        ElementListSelectionDialog dialog = new ElementListSelectionDialog(
133
                getShell(), new JavaElementLabelProvider());
134
        dialog.setElements(types);
135
        dialog.setTitle("Type Selection");
136
137
        if (mode.equals(ILaunchManager.DEBUG_MODE)) {
138
            dialog.setMessage("Select the midlet to be debugged.");
139
        } else {
140
            dialog.setMessage("Select the midlet to be run.");
141
        }
142
143
        dialog.setMultipleSelection(false);
144
        if (dialog.open() == ElementListSelectionDialog.OK) {
145
            selectedType = (IType) dialog.getFirstResult();
146
        }
147
148
        return selectedType;
149
    }
150
151
    /**
152
     * Collect up the MIDlet types related to the specified object.
153
     * 
154
     * @param object
155
     * @param monitor
156
     * @param result
157
     * @throws JavaModelException
158
     */
159
    private void collectTypes(Object object, IProgressMonitor monitor,
160
            Set result) throws JavaModelException {
161
        IType type = null;
162
163
        if (object instanceof ICompilationUnit) {
164
            IType[] types = ((ICompilationUnit) object).getAllTypes();
165
            for (int i = 0; i < types.length; i++) {
166
                collectTypes(types[i], monitor, result);
167
            }
168
        } else if (object instanceof IClassFile) {
169
            type = ((IClassFile) object).getType();
170
        } else if (object instanceof IJavaElement) {
171
            type = (IType) ((IJavaElement) object)
172
                    .getAncestor(IJavaElement.TYPE);
173
        } else if (object instanceof IResource) {
174
            collectTypes(JavaCore.create((IResource) object), monitor, result);
175
        }
176
177
        if (type != null) {
178
            if (Utils.isMidlet(type, monitor)) {
179
                result.add(type);
180
            }
181
        }
182
    }
183
184
    /**
185
     * Create & return a new configuration based on the specified
186
     * <code>IType</code>.
187
     */
188
    private ILaunchConfiguration createConfiguration(IType type) {
189
        ILaunchConfiguration config = null;
190
        try {
191
            ILaunchConfigurationType configType = getEmulatorConfigType();
192
193
            String launchConfigName = DebugPlugin.getDefault()
194
                    .getLaunchManager()
195
                    .generateUniqueLaunchConfigurationNameFrom(
196
                            type.getElementName());
197
            ILaunchConfigurationWorkingCopy wc = configType.newInstance(null,
198
                    launchConfigName);
199
200
            wc.setAttribute(ILaunchConstants.EMULATED_CLASS, Utils
201
                    .getQualifiedClassName(type));
202
            wc.setAttribute(
203
                    IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, type
204
                            .getJavaProject().getElementName());
205
            wc.setAttribute(ILaunchConstants.DO_OTA, false);
206
207
            DebugUITools.setLaunchPerspective(configType,
208
                    ILaunchManager.RUN_MODE,
209
                    IDebugUIConstants.PERSPECTIVE_DEFAULT);
210
            DebugUITools.setLaunchPerspective(configType,
211
                    ILaunchManager.DEBUG_MODE,
212
                    IDebugUIConstants.PERSPECTIVE_DEFAULT);
213
214
            config = wc.doSave();
215
216
        } catch (CoreException ce) {
217
            MTJCorePlugin.log(IStatus.WARNING, "createConfiguration", ce);
218
        }
219
220
        return config;
221
    }
222
223
    /**
224
     * Locate a configuration to re-launch for the given type. If one cannot be
225
     * found, create one.
226
     * 
227
     * @return a re-usable config or <code>null</code> if none
228
     */
229
    private ILaunchConfiguration findLaunchConfiguration(IType type, String mode) {
230
        ILaunchConfiguration configuration = null;
231
        List candidateConfigs = getCandidateConfigs(type);
232
233
        // If there are no existing configs associated with the IType, create
234
        // one.
235
        // If there is exactly one config associated with the IType, return it.
236
        // Otherwise, if there is more than one config associated with the
237
        // IType, prompt the
238
        // user to choose one.
239
        int candidateCount = candidateConfigs.size();
240
        if (candidateCount < 1) {
241
            configuration = createConfiguration(type);
242
        } else if (candidateCount == 1) {
243
            configuration = (ILaunchConfiguration) candidateConfigs.get(0);
244
        } else {
245
            // Prompt the user to choose a config. A null result means the user
246
            // canceled the dialog, in which case this method returns null,
247
            // since canceling the dialog should also cancel launching
248
            // anything.
249
            ILaunchConfiguration config = chooseConfiguration(candidateConfigs,
250
                    mode);
251
            if (config != null) {
252
                configuration = config;
253
            }
254
        }
255
256
        return configuration;
257
    }
258
259
    /**
260
     * Get the candidate launch configurations for the specified type.
261
     * 
262
     * @param type
263
     * @return
264
     */
265
    private List getCandidateConfigs(IType type) {
266
        ILaunchConfigurationType configType = getEmulatorConfigType();
267
        List candidateConfigs = Collections.EMPTY_LIST;
268
        try {
269
            ILaunchConfiguration[] configs = DebugPlugin.getDefault()
270
                    .getLaunchManager().getLaunchConfigurations(configType);
271
            candidateConfigs = new ArrayList(configs.length);
272
            for (int i = 0; i < configs.length; i++) {
273
                ILaunchConfiguration config = configs[i];
274
                String midletName = config.getAttribute(
275
                        ILaunchConstants.EMULATED_CLASS, "");
276
                String projectName = config
277
                        .getAttribute(
278
                                IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME,
279
                                "");
280
281
                if (midletName.equals(Utils.getQualifiedClassName(type))
282
                        && projectName.equals(type.getJavaProject()
283
                                .getElementName())) {
284
                    candidateConfigs.add(config);
285
                }
286
            }
287
        } catch (CoreException e) {
288
            MTJCorePlugin.log(IStatus.WARNING, "getCandidateConfigs", e);
289
        }
290
291
        return candidateConfigs;
292
    }
293
294
    /**
295
     * Get the launch configuration type for wireless toolkit emulator.
296
     * 
297
     * @return
298
     */
299
    private ILaunchConfigurationType getEmulatorConfigType() {
300
        ILaunchManager lm = DebugPlugin.getDefault().getLaunchManager();
301
        ILaunchConfigurationType configType = lm
302
                .getLaunchConfigurationType(ILaunchConstants.LAUNCH_CONFIG_TYPE);
303
        return configType;
304
    }
305
306
    /**
307
     * Find all of the IType instances related to the specified selection.
308
     * 
309
     * @param selection
310
     * @return
311
     */
312
    private IType[] findTypes(final Object[] selection) {
313
        final Set result = new HashSet();
314
315
        if (selection.length > 0) {
316
            IRunnableWithProgress runnable = getTypeCollectionRunnable(
317
                    selection, result);
318
319
            try {
320
                new ProgressMonitorDialog(getShell()).run(true, true, runnable);
321
            } catch (InvocationTargetException e) {
322
                MTJCorePlugin.log(IStatus.WARNING, "findTypes", e);
323
            } catch (InterruptedException e) {
324
                // Ignore
325
            }
326
        }
327
328
        return (IType[]) result.toArray(new IType[result.size()]);
329
    }
330
331
    /**
332
     * Get the runnable to be used in collecting IType instances.
333
     * 
334
     * @param selection
335
     * @param result
336
     * @return
337
     */
338
    private IRunnableWithProgress getTypeCollectionRunnable(
339
            final Object[] selection, final Set result) {
340
        return new IRunnableWithProgress() {
341
            public void run(IProgressMonitor pm) throws InterruptedException {
342
                int nElements = selection.length;
343
                pm.beginTask("Searching", nElements);
344
                try {
345
                    for (int i = 0; i < nElements; i++) {
346
                        try {
347
                            collectTypes(selection[i], new SubProgressMonitor(
348
                                    pm, 1), result);
349
                        } catch (JavaModelException e) {
350
                            MTJCorePlugin.log(IStatus.WARNING, "collectTypes",
351
                                    e);
352
                        }
353
                        if (pm.isCanceled()) {
354
                            throw new InterruptedException();
355
                        }
356
                    }
357
                } finally {
358
                    pm.done();
359
                }
360
            }
361
        };
362
    }
363
364
    /**
365
     * Get the active workbench window's shell.
366
     * 
367
     * @return
368
     */
369
    private Shell getShell() {
370
        Shell shell = null;
371
372
        IWorkbenchWindow workbenchWindow = MTJUIPlugin.getDefault()
373
                .getWorkbench().getActiveWorkbenchWindow();
374
        if (workbenchWindow != null) {
375
            shell = workbenchWindow.getShell();
376
        }
377
378
        return shell;
379
    }
380
381
    /**
382
     * Attempt to find and launch the objects in the selection.
383
     * 
384
     * @param selection
385
     * @param mode
386
     */
387
    private void launch(Object[] selection, String mode) {
388
        IType type = null;
389
        IType[] types = findTypes(selection);
390
391
        // Choose a type
392
        if (types.length == 1) {
393
            type = types[0];
394
        } else if (types.length > 1) {
395
            type = chooseType(types, mode);
396
        }
397
398
        if (type != null) {
399
			ILaunchConfiguration config = findLaunchConfiguration(type, mode);
400
			if (config != null) {
401
				try {
402
					config.launch(mode, null);
403
				} catch (CoreException e) {
404
					ErrorDialog.openError(getShell(), "Error Launching "
405
							+ config.getName(), e.getMessage(), e.getStatus());
406
				}
407
			}
408
409
		}
410
    }
411
}
(-)src/org/eclipse/mtj/ui/internal/launching/JadLaunchShortcut.java (-2 / +2 lines)
Lines 182-189 Link Here
182
		ElementListSelectionDialog dialog = new ElementListSelectionDialog(
182
		ElementListSelectionDialog dialog = new ElementListSelectionDialog(
183
				getShell(), labelProvider);
183
				getShell(), labelProvider);
184
		dialog.setElements(configList.toArray());
184
		dialog.setElements(configList.toArray());
185
		dialog.setTitle(LauncherMessage.launch_configSelection_title);
185
		dialog.setTitle(LauncherMessages.launch_configSelection_title);
186
		dialog.setMessage(LauncherMessage.launch_configSelection_message);
186
		dialog.setMessage(LauncherMessages.launch_configSelection_message);
187
		dialog.setMultipleSelection(false);
187
		dialog.setMultipleSelection(false);
188
		int result = dialog.open();
188
		int result = dialog.open();
189
		labelProvider.dispose();
189
		labelProvider.dispose();
(-)src/org/eclipse/mtj/ui/internal/launching/MidletLaunchConfigUtils.java (+213 lines)
Line 0 Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2008 Sybase Inc. and others.
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 * 
9
 * Contributors:
10
 *     Feng Wang (Sybase) - initial implementation
11
 *******************************************************************************/
12
13
package org.eclipse.mtj.ui.internal.launching;
14
15
import java.lang.reflect.InvocationTargetException;
16
import java.util.ArrayList;
17
import java.util.HashSet;
18
import java.util.Iterator;
19
import java.util.List;
20
import java.util.Set;
21
22
import org.eclipse.core.resources.IResource;
23
import org.eclipse.core.runtime.IAdaptable;
24
import org.eclipse.core.runtime.IProgressMonitor;
25
import org.eclipse.core.runtime.IStatus;
26
import org.eclipse.core.runtime.SubProgressMonitor;
27
import org.eclipse.jdt.core.IClassFile;
28
import org.eclipse.jdt.core.ICompilationUnit;
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.IType;
33
import org.eclipse.jdt.core.ITypeHierarchy;
34
import org.eclipse.jdt.core.JavaCore;
35
import org.eclipse.jdt.core.JavaModelException;
36
import org.eclipse.jface.operation.IRunnableContext;
37
import org.eclipse.jface.operation.IRunnableWithProgress;
38
import org.eclipse.mtj.core.IMTJCoreConstants;
39
import org.eclipse.mtj.core.internal.MTJCorePlugin;
40
import org.eclipse.mtj.core.internal.utils.Utils;
41
42
/**
43
 * Utilities for Midlet launching
44
 * 
45
 * @author wangf
46
 * 
47
 */
48
public class MidletLaunchConfigUtils {
49
	/**
50
	 * Searches for Midlets from within the given scope of elements
51
	 * 
52
	 * @param context
53
	 * @param elements
54
	 *            - a array of <code>IJavaElement</code>s. The search scope.
55
	 * @return - an array of <code>IType</code>s of matches for java types that
56
	 *         extend <code>javax.microedition.midlet.MIDlet</code> (directly or
57
	 *         indirectly)
58
	 * @throws InvocationTargetException
59
	 * @throws InterruptedException
60
	 */
61
	public static IType[] findMidlets(IRunnableContext context,
62
			final Object[] elements) throws InvocationTargetException,
63
			InterruptedException {
64
		final Set<IType> result = new HashSet<IType>();
65
66
		if (elements.length > 0) {
67
			IRunnableWithProgress runnable = new IRunnableWithProgress() {
68
69
				public void run(IProgressMonitor monitor)
70
						throws InvocationTargetException, InterruptedException {
71
					for (Object element : elements) {
72
						collectTypes(element,
73
								new SubProgressMonitor(monitor, 1), result);
74
					}
75
				}
76
77
			};
78
			context.run(true, true, runnable);
79
		}
80
81
		IType[] types = result.toArray(new IType[result.size()]);
82
		return types;
83
	}
84
85
	/**
86
	 * Collect Midlet(s) from given Java element.
87
	 * 
88
	 * @param element
89
	 *            - a <code>IJavaElement</code> within which the collecting is
90
	 *            performed.
91
	 * @param monitor
92
	 * @param result
93
	 *            - a <code>Set</code> contains collected Midlets.
94
	 */
95
	private static void collectTypes(Object element,
96
			SubProgressMonitor monitor, Set<IType> result) {
97
		element = computeScope(element);
98
		try {
99
			// if the selected is a member(field, method) of Midlet, collect
100
			// is't parent Midlet
101
			while (element instanceof IMember) {
102
				if (element instanceof IType) {
103
					if (Utils.isMidlet((IType) element, monitor)) {
104
						result.add((IType) element);
105
						monitor.done();
106
						return;
107
					}
108
				}
109
				element = ((IJavaElement) element).getParent();
110
			}
111
			// if the selected is a Midlet, collect it
112
			if (element instanceof ICompilationUnit) {
113
				ICompilationUnit cu = (ICompilationUnit) element;
114
				IType[] types = cu.getAllTypes();
115
				for (int i = 0; i < types.length; i++) {
116
					if (Utils.isMidlet(types[i], monitor)) {
117
						result.add(types[i]);
118
					}
119
				}
120
			}
121
			// if the selected is a Midlet class file, collect the Midlet
122
			else if (element instanceof IClassFile) {
123
				IType type = ((IClassFile) element).getType();
124
				if (Utils.isMidlet(type, monitor)) {
125
					result.add(type);
126
				}
127
			}
128
			// if the selected is a container, collect all Midlets in it
129
			else if (element instanceof IJavaElement) {
130
				// the container
131
				IJavaElement parent = (IJavaElement) element;
132
				// get all Midlets in the project
133
				List<IType> found = collectMidletTypesInProject(monitor, parent
134
						.getJavaProject());
135
				// filter within the parent element
136
				// only collect Midlets that are located in the container
137
				Iterator<IType> iterator = found.iterator();
138
				while (iterator.hasNext()) {
139
					IJavaElement target = iterator.next();
140
					IJavaElement child = target;
141
					while (child != null) {
142
						if (child.equals(parent)) {
143
							result.add((IType) target);
144
							break;
145
						}
146
						child = child.getParent();
147
					}
148
				}
149
			}
150
		} catch (JavaModelException e) {
151
			MTJCorePlugin.log(IStatus.WARNING, "collectTypes", e);
152
		}
153
	}
154
155
	/**
156
	 * Collect Midlets from project.
157
	 * 
158
	 * @param monitor
159
	 * @param project
160
	 * @return
161
	 */
162
	private static List<IType> collectMidletTypesInProject(
163
			IProgressMonitor monitor, IJavaProject project) {
164
		IType[] types;
165
		HashSet<IType> result = new HashSet<IType>(5);
166
		try {
167
			IType midlet = project
168
					.findType(IMTJCoreConstants.MIDLET_SUPERCLASS);
169
			ITypeHierarchy hierarchy = midlet.newTypeHierarchy(project,
170
					new SubProgressMonitor(monitor, 1));
171
			types = hierarchy.getAllSubtypes(midlet);
172
			int length = types.length;
173
			if (length != 0) {
174
				for (int i = 0; i < length; i++) {
175
					if (!types[i].isBinary()) {
176
						result.add(types[i]);
177
					}
178
				}
179
			}
180
		} catch (JavaModelException jme) {
181
		}
182
		monitor.done();
183
		return new ArrayList<IType>(result);
184
	}
185
186
	/**
187
	 * If the element is not a <code>IJavaElement</code>, try to get the
188
	 * <code>IJavaElement</code> from it.
189
	 * 
190
	 * @param element
191
	 * @return
192
	 */
193
	private static Object computeScope(Object element) {
194
		if (element instanceof IJavaElement) {
195
			return element;
196
		}
197
		if (element instanceof IAdaptable) {
198
			element = ((IAdaptable) element).getAdapter(IResource.class);
199
		}
200
		if (element instanceof IResource) {
201
			IJavaElement javaElement = JavaCore.create((IResource) element);
202
			if (javaElement != null && !javaElement.exists()) {
203
				// do not consider the resource - corresponding java element
204
				// does not exist
205
				element = null;
206
			} else {
207
				element = javaElement;
208
			}
209
210
		}
211
		return element;
212
	}
213
}
(-)src/org/eclipse/mtj/ui/internal/launching/MidletLaunchShortcut.java (+147 lines)
Line 0 Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2008 Sybase Inc. and others.
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 * 
9
 * Contributors:
10
 *     Feng Wang (Sybase) - initial implementation
11
 *******************************************************************************/
12
13
package org.eclipse.mtj.ui.internal.launching;
14
15
import java.lang.reflect.InvocationTargetException;
16
17
import org.eclipse.core.runtime.CoreException;
18
import org.eclipse.core.runtime.IStatus;
19
import org.eclipse.debug.core.DebugPlugin;
20
import org.eclipse.debug.core.ILaunchConfiguration;
21
import org.eclipse.debug.core.ILaunchConfigurationType;
22
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
23
import org.eclipse.debug.core.ILaunchManager;
24
import org.eclipse.debug.ui.DebugUITools;
25
import org.eclipse.debug.ui.IDebugUIConstants;
26
import org.eclipse.jdt.core.IType;
27
import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
28
import org.eclipse.jface.operation.IRunnableContext;
29
import org.eclipse.mtj.core.internal.MTJCorePlugin;
30
import org.eclipse.mtj.core.internal.utils.Utils;
31
import org.eclipse.mtj.core.launching.ILaunchConstants;
32
33
/**
34
 * Launch shortcut for Midlet.
35
 * 
36
 * @author wangf
37
 * 
38
 */
39
public class MidletLaunchShortcut extends JavaLaunchShortcut {
40
	/*
41
	 * (non-Javadoc)
42
	 * 
43
	 * @seeorg.eclipse.jdt.debug.ui.launchConfigurations.JavaLaunchShortcut#
44
	 * createConfiguration(org.eclipse.jdt.core.IType)
45
	 */
46
	@Override
47
	protected ILaunchConfiguration createConfiguration(IType type) {
48
		ILaunchConfiguration config = null;
49
		try {
50
			ILaunchConfigurationType configType = getConfigurationType();
51
52
			String launchConfigName = DebugPlugin.getDefault()
53
					.getLaunchManager()
54
					.generateUniqueLaunchConfigurationNameFrom(
55
							type.getElementName());
56
			ILaunchConfigurationWorkingCopy wc = configType.newInstance(null,
57
					launchConfigName);
58
59
			wc.setAttribute(ILaunchConstants.EMULATED_CLASS, Utils
60
					.getQualifiedClassName(type));
61
			wc.setAttribute(
62
					IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, type
63
							.getJavaProject().getElementName());
64
			wc.setAttribute(ILaunchConstants.DO_OTA, false);
65
66
			DebugUITools.setLaunchPerspective(configType,
67
					ILaunchManager.RUN_MODE,
68
					IDebugUIConstants.PERSPECTIVE_DEFAULT);
69
			DebugUITools.setLaunchPerspective(configType,
70
					ILaunchManager.DEBUG_MODE,
71
					IDebugUIConstants.PERSPECTIVE_DEFAULT);
72
73
			config = wc.doSave();
74
75
		} catch (CoreException ce) {
76
			MTJCorePlugin.log(IStatus.WARNING, "createConfiguration", ce);
77
		}
78
79
		return config;
80
	}
81
82
	/*
83
	 * (non-Javadoc)
84
	 * 
85
	 * @see org.eclipse.jdt.debug.ui.launchConfigurations.JavaLaunchShortcut#findTypes
86
	 *      (java.lang.Object[], org.eclipse.jface.operation.IRunnableContext)
87
	 */
88
	@Override
89
	protected IType[] findTypes(Object[] elements, IRunnableContext context)
90
			throws InterruptedException, CoreException {
91
92
		try {
93
			return MidletLaunchConfigUtils.findMidlets(context, elements);
94
		} catch (InvocationTargetException e) {
95
			throw (CoreException) e.getTargetException();
96
		}
97
98
	}
99
100
	/*
101
	 * (non-Javadoc)
102
	 * 
103
	 * @seeorg.eclipse.jdt.debug.ui.launchConfigurations.JavaLaunchShortcut#
104
	 * getConfigurationType()
105
	 */
106
	@Override
107
	protected ILaunchConfigurationType getConfigurationType() {
108
		ILaunchManager lm = DebugPlugin.getDefault().getLaunchManager();
109
		ILaunchConfigurationType configType = lm
110
				.getLaunchConfigurationType(ILaunchConstants.LAUNCH_CONFIG_TYPE);
111
		return configType;
112
	}
113
114
	/*
115
	 * (non-Javadoc)
116
	 * 
117
	 * @seeorg.eclipse.jdt.debug.ui.launchConfigurations.JavaLaunchShortcut#
118
	 * getEditorEmptyMessage()
119
	 */
120
	@Override
121
	protected String getEditorEmptyMessage() {
122
		return LauncherMessages.MidletLaunching_EditorContainsNoMidlet;
123
	}
124
125
	/*
126
	 * (non-Javadoc)
127
	 * 
128
	 * @seeorg.eclipse.jdt.debug.ui.launchConfigurations.JavaLaunchShortcut#
129
	 * getSelectionEmptyMessage()
130
	 */
131
	@Override
132
	protected String getSelectionEmptyMessage() {
133
		return LauncherMessages.MidletLaunching_SelectionContainsNoMidlet;
134
	}
135
136
	/*
137
	 * (non-Javadoc)
138
	 * 
139
	 * @seeorg.eclipse.jdt.debug.ui.launchConfigurations.JavaLaunchShortcut#
140
	 * getTypeSelectionTitle()
141
	 */
142
	@Override
143
	protected String getTypeSelectionTitle() {
144
		return LauncherMessages.MidletLaunching_SelectionDialogTitle;
145
	}
146
147
}
(-)src/org/eclipse/mtj/ui/internal/launching/LauncherMessages.java (+33 lines)
Line 0 Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2008 Sybase Inc. and others.
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 * 
9
 * Contributors:
10
 *     Feng Wang (Sybase) - Initial implementation
11
 *******************************************************************************/
12
package org.eclipse.mtj.ui.internal.launching;
13
14
import org.eclipse.osgi.util.NLS;
15
16
public class LauncherMessages extends NLS {
17
	private static final String BUNDLE_NAME = "org.eclipse.mtj.ui.internal.launching.messages";//$NON-NLS-1$
18
	public static String launch_configSelection_title;
19
	public static String launch_configSelection_message;
20
	public static String MidletLaunching_EditorContainsNoMidlet;
21
	public static String MidletLaunching_SelectionContainsNoMidlet;
22
	public static String MidletLaunching_SelectionDialogTitle;
23
	public static String JavaLaunchShortcut_0;
24
	public static String JavaLaunchShortcut_1;
25
	public static String JavaLaunchShortcut_2;
26
	public static String JavaLaunchShortcut_3;
27
	public static String MainMethodLabelProvider_0;
28
	public static String JavaMainTab_Choose_a_main__type_to_launch__12;
29
	static {
30
		// load message values from bundle file
31
		NLS.initializeMessages(BUNDLE_NAME, LauncherMessages.class);
32
	}
33
}
(-)src/org/eclipse/mtj/ui/internal/launching/DebugTypeSelectionDialog.java (+337 lines)
Line 0 Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2006, 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
/*******************************************************************************
12
 * Copyright (c) 2008 Sybase Inc. and others.
13
 * 
14
 * All rights reserved. This program and the accompanying materials
15
 * are made available under the terms of the Eclipse Public License v1.0
16
 * which accompanies this distribution, and is available at
17
 * http://www.eclipse.org/legal/epl-v10.html
18
 * 
19
 * Contributors:
20
 *     Feng Wang (Sybase) - Copy from 
21
 *     		org.eclipse.jdt.internal.debug.ui.launcher.DebugTypeSelectionDialog And Modified.
22
 *     		This class is used by org.eclipse.mtj.ui.internal.launching.JavaLaunchShortcut
23
 *     		In feature when MTJ do not need to support Eclipse 3.3, 
24
 *     		org.eclipse.mtj.ui.internal.launching.JavaLaunchShortcut will no
25
 *     		longer useful and will be deleted. This class will be deleted too.
26
 *******************************************************************************/
27
28
package org.eclipse.mtj.ui.internal.launching;
29
30
import java.util.Arrays;
31
import java.util.Comparator;
32
import java.util.HashMap;
33
34
import org.eclipse.core.runtime.CoreException;
35
import org.eclipse.core.runtime.IAdaptable;
36
import org.eclipse.core.runtime.IProgressMonitor;
37
import org.eclipse.core.runtime.IStatus;
38
import org.eclipse.core.runtime.Status;
39
import org.eclipse.jdt.core.IJavaElement;
40
import org.eclipse.jdt.core.IJavaProject;
41
import org.eclipse.jdt.core.IType;
42
import org.eclipse.jdt.core.JavaCore;
43
import org.eclipse.jdt.core.JavaModelException;
44
import org.eclipse.jface.dialogs.IDialogSettings;
45
import org.eclipse.jface.resource.ImageDescriptor;
46
import org.eclipse.jface.viewers.ILabelProvider;
47
import org.eclipse.jface.viewers.ILabelProviderListener;
48
import org.eclipse.mtj.core.internal.MTJCorePlugin;
49
import org.eclipse.mtj.ui.IMTJUIConstants;
50
import org.eclipse.mtj.ui.internal.MTJUIPlugin;
51
import org.eclipse.swt.graphics.Image;
52
import org.eclipse.swt.widgets.Composite;
53
import org.eclipse.swt.widgets.Control;
54
import org.eclipse.swt.widgets.Shell;
55
import org.eclipse.ui.IMemento;
56
import org.eclipse.ui.PlatformUI;
57
import org.eclipse.ui.dialogs.FilteredItemsSelectionDialog;
58
import org.eclipse.ui.model.IWorkbenchAdapter;
59
60
/**
61
 * This is a specialization of <code>FilteredItemsSelectionDialog</code> used
62
 * to present users with a listing of <code>IType</code>s that contain main
63
 * methods
64
 * 
65
 * @since 3.3
66
 * 
67
 */
68
public class DebugTypeSelectionDialog extends FilteredItemsSelectionDialog {
69
70
	private static final String SELECT_MAIN_METHOD_DIALOG = "org.eclipse.jdt.debug.ui.select_main_method_dialog";
71
72
	/**
73
	 * Main list label provider
74
	 */
75
	public class DebugTypeLabelProvider implements ILabelProvider {
76
		HashMap<ImageDescriptor, Image> fImageMap = new HashMap<ImageDescriptor, Image>();
77
78
		public Image getImage(Object element) {
79
			if (element instanceof IAdaptable) {
80
				IWorkbenchAdapter adapter = (IWorkbenchAdapter) ((IAdaptable) element)
81
						.getAdapter(IWorkbenchAdapter.class);
82
				if (adapter != null) {
83
					ImageDescriptor descriptor = adapter
84
							.getImageDescriptor(element);
85
					Image image = fImageMap.get(descriptor);
86
					if (image == null) {
87
						image = descriptor.createImage();
88
						fImageMap.put(descriptor, image);
89
					}
90
					return image;
91
				}
92
			}
93
			return null;
94
		}
95
96
		public String getText(Object element) {
97
			if (element instanceof IType) {
98
				IType type = (IType) element;
99
				String label = type.getElementName();
100
				String container = getDeclaringContainerName(type);
101
				if (container != null && !"".equals(container)) { //$NON-NLS-1$
102
					label += " - " + container; //$NON-NLS-1$
103
				}
104
				return label;
105
			}
106
			return null;
107
		}
108
109
		/**
110
		 * Returns the name of the declaring container name
111
		 * 
112
		 * @param type
113
		 *            the type to find the container name for
114
		 * @return the container name for the specified type
115
		 */
116
		protected String getDeclaringContainerName(IType type) {
117
			IType outer = type.getDeclaringType();
118
			if (outer != null) {
119
				return outer.getFullyQualifiedName('.');
120
			} else {
121
				String name = type.getPackageFragment().getElementName();
122
				if ("".equals(name)) { //$NON-NLS-1$
123
					name = LauncherMessages.MainMethodLabelProvider_0;
124
				}
125
				return name;
126
			}
127
		}
128
129
		/**
130
		 * Returns the narrowest enclosing <code>IJavaElement</code> which is
131
		 * either an <code>IType</code> (enclosing) or an
132
		 * <code>IPackageFragment</code> (contained in)
133
		 * 
134
		 * @param type
135
		 *            the type to find the enclosing <code>IJavaElement</code>
136
		 *            for.
137
		 * @return the enclosing element or <code>null</code> if none
138
		 */
139
		protected IJavaElement getDeclaringContainer(IType type) {
140
			IJavaElement outer = type.getDeclaringType();
141
			if (outer == null) {
142
				outer = type.getPackageFragment();
143
			}
144
			return outer;
145
		}
146
147
		public void dispose() {
148
			fImageMap.clear();
149
			fImageMap = null;
150
		}
151
152
		public void addListener(ILabelProviderListener listener) {
153
		}
154
155
		public boolean isLabelProperty(Object element, String property) {
156
			return false;
157
		}
158
159
		public void removeListener(ILabelProviderListener listener) {
160
		}
161
	}
162
163
	/**
164
	 * Provides a label and image for the details area of the dialog
165
	 */
166
	class DebugTypeDetailsLabelProvider extends DebugTypeLabelProvider {
167
		public String getText(Object element) {
168
			if (element instanceof IType) {
169
				IType type = (IType) element;
170
				String name = getDeclaringContainerName(type);
171
				if (name != null) {
172
					if (name.equals(LauncherMessages.MainMethodLabelProvider_0)) {
173
						IJavaProject project = type.getJavaProject();
174
						if (project != null) {
175
							try {
176
								return project.getOutputLocation().toOSString()
177
										.substring(1)
178
										+ " - " + name; //$NON-NLS-1$
179
							} catch (JavaModelException e) {
180
								MTJCorePlugin.log(IStatus.ERROR, e);
181
							}
182
						}
183
					} else {
184
						return name;
185
					}
186
				}
187
			}
188
			return null;
189
		}
190
191
		public Image getImage(Object element) {
192
			if (element instanceof IType) {
193
				return super.getImage(getDeclaringContainer(((IType) element)));
194
			}
195
			return super.getImage(element);
196
		}
197
	}
198
199
	/**
200
	 * Simple items filter
201
	 */
202
	class DebugTypeItemsFilter extends ItemsFilter {
203
		public boolean isConsistentItem(Object item) {
204
			return item instanceof IType;
205
		}
206
207
		public boolean matchItem(Object item) {
208
			if (!(item instanceof IType)
209
					|| !Arrays.asList(fTypes).contains(item)) {
210
				return false;
211
			}
212
			return matches(((IType) item).getElementName());
213
		}
214
	}
215
216
	/**
217
	 * The selection history for the dialog
218
	 */
219
	class DebugTypeSelectionHistory extends SelectionHistory {
220
		protected Object restoreItemFromMemento(IMemento memento) {
221
			IJavaElement element = JavaCore.create(memento.getTextData());
222
			return (element instanceof IType ? element : null);
223
		}
224
225
		protected void storeItemToMemento(Object item, IMemento memento) {
226
			if (item instanceof IType) {
227
				memento.putTextData(((IType) item).getHandleIdentifier());
228
			}
229
		}
230
	}
231
232
	private static final String SETTINGS_ID = IMTJUIConstants.PLUGIN_ID
233
			+ ".MIDLET_SELECTION_DIALOG"; //$NON-NLS-1$
234
	private IType[] fTypes = null;
235
236
	/**
237
	 * Constructor
238
	 * 
239
	 * @param elements
240
	 *            the types to display in the dialog
241
	 */
242
	public DebugTypeSelectionDialog(Shell shell, IType[] elements, String title) {
243
		super(shell, false);
244
		setTitle(title);
245
		fTypes = elements;
246
		setMessage(LauncherMessages.JavaMainTab_Choose_a_main__type_to_launch__12);
247
		setInitialPattern("**"); //$NON-NLS-1$
248
		setListLabelProvider(new DebugTypeLabelProvider());
249
		setDetailsLabelProvider(new DebugTypeDetailsLabelProvider());
250
		setSelectionHistory(new DebugTypeSelectionHistory());
251
	}
252
253
	/*
254
	 * (non-Javadoc)
255
	 * 
256
	 * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#createDialogArea(org.eclipse.swt.widgets.Composite)
257
	 */
258
	protected Control createDialogArea(Composite parent) {
259
		Control ctrl = super.createDialogArea(parent);
260
		PlatformUI.getWorkbench().getHelpSystem().setHelp(ctrl,
261
				SELECT_MAIN_METHOD_DIALOG);
262
		return ctrl;
263
	}
264
265
	/**
266
	 * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#getDialogSettings()
267
	 */
268
	protected IDialogSettings getDialogSettings() {
269
		IDialogSettings settings = MTJUIPlugin.getDefault().getDialogSettings();
270
		IDialogSettings section = settings.getSection(SETTINGS_ID);
271
		if (section == null) {
272
			section = settings.addNewSection(SETTINGS_ID);
273
		}
274
		return section;
275
	}
276
277
	/**
278
	 * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#getItemsComparator()
279
	 */
280
	protected Comparator<IType> getItemsComparator() {
281
		Comparator<IType> comp = new Comparator<IType>() {
282
283
			public int compare(IType o1, IType o2) {
284
				return o1.getElementName().compareTo(o2.getElementName());
285
			}
286
		};
287
		return comp;
288
	}
289
290
	/**
291
	 * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#validateItem(java.lang.Object)
292
	 */
293
	protected IStatus validateItem(Object item) {
294
		return Status.OK_STATUS;
295
	}
296
297
	/**
298
	 * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#createExtendedContentArea(org.eclipse.swt.widgets.Composite)
299
	 */
300
	protected Control createExtendedContentArea(Composite parent) {
301
		return null;
302
	}
303
304
	/**
305
	 * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#createFilter()
306
	 */
307
	protected ItemsFilter createFilter() {
308
		return new DebugTypeItemsFilter();
309
	}
310
311
	/**
312
	 * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#fillContentProvider(org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.AbstractContentProvider,
313
	 *      org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.ItemsFilter,
314
	 *      org.eclipse.core.runtime.IProgressMonitor)
315
	 */
316
	protected void fillContentProvider(AbstractContentProvider contentProvider,
317
			ItemsFilter itemsFilter, IProgressMonitor progressMonitor)
318
			throws CoreException {
319
		if (fTypes != null && fTypes.length > 0) {
320
			for (int i = 0; i < fTypes.length; i++) {
321
				if (itemsFilter.isConsistentItem(fTypes[i])) {
322
					contentProvider.add(fTypes[i], itemsFilter);
323
				}
324
			}
325
		}
326
	}
327
328
	/**
329
	 * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#getElementName(java.lang.Object)
330
	 */
331
	public String getElementName(Object item) {
332
		if (item instanceof IType) {
333
			return ((IType) item).getElementName();
334
		}
335
		return null;
336
	}
337
}
(-)src/org/eclipse/mtj/ui/internal/launching/JavaLaunchShortcut.java (+318 lines)
Line 0 Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2005, 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
/*******************************************************************************
12
 * Copyright (c) 2008 Sybase Inc. and others.
13
 * 
14
 * All rights reserved. This program and the accompanying materials
15
 * are made available under the terms of the Eclipse Public License v1.0
16
 * which accompanies this distribution, and is available at
17
 * http://www.eclipse.org/legal/epl-v10.html
18
 * 
19
 * Contributors:
20
 *     Feng Wang (Sybase) - Copy from 
21
 *     		org.eclipse.jdt.internal.debug.ui.launcher.JavaLaunchShortcut And Modified.
22
 *     		In Eclipse 3.4, JavaLaunchShortcut become a non-internal class:
23
 *     		org.eclipse.jdt.debug.ui.launchConfigurations.JavaLaunchShortcut,
24
 *     		so we can use it directly.
25
 *     		In feature when MTJ do not need to support Eclipse 3.3, this 
26
 *     		class will no longer useful and should be deleted.
27
 *******************************************************************************/
28
29
package org.eclipse.mtj.ui.internal.launching;
30
31
import java.util.ArrayList;
32
import java.util.Collections;
33
import java.util.List;
34
35
import org.eclipse.core.runtime.CoreException;
36
import org.eclipse.core.runtime.IStatus;
37
import org.eclipse.debug.core.DebugPlugin;
38
import org.eclipse.debug.core.ILaunchConfiguration;
39
import org.eclipse.debug.core.ILaunchConfigurationType;
40
import org.eclipse.debug.core.ILaunchManager;
41
import org.eclipse.debug.ui.DebugUITools;
42
import org.eclipse.debug.ui.IDebugModelPresentation;
43
import org.eclipse.debug.ui.ILaunchShortcut;
44
import org.eclipse.jdt.core.IJavaElement;
45
import org.eclipse.jdt.core.IType;
46
import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
47
import org.eclipse.jface.dialogs.MessageDialog;
48
import org.eclipse.jface.operation.IRunnableContext;
49
import org.eclipse.jface.viewers.ISelection;
50
import org.eclipse.jface.viewers.IStructuredSelection;
51
import org.eclipse.jface.window.Window;
52
import org.eclipse.mtj.core.internal.MTJCorePlugin;
53
import org.eclipse.swt.widgets.Shell;
54
import org.eclipse.ui.IEditorInput;
55
import org.eclipse.ui.IEditorPart;
56
import org.eclipse.ui.IWorkbenchWindow;
57
import org.eclipse.ui.PlatformUI;
58
import org.eclipse.ui.dialogs.ElementListSelectionDialog;
59
60
/**
61
 * Common behavior for Java launch shortcuts
62
 * 
63
 * @since 3.2
64
 */
65
public abstract class JavaLaunchShortcut implements ILaunchShortcut {
66
67
	/**
68
	 * @param search
69
	 *            the java elements to search for a main type
70
	 * @param mode
71
	 *            the mode to launch in
72
	 * @param editor
73
	 *            activated on an editor (or from a selection in a viewer)
74
	 */
75
	public void searchAndLaunch(Object[] search, String mode,
76
			String selectMessage, String emptyMessage) {
77
		IType[] types = null;
78
		try {
79
			types = findTypes(search, PlatformUI.getWorkbench()
80
					.getProgressService());
81
		} catch (InterruptedException e) {
82
			return;
83
		} catch (CoreException e) {
84
			MessageDialog.openError(getShell(),
85
					LauncherMessages.JavaLaunchShortcut_0, e.getMessage());
86
			return;
87
		}
88
		IType type = null;
89
		if (types.length == 0) {
90
			MessageDialog.openError(getShell(),
91
					LauncherMessages.JavaLaunchShortcut_1, emptyMessage);
92
		} else if (types.length > 1) {
93
			type = chooseType(types, selectMessage);
94
		} else {
95
			type = types[0];
96
		}
97
		if (type != null) {
98
			launch(type, mode);
99
		}
100
	}
101
102
	/**
103
	 * Finds and returns the launchable types in the given selection of
104
	 * elements.
105
	 * 
106
	 * @param elements
107
	 *            scope to search for launchable types
108
	 * @param context
109
	 *            progress reporting context
110
	 * @return launchable types, possibly empty
111
	 * @exception InterruptedException
112
	 *                if the search is canceled
113
	 * @exception org.eclipse.core.runtime.CoreException
114
	 *                if the search fails
115
	 */
116
	protected abstract IType[] findTypes(Object[] elements,
117
			IRunnableContext context) throws InterruptedException,
118
			CoreException;
119
120
	/**
121
	 * Prompts the user to select a type from the given types.
122
	 * 
123
	 * @param types
124
	 *            the types to choose from
125
	 * @param title
126
	 *            the selection dialog title
127
	 * 
128
	 * @return the selected type or <code>null</code> if none.
129
	 */
130
	protected IType chooseType(IType[] types, String title) {
131
		DebugTypeSelectionDialog mmsd = new DebugTypeSelectionDialog(
132
				getShell(), types, title);
133
		if (mmsd.open() == Window.OK) {
134
			return (IType) mmsd.getResult()[0];
135
		}
136
		return null;
137
	}
138
139
	/**
140
	 * Launches a configuration for the given type
141
	 */
142
	protected void launch(IType type, String mode) {
143
		ILaunchConfiguration config = findLaunchConfiguration(type,
144
				getConfigurationType());
145
		if (config != null) {
146
			DebugUITools.launch(config, mode);
147
		}
148
	}
149
150
	/**
151
	 * Returns the type of configuration this shortcut is applicable to.
152
	 * 
153
	 * @return the type of configuration this shortcut is applicable to
154
	 */
155
	protected abstract ILaunchConfigurationType getConfigurationType();
156
157
	/**
158
	 * Locate a configuration to relaunch for the given type. If one cannot be
159
	 * found, create one.
160
	 * 
161
	 * @return a re-usable config or <code>null</code> if none
162
	 */
163
	protected ILaunchConfiguration findLaunchConfiguration(IType type,
164
			ILaunchConfigurationType configType) {
165
		List<ILaunchConfiguration> candidateConfigs = Collections.emptyList();
166
		try {
167
			ILaunchConfiguration[] configs = DebugPlugin.getDefault()
168
					.getLaunchManager().getLaunchConfigurations(configType);
169
			candidateConfigs = new ArrayList<ILaunchConfiguration>(
170
					configs.length);
171
			for (int i = 0; i < configs.length; i++) {
172
				ILaunchConfiguration config = configs[i];
173
				if (config.getAttribute(
174
						IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME,
175
						"").equals(type.getFullyQualifiedName())) { //$NON-NLS-1$
176
					if (config
177
							.getAttribute(
178
									IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME,
179
									"").equals(type.getJavaProject().getElementName())) { //$NON-NLS-1$
180
						candidateConfigs.add(config);
181
					}
182
				}
183
			}
184
		} catch (CoreException e) {
185
			MTJCorePlugin.log(IStatus.ERROR, e);
186
		}
187
188
		// If there are no existing configs associated with the IType, create
189
		// one.
190
		// If there is exactly one config associated with the IType, return it.
191
		// Otherwise, if there is more than one config associated with the
192
		// IType, prompt the
193
		// user to choose one.
194
		int candidateCount = candidateConfigs.size();
195
		if (candidateCount < 1) {
196
			return createConfiguration(type);
197
		} else if (candidateCount == 1) {
198
			return candidateConfigs.get(0);
199
		} else {
200
			// Prompt the user to choose a config. A null result means the user
201
			// canceled the dialog, in which case this method returns null,
202
			// since canceling the dialog should also cancel launching anything.
203
			ILaunchConfiguration config = chooseConfiguration(candidateConfigs);
204
			if (config != null) {
205
				return config;
206
			}
207
		}
208
209
		return null;
210
	}
211
212
	/**
213
	 * Show a selection dialog that allows the user to choose one of the
214
	 * specified launch configurations. Return the chosen config, or
215
	 * <code>null</code> if the user canceled the dialog.
216
	 */
217
	protected ILaunchConfiguration chooseConfiguration(
218
			List<ILaunchConfiguration> configList) {
219
		IDebugModelPresentation labelProvider = DebugUITools
220
				.newDebugModelPresentation();
221
		ElementListSelectionDialog dialog = new ElementListSelectionDialog(
222
				getShell(), labelProvider);
223
		dialog.setElements(configList.toArray());
224
		dialog.setTitle(getTypeSelectionTitle());
225
		dialog.setMessage(LauncherMessages.JavaLaunchShortcut_2);
226
		dialog.setMultipleSelection(false);
227
		int result = dialog.open();
228
		labelProvider.dispose();
229
		if (result == Window.OK) {
230
			return (ILaunchConfiguration) dialog.getFirstResult();
231
		}
232
		return null;
233
	}
234
235
	/**
236
	 * Create and returns a new configuration based on the specified
237
	 * <code>IType</code>.
238
	 */
239
	protected abstract ILaunchConfiguration createConfiguration(IType type);
240
241
	/**
242
	 * Opens an error dialog on the given exception.
243
	 * 
244
	 * @param exception
245
	 */
246
	protected void reportErorr(CoreException exception) {
247
		MessageDialog.openError(getShell(),
248
				LauncherMessages.JavaLaunchShortcut_3, exception.getStatus()
249
						.getMessage());
250
	}
251
252
	protected ILaunchManager getLaunchManager() {
253
		return DebugPlugin.getDefault().getLaunchManager();
254
	}
255
256
	/**
257
	 * Convenience method to get the window that owns this action's Shell.
258
	 */
259
	private Shell getShell() {
260
		IWorkbenchWindow window = PlatformUI.getWorkbench()
261
				.getActiveWorkbenchWindow();
262
		if (window == null) {
263
			IWorkbenchWindow[] windows = PlatformUI.getWorkbench()
264
					.getWorkbenchWindows();
265
			if (windows.length > 0) {
266
				return windows[0].getShell();
267
			}
268
		} else {
269
			return window.getShell();
270
		}
271
		return null;
272
	}
273
274
	/**
275
	 * @see ILaunchShortcut#launch(IEditorPart, String)
276
	 */
277
	public void launch(IEditorPart editor, String mode) {
278
		IEditorInput input = editor.getEditorInput();
279
		IJavaElement je = (IJavaElement) input.getAdapter(IJavaElement.class);
280
		if (je != null) {
281
			searchAndLaunch(new Object[] { je }, mode, getTypeSelectionTitle(),
282
					getEditorEmptyMessage());
283
		}
284
	}
285
286
	/**
287
	 * @see ILaunchShortcut#launch(ISelection, String)
288
	 */
289
	public void launch(ISelection selection, String mode) {
290
		if (selection instanceof IStructuredSelection) {
291
			searchAndLaunch(((IStructuredSelection) selection).toArray(), mode,
292
					getTypeSelectionTitle(), getSelectionEmptyMessage());
293
		}
294
	}
295
296
	/**
297
	 * Returns the title for type selection dialog for this launch shortcut.
298
	 * 
299
	 * @return type selection dialog title
300
	 */
301
	protected abstract String getTypeSelectionTitle();
302
303
	/**
304
	 * Returns an error message to use when the editor does not contain a
305
	 * launchable type.
306
	 * 
307
	 * @return error message
308
	 */
309
	protected abstract String getEditorEmptyMessage();
310
311
	/**
312
	 * Returns an error message to use when the selection does not contain a
313
	 * launchable type.
314
	 * 
315
	 * @return error message
316
	 */
317
	protected abstract String getSelectionEmptyMessage();
318
}
(-)src/org/eclipse/mtj/ui/internal/launching/messages.properties (+12 lines)
Lines 12-14 Link Here
12
12
13
launch_configSelection_title = Launch configuration
13
launch_configSelection_title = Launch configuration
14
launch_configSelection_message = Select launch configuration
14
launch_configSelection_message = Select launch configuration
15
16
MidletLaunching_SelectionDialogTitle = Select Java Midlet
17
MidletLaunching_EditorContainsNoMidlet = Editor does not contain an Midlet
18
MidletLaunching_SelectionContainsNoMidlet = Selection does not contain an Midlet
19
20
JavaLaunchShortcut_0=Error
21
JavaLaunchShortcut_1=Launch Error
22
JavaLaunchShortcut_2=&Select existing configuration:
23
JavaLaunchShortcut_3=Error
24
25
MainMethodLabelProvider_0=(default package)
26
JavaMainTab_Choose_a_main__type_to_launch__12=Select &type (? = any character, * = any String, TZ = TimeZone):
(-)src/org/eclipse/mtj/ui/internal/launching/LauncherMessage.java (-24 lines)
Lines 1-24 Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2008 Sybase Inc. and others.
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 * 
9
 * Contributors:
10
 *     Feng Wang (Sybase) - Initial implementation
11
 *******************************************************************************/
12
package org.eclipse.mtj.ui.internal.launching;
13
14
import org.eclipse.osgi.util.NLS;
15
16
public class LauncherMessage extends NLS {
17
	private static final String BUNDLE_NAME = "org.eclipse.mtj.ui.internal.launching.messages";//$NON-NLS-1$
18
	public static String launch_configSelection_title;
19
	public static String launch_configSelection_message;
20
	static {
21
		// load message values from bundle file
22
		NLS.initializeMessages(BUNDLE_NAME, LauncherMessage.class);
23
	}
24
}

Return to bug 240665