KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > debug > internal > ui > DebugUIPlugin


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  * Sascha Radike - bug 56642
11  *******************************************************************************/

12 package org.eclipse.debug.internal.ui;
13
14  
15 import java.io.ByteArrayOutputStream JavaDoc;
16 import java.io.IOException JavaDoc;
17 import java.lang.reflect.InvocationTargetException JavaDoc;
18 import java.net.URL JavaDoc;
19 import java.util.HashSet JavaDoc;
20 import java.util.Iterator JavaDoc;
21 import java.util.Set JavaDoc;
22
23 import javax.xml.parsers.DocumentBuilder JavaDoc;
24 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
25 import javax.xml.parsers.ParserConfigurationException JavaDoc;
26 import javax.xml.transform.OutputKeys JavaDoc;
27 import javax.xml.transform.Transformer JavaDoc;
28 import javax.xml.transform.TransformerException JavaDoc;
29 import javax.xml.transform.TransformerFactory JavaDoc;
30 import javax.xml.transform.dom.DOMSource JavaDoc;
31 import javax.xml.transform.stream.StreamResult JavaDoc;
32
33 import org.eclipse.core.resources.ISaveContext;
34 import org.eclipse.core.resources.ISaveParticipant;
35 import org.eclipse.core.resources.IncrementalProjectBuilder;
36 import org.eclipse.core.resources.ResourcesPlugin;
37 import org.eclipse.core.runtime.CoreException;
38 import org.eclipse.core.runtime.FileLocator;
39 import org.eclipse.core.runtime.IAdapterManager;
40 import org.eclipse.core.runtime.IConfigurationElement;
41 import org.eclipse.core.runtime.IProgressMonitor;
42 import org.eclipse.core.runtime.IStatus;
43 import org.eclipse.core.runtime.Path;
44 import org.eclipse.core.runtime.Platform;
45 import org.eclipse.core.runtime.Status;
46 import org.eclipse.core.runtime.SubProgressMonitor;
47 import org.eclipse.core.runtime.jobs.IJobChangeEvent;
48 import org.eclipse.core.runtime.jobs.IJobChangeListener;
49 import org.eclipse.core.runtime.jobs.IJobManager;
50 import org.eclipse.core.runtime.jobs.Job;
51 import org.eclipse.debug.core.DebugException;
52 import org.eclipse.debug.core.DebugPlugin;
53 import org.eclipse.debug.core.IExpressionManager;
54 import org.eclipse.debug.core.ILaunch;
55 import org.eclipse.debug.core.ILaunchConfiguration;
56 import org.eclipse.debug.core.ILaunchConfigurationType;
57 import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
58 import org.eclipse.debug.core.ILaunchListener;
59 import org.eclipse.debug.core.ILaunchManager;
60 import org.eclipse.debug.core.IStatusHandler;
61 import org.eclipse.debug.core.Launch;
62 import org.eclipse.debug.core.model.IDebugElement;
63 import org.eclipse.debug.core.model.IDebugTarget;
64 import org.eclipse.debug.core.model.IExpression;
65 import org.eclipse.debug.core.model.IMemoryBlockRetrieval;
66 import org.eclipse.debug.core.model.IProcess;
67 import org.eclipse.debug.core.model.IRegister;
68 import org.eclipse.debug.core.model.IRegisterGroup;
69 import org.eclipse.debug.core.model.IStackFrame;
70 import org.eclipse.debug.core.model.IThread;
71 import org.eclipse.debug.core.model.IVariable;
72 import org.eclipse.debug.internal.ui.contextlaunching.LaunchingResourceManager;
73 import org.eclipse.debug.internal.ui.contexts.SuspendTriggerAdapterFactory;
74 import org.eclipse.debug.internal.ui.launchConfigurations.ClosedProjectFilter;
75 import org.eclipse.debug.internal.ui.launchConfigurations.DeletedProjectFilter;
76 import org.eclipse.debug.internal.ui.launchConfigurations.LaunchConfigurationEditDialog;
77 import org.eclipse.debug.internal.ui.launchConfigurations.LaunchConfigurationManager;
78 import org.eclipse.debug.internal.ui.launchConfigurations.LaunchConfigurationPropertiesDialog;
79 import org.eclipse.debug.internal.ui.launchConfigurations.LaunchConfigurationTypeFilter;
80 import org.eclipse.debug.internal.ui.launchConfigurations.LaunchGroupExtension;
81 import org.eclipse.debug.internal.ui.launchConfigurations.PerspectiveManager;
82 import org.eclipse.debug.internal.ui.sourcelookup.SourceLookupFacility;
83 import org.eclipse.debug.internal.ui.sourcelookup.SourceLookupManager;
84 import org.eclipse.debug.internal.ui.stringsubstitution.SelectedResourceManager;
85 import org.eclipse.debug.internal.ui.views.breakpoints.BreakpointOrganizerManager;
86 import org.eclipse.debug.internal.ui.views.breakpoints.OtherBreakpointCategory;
87 import org.eclipse.debug.internal.ui.views.console.ProcessConsoleManager;
88 import org.eclipse.debug.internal.ui.views.launch.DebugElementAdapterFactory;
89 import org.eclipse.debug.internal.ui.views.launch.DebugElementHelper;
90 import org.eclipse.debug.internal.ui.views.memory.renderings.MemorySegment;
91 import org.eclipse.debug.ui.DebugUITools;
92 import org.eclipse.debug.ui.IDebugModelPresentation;
93 import org.eclipse.debug.ui.IDebugUIConstants;
94 import org.eclipse.debug.ui.ILaunchGroup;
95 import org.eclipse.jface.dialogs.ErrorDialog;
96 import org.eclipse.jface.dialogs.IDialogConstants;
97 import org.eclipse.jface.dialogs.MessageDialogWithToggle;
98 import org.eclipse.jface.operation.IRunnableWithProgress;
99 import org.eclipse.jface.preference.IPreferenceStore;
100 import org.eclipse.jface.preference.PreferenceConverter;
101 import org.eclipse.jface.resource.ImageDescriptor;
102 import org.eclipse.jface.resource.ImageRegistry;
103 import org.eclipse.jface.viewers.ILabelProvider;
104 import org.eclipse.jface.viewers.StructuredSelection;
105 import org.eclipse.jface.window.Window;
106 import org.eclipse.swt.custom.BusyIndicator;
107 import org.eclipse.swt.graphics.Color;
108 import org.eclipse.swt.widgets.Display;
109 import org.eclipse.swt.widgets.Shell;
110 import org.eclipse.ui.IWorkbench;
111 import org.eclipse.ui.IWorkbenchWindow;
112 import org.eclipse.ui.PlatformUI;
113 import org.eclipse.ui.plugin.AbstractUIPlugin;
114 import org.eclipse.ui.progress.IProgressService;
115 import org.osgi.framework.Bundle;
116 import org.osgi.framework.BundleContext;
117 import org.osgi.service.packageadmin.PackageAdmin;
118 import org.osgi.util.tracker.ServiceTracker;
119 import org.w3c.dom.Document JavaDoc;
120
121 import com.ibm.icu.text.MessageFormat;
122
123 /**
124  * The Debug UI Plug-in.
125  *
126  * Since 3.3 this plugin registers an <code>ISaveParticipant</code>, allowing this plugin to participate
127  * in workspace persistence life-cycles
128  *
129  * @see ISaveParticipant
130  * @see ILaunchListener
131  * @see LaunchConfigurationManager
132  * @see PerspectiveManager
133  * @see ContextLaunch
134  */

135 public class DebugUIPlugin extends AbstractUIPlugin implements ILaunchListener {
136     
137     
138     /**
139      * The singleton debug plug-in instance
140      */

141     private static DebugUIPlugin fgDebugUIPlugin = null;
142     
143     /**
144      * A utility presentation used to obtain labels
145      */

146     protected static IDebugModelPresentation fgPresentation = null;
147
148     /**
149      * Default label provider
150      */

151     private static DefaultLabelProvider fgDefaultLabelProvider;
152     
153     /**
154      * Launch configuration attribute - used by the stand-in launch
155      * config working copies that are created while a launch is waiting
156      * for a build to finish. This attribute allows the EditLaunchConfigurationAction
157      * to access the original config if the user asks to edit it.
158      */

159     public static String JavaDoc ATTR_LAUNCHING_CONFIG_HANDLE= getUniqueIdentifier() + "launching_config_handle"; //$NON-NLS-1$
160

161     /**
162      * Singleton console document manager
163      */

164     private ProcessConsoleManager fProcessConsoleManager = null;
165     
166     /**
167      * Perspective manager
168      */

169     private PerspectiveManager fPerspectiveManager = null;
170     
171     /**
172      * Launch configuration manager
173      */

174     private LaunchConfigurationManager fLaunchConfigurationManager = null;
175     
176     /**
177      * Context launching manager
178      */

179     private LaunchingResourceManager fContextLaunchingManager = null;
180     
181     /**
182      * Image descriptor registry used for images with common overlays.
183      *
184      * @since 3.1
185      */

186     private ImageDescriptorRegistry fImageDescriptorRegistry;
187     
188     /**
189      * Service tracker and service used for finding plug-ins associated
190      * with a class.
191      */

192     private ServiceTracker fServiceTracker;
193     private PackageAdmin fPackageAdminService;
194     
195     /**
196      * A set of <code>ISaveParticipant</code>s that want to contribute to saving via this plugin
197      *
198      * @since 3.3
199      */

200     private Set JavaDoc fSaveParticipants = new HashSet JavaDoc();
201     
202     public static boolean DEBUG = false;
203     
204     /**
205      * Dummy launch node representing a launch that is waiting
206      * for a build to finish before proceeding. This node exists
207      * to provide immediate feedback to the user in the Debug view and
208      * allows termination, which equates to cancellation of the launch.
209      */

210     public static class PendingLaunch extends Launch {
211         private Job fJob;
212         public PendingLaunch(ILaunchConfiguration launchConfiguration, String JavaDoc mode, Job job) {
213             super(launchConfiguration, mode, null);
214             fJob= job;
215         }
216
217         // Allow the user to terminate the dummy launch as a means to
218
// cancel the launch while waiting for a build to finish.
219
public boolean canTerminate() {
220             return true;
221         }
222
223         public void terminate() throws DebugException {
224             fJob.cancel();
225         }
226     }
227     
228     /**
229      * Returns the bundle the given class originated from.
230      *
231      * @param clazz a class
232      * @return the bundle the given class originated from, or <code>null</code>
233      * if unable to be determined
234      * @since 3.1
235      */

236     public Bundle getBundle(Class JavaDoc clazz) {
237         if (fPackageAdminService != null) {
238             return fPackageAdminService.getBundle(clazz);
239         }
240         return null;
241     }
242     
243     /**
244      * Constructs the debug UI plug-in
245      */

246     public DebugUIPlugin() {
247         super();
248         fgDebugUIPlugin= this;
249     }
250     
251     /**
252      * If the debug flag is set the specified message is printed to the console
253      * @param message
254      */

255     public static void debug(String JavaDoc message) {
256         if (DEBUG) {
257             System.out.println(message);
258         }
259     }
260         
261     /**
262      * Returns the singleton instance of the debug plug-in.
263      */

264     public static DebugUIPlugin getDefault() {
265         if(fgDebugUIPlugin == null) {
266             fgDebugUIPlugin = new DebugUIPlugin();
267         }
268         return fgDebugUIPlugin;
269     }
270     
271     /**
272      * Convenience method which returns the unique identifier of this plug-in.
273      */

274     public static String JavaDoc getUniqueIdentifier() {
275         return IDebugUIConstants.PLUGIN_ID;
276     }
277
278     /**
279      * Returns the default delegating model presentation
280      * @return the default delegating model presentation
281      */

282     public static IDebugModelPresentation getModelPresentation() {
283         if (fgPresentation == null) {
284             fgPresentation = new DelegatingModelPresentation();
285         }
286         return fgPresentation;
287     }
288     
289     /**
290      * Returns the launch configuration manager
291      * @return the launch configuration manager
292      */

293     public LaunchConfigurationManager getLaunchConfigurationManager() {
294         if (fLaunchConfigurationManager == null) {
295             fLaunchConfigurationManager = new LaunchConfigurationManager();
296         }
297         return fLaunchConfigurationManager;
298     }
299     
300     /**
301      * Returns the context launching resource manager. If one has not been created prior to this
302      * method call, a new manager is created and initialized, by calling its startup() method.
303      * @return the context launching resource manager
304      *
305      * @since 3.3
306      */

307     public LaunchingResourceManager getLaunchingResourceManager() {
308         if(fContextLaunchingManager == null) {
309             fContextLaunchingManager = new LaunchingResourceManager();
310             fContextLaunchingManager.startup();
311         }
312         return fContextLaunchingManager;
313     }
314     
315     /**
316      * Returns the currently active workbench window or <code>null</code>
317      * if none.
318      *
319      * @return the currently active workbench window or <code>null</code>
320      */

321     public static IWorkbenchWindow getActiveWorkbenchWindow() {
322         return getDefault().getWorkbench().getActiveWorkbenchWindow();
323     }
324     
325     /**
326      * Returns the currently active workbench window shell or <code>null</code>
327      * if none.
328      *
329      * @return the currently active workbench window shell or <code>null</code>
330      */

331     public static Shell getShell() {
332         IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
333         if (window == null) {
334             IWorkbenchWindow[] windows = PlatformUI.getWorkbench().getWorkbenchWindows();
335             if (windows.length > 0) {
336                 return windows[0].getShell();
337             }
338         }
339         else {
340             return window.getShell();
341         }
342         return null;
343     }
344
345     /**
346      * Returns the default label provider for the debug UI.
347      */

348     public static ILabelProvider getDefaultLabelProvider() {
349         if (fgDefaultLabelProvider == null) {
350             fgDefaultLabelProvider = new DefaultLabelProvider();
351         }
352         return fgDefaultLabelProvider;
353     }
354
355     /**
356      * Creates an extension. If the extension plug-in has not
357      * been loaded a busy cursor will be activated during the duration of
358      * the load.
359      *
360      * @param element the config element defining the extension
361      * @param classAttribute the name of the attribute carrying the class
362      * @return the extension object
363      */

364     public static Object JavaDoc createExtension(final IConfigurationElement element, final String JavaDoc classAttribute) throws CoreException {
365         // If plug-n has been loaded create extension.
366
// Otherwise, show busy cursor then create extension.
367
Bundle bundle = Platform.getBundle(element.getContributor().getName());
368         if (bundle.getState() == Bundle.ACTIVE) {
369             return element.createExecutableExtension(classAttribute);
370         }
371         final Object JavaDoc [] ret = new Object JavaDoc[1];
372         final CoreException [] exc = new CoreException[1];
373         BusyIndicator.showWhile(null, new Runnable JavaDoc() {
374             public void run() {
375                 try {
376                     ret[0] = element.createExecutableExtension(classAttribute);
377                 } catch (CoreException e) {
378                     exc[0] = e;
379                 }
380             }
381         });
382         if (exc[0] != null) {
383             throw exc[0];
384         }
385         return ret[0];
386     }
387     
388     /**
389      * @see org.eclipse.ui.plugin.AbstractUIPlugin#createImageRegistry()
390      */

391     protected ImageRegistry createImageRegistry() {
392         return DebugPluginImages.initializeImageRegistry();
393     }
394
395     /* (non-Javadoc)
396      * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
397      */

398     public void stop(BundleContext context) throws Exception JavaDoc {
399         try {
400             if (fProcessConsoleManager != null) {
401                 fProcessConsoleManager.shutdown();
402             }
403             
404             BreakpointOrganizerManager.getDefault().shutdown();
405             
406             if (fPerspectiveManager != null) {
407                 fPerspectiveManager.shutdown();
408             }
409             if (fLaunchConfigurationManager != null) {
410                 fLaunchConfigurationManager.shutdown();
411             }
412             if(fContextLaunchingManager != null) {
413                 fContextLaunchingManager.shutdown();
414             }
415     
416             ColorManager.getDefault().dispose();
417             
418             if (fgPresentation != null) {
419                 fgPresentation.dispose();
420             }
421             
422             if (fImageDescriptorRegistry != null) {
423                 fImageDescriptorRegistry.dispose();
424             }
425             
426             SourceLookupFacility.shutdown();
427             
428             DebugElementHelper.dispose();
429             
430             fServiceTracker.close();
431             fPackageAdminService = null;
432             
433             fSaveParticipants.clear();
434             
435             ResourcesPlugin.getWorkspace().removeSaveParticipant(this);
436             
437         } finally {
438             super.stop(context);
439         }
440     }
441
442     /**
443      * Add the specified <code>ISaveParticipant</code> to the current listing of
444      * registered participants
445      * @param participant
446      * @return true if this current listing did not already contain the specified participant
447      * @since 3.3
448      */

449     public boolean addSaveParticipant(ISaveParticipant participant) {
450         return fSaveParticipants.add(participant);
451     }
452     
453     /**
454      * Removes the specified <code>ISaveParticipant</code> from the current listing of registered
455      * participants
456      * @param participant
457      * @return true if the set contained the specified element
458      *
459      * @since 3.3
460      */

461     public boolean removeSaveParticipant(ISaveParticipant participant) {
462         return fSaveParticipants.remove(participant);
463     }
464     
465     /**
466      * @see AbstractUIPlugin#startup()
467      */

468     public void start(BundleContext context) throws Exception JavaDoc {
469         super.start(context);
470         ResourcesPlugin.getWorkspace().addSaveParticipant(this,
471                 new ISaveParticipant() {
472                     public void saving(ISaveContext saveContext) throws CoreException {
473                         savePluginPreferences();
474                         for(Iterator JavaDoc iter = fSaveParticipants.iterator(); iter.hasNext();) {
475                             ((ISaveParticipant)iter.next()).saving(saveContext);
476                         }
477                     }
478                     public void rollback(ISaveContext saveContext) {
479                         for(Iterator JavaDoc iter = fSaveParticipants.iterator(); iter.hasNext();) {
480                             ((ISaveParticipant)iter.next()).rollback(saveContext);
481                         }
482                     }
483                     public void prepareToSave(ISaveContext saveContext) throws CoreException {
484                         for(Iterator JavaDoc iter = fSaveParticipants.iterator(); iter.hasNext();) {
485                             ((ISaveParticipant)iter.next()).prepareToSave(saveContext);
486                         }
487                     }
488                     public void doneSaving(ISaveContext saveContext) {
489                         for(Iterator JavaDoc iter = fSaveParticipants.iterator(); iter.hasNext();) {
490                             ((ISaveParticipant)iter.next()).doneSaving(saveContext);
491                         }
492                     }
493                 });
494         DEBUG = "true".equals(Platform.getDebugOption("org.eclipse.debug.ui/debug")); //$NON-NLS-1$//$NON-NLS-2$
495

496         // make sure the perspective manager is created
497
// and be the first debug event listener
498
fPerspectiveManager = new PerspectiveManager();
499         fPerspectiveManager.startup();
500         
501         getLaunchingResourceManager();
502         
503         // Listen to launches to lazily create "launch processors"
504
DebugPlugin.getDefault().getLaunchManager().addLaunchListener(this);
505         
506         // start the breakpoint organizer manager
507
BreakpointOrganizerManager.getDefault();
508         
509         IAdapterManager manager= Platform.getAdapterManager();
510         DebugElementAdapterFactory propertiesFactory = new DebugElementAdapterFactory();
511         manager.registerAdapters(propertiesFactory, ILaunchManager.class);
512         manager.registerAdapters(propertiesFactory, ILaunch.class);
513         manager.registerAdapters(propertiesFactory, IDebugTarget.class);
514         manager.registerAdapters(propertiesFactory, IProcess.class);
515         manager.registerAdapters(propertiesFactory, IThread.class);
516         manager.registerAdapters(propertiesFactory, IStackFrame.class);
517         manager.registerAdapters(propertiesFactory, IRegisterGroup.class);
518         manager.registerAdapters(propertiesFactory, IVariable.class);
519         manager.registerAdapters(propertiesFactory, IRegister.class);
520         manager.registerAdapters(propertiesFactory, IExpression.class);
521         manager.registerAdapters(propertiesFactory, IExpressionManager.class);
522         manager.registerAdapters(propertiesFactory, OtherBreakpointCategory.class);
523         manager.registerAdapters(propertiesFactory, IDebugElement.class);
524         manager.registerAdapters(propertiesFactory, IMemoryBlockRetrieval.class);
525         manager.registerAdapters(propertiesFactory, MemorySegment.class);
526         DebugUIAdapterFactory uiFactory = new DebugUIAdapterFactory();
527         manager.registerAdapters(uiFactory, ILaunchConfiguration.class);
528         manager.registerAdapters(uiFactory, ILaunchConfigurationType.class);
529         SuspendTriggerAdapterFactory factory = new SuspendTriggerAdapterFactory();
530         manager.registerAdapters(factory, ILaunch.class);
531         
532         getStandardDisplay().asyncExec(
533             new Runnable JavaDoc() {
534                 public void run() {
535                     //initialize the selected resource `
536
SelectedResourceManager.getDefault();
537                     // forces launch shortcuts to be initialized so their key-bindings work
538
getLaunchConfigurationManager().getLaunchShortcuts();
539                 }
540             });
541         
542         fServiceTracker = new ServiceTracker(context, PackageAdmin.class.getName(), null);
543         fServiceTracker.open();
544         fPackageAdminService = (PackageAdmin) fServiceTracker.getService();
545         
546         getLaunchConfigurationManager().startup();
547     }
548
549     /**
550      * Utility method with conventions
551      */

552     public static void errorDialog(Shell shell, String JavaDoc title, String JavaDoc message, IStatus s) {
553         // if the 'message' resource string and the IStatus' message are the same,
554
// don't show both in the dialog
555
if (s != null && message.equals(s.getMessage())) {
556             message= null;
557         }
558         ErrorDialog.openError(shell, title, message, s);
559     }
560     
561     /**
562      * Utility method with conventions
563      */

564     public static void errorDialog(Shell shell, String JavaDoc title, String JavaDoc message, Throwable JavaDoc t) {
565         IStatus status;
566         if (t instanceof CoreException) {
567             status= ((CoreException)t).getStatus();
568             // if the 'message' resource string and the IStatus' message are the same,
569
// don't show both in the dialog
570
if (status != null && message.equals(status.getMessage())) {
571                 message= null;
572             }
573         } else {
574             status= new Status(IStatus.ERROR, getUniqueIdentifier(), IDebugUIConstants.INTERNAL_ERROR, "Error within Debug UI: ", t); //$NON-NLS-1$
575
log(status);
576         }
577         ErrorDialog.openError(shell, title, message, status);
578     }
579
580     /**
581      * Logs the specified status with this plug-in's log.
582      *
583      * @param status status to log
584      */

585     public static void log(IStatus status) {
586         getDefault().getLog().log(status);
587     }
588     
589     /**
590      * Logs the specified throwable with this plug-in's log.
591      *
592      * @param t throwable to log
593      */

594     public static void log(Throwable JavaDoc t) {
595         log(newErrorStatus("Error logged from Debug UI: ", t)); //$NON-NLS-1$
596
}
597     
598     /**
599      * Logs an internal error with the specified message.
600      *
601      * @param message the error message to log
602      */

603     public static void logErrorMessage(String JavaDoc message) {
604         // this message is intentionally not internationalized, as an exception may
605
// be due to the resource bundle itself
606
log(newErrorStatus("Internal message logged from Debug UI: " + message, null)); //$NON-NLS-1$
607
}
608     
609     /**
610      * Returns a new error status for this plug-in with the given message
611      * @param message the message to be included in the status
612      * @param exception the exception to be included in the status or <code>null</code> if none
613      * @return a new error status
614      */

615     public static IStatus newErrorStatus(String JavaDoc message, Throwable JavaDoc exception) {
616         return new Status(IStatus.ERROR, getUniqueIdentifier(), IDebugUIConstants.INTERNAL_ERROR, message, exception);
617     }
618     
619     /**
620      * Open the launch configuration dialog on the specified launch
621      * configuration. The dialog displays the tabs for a single configuration
622      * only (a tree of launch configuration is not displayed)
623      * <p>
624      * If a status is specified, a status handler is consulted to handle the
625      * status. The status handler is passed the instance of the launch
626      * configuration dialog that is opened. This gives the status handler an
627      * opportunity to perform error handling/initialization as required.
628      * </p>
629      * @param shell the parent shell for the launch configuration dialog
630      * @param configuration the configuration to display
631      * @param groupIdentifier group identifier of the launch group the launch configuration
632      * belongs to
633      * @param status the status to display, or <code>null</code> if none
634      * @param showCancel if the cancel button should be shown in the particular instance of the dialog
635      * @return the return code from opening the launch configuration dialog -
636      * one of <code>Window.OK</code> or <code>Window.CANCEL</code>
637      *
638      * @since 3.3
639      *
640      */

641     public static int openLaunchConfigurationEditDialog(Shell shell, ILaunchConfiguration configuration, String JavaDoc groupIdentifier, IStatus status, boolean showCancel) {
642         LaunchGroupExtension group = DebugUIPlugin.getDefault().getLaunchConfigurationManager().getLaunchGroup(groupIdentifier);
643         if (group != null) {
644             LaunchConfigurationEditDialog dialog = new LaunchConfigurationEditDialog(shell, configuration, group, showCancel);
645             dialog.setInitialStatus(status);
646             return dialog.open();
647         }
648         return Window.CANCEL;
649     }
650     
651     /**
652      * Open the launch configuration dialog on the specified launch
653      * configuration. The dialog displays the tabs for a single configuration
654      * only (a tree of launch configuration is not displayed)
655      * <p>
656      * If a status is specified, a status handler is consulted to handle the
657      * status. The status handler is passed the instance of the launch
658      * configuration dialog that is opened. This gives the status handler an
659      * opportunity to perform error handling/initialization as required.
660      * </p>
661      * @param shell the parent shell for the launch configuration dialog
662      * @param configuration the configuration to display
663      * @param groupIdentifier group identifier of the launch group the launch configuration
664      * belongs to
665      * @param reservednames a set of launch configuration names that cannot be used when creating or renaming
666      * the specified launch configuration
667      * @param status the status to display, or <code>null</code> if none
668      * @param setDefaults whether to set default values in the configuration
669      * @return the return code from opening the launch configuration dialog -
670      * one of <code>Window.OK</code> or <code>Window.CANCEL</code>
671      *
672      * @since 3.3
673      *
674      */

675     public static int openLaunchConfigurationPropertiesDialog(Shell shell, ILaunchConfiguration configuration, String JavaDoc groupIdentifier, Set JavaDoc reservednames, IStatus status, boolean setDefaults) {
676         LaunchGroupExtension group = DebugUIPlugin.getDefault().getLaunchConfigurationManager().getLaunchGroup(groupIdentifier);
677         if (group != null) {
678             LaunchConfigurationPropertiesDialog dialog = new LaunchConfigurationPropertiesDialog(shell, configuration, group, reservednames);
679             dialog.setInitialStatus(status);
680             dialog.setDefaultsOnOpen(setDefaults);
681             return dialog.open();
682         }
683         return Window.CANCEL;
684     }
685     
686     /**
687      * Save all dirty editors in the workbench.
688      * Returns whether the operation succeeded.
689      *
690      * @return whether all saving was completed
691      * @deprecated Saving has been moved to the launch delegate <code>LaunchConfigurationDelegate</code> to allow for scoped saving
692      * of resources that are only involved in the current launch, no longer the entire workspace
693      */

694     protected static boolean saveAllEditors(boolean confirm) {
695         if (getActiveWorkbenchWindow() == null) {
696             return false;
697         }
698         return PlatformUI.getWorkbench().saveAllEditors(confirm);
699     }
700     
701     /**
702      * Save & build the workspace according to the user-specified preferences. Return <code>false</code> if
703      * any problems were encountered, <code>true</code> otherwise.
704      *
705      * @deprecated this method is no longer to be used. It is an artifact from 2.0, and all saving is now done with the
706      * launch delegate <code>LaunchConfigurationDelegate</code>
707      */

708     public static boolean saveAndBuild() {
709         boolean status = true;
710         String JavaDoc saveDirty = getDefault().getPreferenceStore().getString(IInternalDebugUIConstants.PREF_SAVE_DIRTY_EDITORS_BEFORE_LAUNCH);
711         boolean buildBeforeLaunch = getDefault().getPreferenceStore().getBoolean(IDebugUIConstants.PREF_BUILD_BEFORE_LAUNCH);
712         
713         // If we're ignoring dirty editors, check if we need to build
714
if (saveDirty.equals(MessageDialogWithToggle.NEVER)) {
715             if (buildBeforeLaunch) {
716                 return doBuild();
717             }
718         } else {
719             status = saveAllEditors(saveDirty.equals(MessageDialogWithToggle.PROMPT));
720             if (status && buildBeforeLaunch) {
721                 status = doBuild();
722             }
723         }
724                 
725         return status;
726     }
727     
728     private static boolean doBuild() {
729         try {
730             PlatformUI.getWorkbench().getProgressService().busyCursorWhile(new IRunnableWithProgress() {
731                 public void run(IProgressMonitor monitor) throws InvocationTargetException JavaDoc {
732                     try {
733                         ResourcesPlugin.getWorkspace().build(IncrementalProjectBuilder.INCREMENTAL_BUILD, monitor);
734                     } catch (CoreException e) {
735                         throw new InvocationTargetException JavaDoc(e);
736                     }
737                 }
738             });
739         } catch (InterruptedException JavaDoc e) {
740             // canceled by user
741
return false;
742         } catch (InvocationTargetException JavaDoc e) {
743             String JavaDoc title= DebugUIMessages.DebugUIPlugin_Run_Debug_1;
744             String JavaDoc message= DebugUIMessages.DebugUIPlugin_Build_error__Check_log_for_details__2;
745             Throwable JavaDoc t = e.getTargetException();
746             errorDialog(getShell(), title, message, t);
747             return false;
748         }
749         return true;
750     }
751     
752     /**
753      * Returns the standard display to be used. The method first checks, if
754      * the thread calling this method has an associated display. If so, this
755      * display is returned. Otherwise the method returns the default display.
756      *
757      */

758     public static Display getStandardDisplay() {
759         Display display= Display.getCurrent();
760         if (display == null) {
761             display= Display.getDefault();
762         }
763         return display;
764     }
765     
766     /**
767      * Returns the a color based on the type of output.
768      * Valid types:
769      * <li>CONSOLE_SYS_OUT_RGB</li>
770      * <li>CONSOLE_SYS_ERR_RGB</li>
771      * <li>CONSOLE_SYS_IN_RGB</li>
772      * <li>CHANGED_VARIABLE_RGB</li>
773      */

774     public static Color getPreferenceColor(String JavaDoc type) {
775         return ColorManager.getDefault().getColor(PreferenceConverter.getColor(getDefault().getPreferenceStore(), type));
776     }
777
778     /**
779      * Returns the process console manager. The manager will be created lazily on
780      * the first access.
781      *
782      * @return ProcessConsoleManager
783      */

784     public ProcessConsoleManager getProcessConsoleManager() {
785         if (fProcessConsoleManager == null) {
786             fProcessConsoleManager = new ProcessConsoleManager();
787         }
788         return fProcessConsoleManager;
789     }
790     
791     /**
792      * Serializes a XML document into a string - encoded in UTF8 format,
793      * with platform line separators.
794      *
795      * @param doc document to serialize
796      * @return the document as a string
797      * @throws TransformerException if an unrecoverable error occurs during the serialization
798      * @throws IOException if the encoding attempted to be used is not supported
799      */

800     public static String JavaDoc serializeDocument(Document JavaDoc doc) throws TransformerException JavaDoc, IOException JavaDoc {
801         ByteArrayOutputStream JavaDoc s= new ByteArrayOutputStream JavaDoc();
802         
803         TransformerFactory JavaDoc factory= TransformerFactory.newInstance();
804         
805         Transformer JavaDoc transformer= factory.newTransformer();
806         transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
807
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
808

809         DOMSource JavaDoc source= new DOMSource JavaDoc(doc);
810         StreamResult JavaDoc outputTarget= new StreamResult JavaDoc(s);
811         transformer.transform(source, outputTarget);
812         
813         return s.toString("UTF8"); //$NON-NLS-1$
814
}
815     
816     /**
817      * Returns a Document that can be used to build a DOM tree
818      * @return the Document
819      * @throws ParserConfigurationException if an exception occurs creating the document builder
820      * @since 3.0
821      */

822     public static Document JavaDoc getDocument() throws ParserConfigurationException JavaDoc {
823         DocumentBuilderFactory JavaDoc dfactory= DocumentBuilderFactory.newInstance();
824
825         DocumentBuilder JavaDoc docBuilder= dfactory.newDocumentBuilder();
826         Document JavaDoc doc= docBuilder.newDocument();
827         return doc;
828     }
829         
830     /**
831      * When the first launch is added, instantiate launch processors,
832      * and stop listening to launch notifications.
833      * <p>
834      * Launch processors are:
835      * <ul>
836      * <li>console document manager</li>
837      * <li>perspective manager</li>
838      * </ul>
839      * </p>
840      * @see org.eclipse.debug.core.ILaunchListener#launchAdded(org.eclipse.debug.core.ILaunch)
841      */

842     public void launchAdded(ILaunch launch) {
843         DebugPlugin.getDefault().getLaunchManager().removeLaunchListener(this);
844         getProcessConsoleManager().startup();
845         SourceLookupManager.getDefault();
846     }
847     
848     /**
849      * Returns the perspective manager.
850      *
851      * @return
852      */

853     public PerspectiveManager getPerspectiveManager() {
854         return fPerspectiveManager;
855     }
856
857     /**
858      * @see org.eclipse.debug.core.ILaunchListener#launchChanged(org.eclipse.debug.core.ILaunch)
859      */

860     public void launchChanged(ILaunch launch) {}
861
862     /**
863      * @see org.eclipse.debug.core.ILaunchListener#launchRemoved(org.eclipse.debug.core.ILaunch)
864      */

865     public void launchRemoved(ILaunch launch) {}
866
867     /**
868      * Save dirty editors before launching, according to preferences.
869      *
870      * @return whether to proceed with launch
871      * @deprecated Saving has been moved to the launch delegate <code>LaunchConfigurationDelegate</code> to allow for scoped saving
872      * of resources that are only involved in the current launch, no longer the entire workspace
873      */

874     public static boolean preLaunchSave() {
875         String JavaDoc saveDirty = getDefault().getPreferenceStore().getString(IInternalDebugUIConstants.PREF_SAVE_DIRTY_EDITORS_BEFORE_LAUNCH);
876         if (saveDirty.equals(MessageDialogWithToggle.NEVER)) {
877             return true;
878         }
879         return saveAllEditors(saveDirty.equals(MessageDialogWithToggle.PROMPT));
880     }
881     
882     /**
883      * Builds the workspace (according to preferences) and launches the given launch
884      * configuration in the specified mode. May return null if auto build is in process and
885      * user cancels the launch.
886      *
887      * @param configuration the configuration to launch
888      * @param mode launch mode - run or debug
889      * @param monitor progress monitor
890      * @exception CoreException if an exception occurs while building or launching
891      * @return resulting launch or <code>null</code> if user cancels
892      */

893     public static ILaunch buildAndLaunch(ILaunchConfiguration configuration, String JavaDoc mode, IProgressMonitor monitor) throws CoreException {
894         boolean buildBeforeLaunch = getDefault().getPreferenceStore().getBoolean(IDebugUIConstants.PREF_BUILD_BEFORE_LAUNCH);
895         
896         monitor.beginTask("", 1); //$NON-NLS-1$
897
try
898         {
899             return configuration.launch(
900                     mode,
901                     new SubProgressMonitor(monitor, 1),
902                     buildBeforeLaunch);
903         }
904         finally
905         {
906             monitor.done();
907         }
908     }
909     
910     /**
911      * Saves and builds the workspace according to current preference settings and
912      * launches the given launch configuration in the specified mode in the
913      * foreground with a progress dialog. Reports any exceptions that occur
914      * in an error dialog.
915      *
916      * @param configuration the configuration to launch
917      * @param mode launch mode
918      * @since 3.0
919      */

920     public static void launchInForeground(final ILaunchConfiguration configuration, final String JavaDoc mode) {
921         final IJobManager jobManager = Job.getJobManager();
922         IPreferenceStore store = DebugUIPlugin.getDefault().getPreferenceStore();
923         boolean wait = false;
924         
925         if (jobManager.find(ResourcesPlugin.FAMILY_AUTO_BUILD).length > 0 || jobManager.find(ResourcesPlugin.FAMILY_MANUAL_BUILD).length >0) {
926             String JavaDoc waitForBuild = store.getString(IInternalDebugUIConstants.PREF_WAIT_FOR_BUILD);
927
928             if (waitForBuild.equals(MessageDialogWithToggle.PROMPT)) {
929                 MessageDialogWithToggle dialog = MessageDialogWithToggle.openYesNoCancelQuestion(getShell(), DebugUIMessages.DebugUIPlugin_23, DebugUIMessages.DebugUIPlugin_24, null, false, store, IInternalDebugUIConstants.PREF_WAIT_FOR_BUILD); //
930

931                 switch (dialog.getReturnCode()) {
932                     case IDialogConstants.CANCEL_ID:
933                         return;
934                     case IDialogConstants.YES_ID:
935                         wait = false;
936                         break;
937                     case IDialogConstants.NO_ID:
938                         wait = true;
939                         break;
940                 }
941             } else if (waitForBuild.equals(MessageDialogWithToggle.ALWAYS)) {
942                 wait = true;
943             }
944         }
945
946         if (wait) {
947             IWorkbench workbench = DebugUIPlugin.getDefault().getWorkbench();
948             IProgressService progressService = workbench.getProgressService();
949             final IRunnableWithProgress runnable = new IRunnableWithProgress() {
950                 public void run(IProgressMonitor monitor) throws InvocationTargetException JavaDoc {
951                     /* Setup progress monitor
952                      * - Waiting for jobs to finish (2)
953                      * - Build & launch (98) */

954                     monitor.beginTask(MessageFormat.format(DebugUIMessages.DebugUIPlugin_25, new Object JavaDoc[] {configuration.getName()}), 100);
955
956                     try {
957                         jobManager.join(ResourcesPlugin.FAMILY_MANUAL_BUILD, new SubProgressMonitor(monitor, 1));
958                         jobManager.join(ResourcesPlugin.FAMILY_AUTO_BUILD, new SubProgressMonitor(monitor, 1));
959                     }
960                     catch (InterruptedException JavaDoc e) {/* continue*/}
961                     if (!monitor.isCanceled()) {
962                         try {
963                             buildAndLaunch(configuration, mode, new SubProgressMonitor(monitor, 98));
964                         }
965                         catch (CoreException e) {
966                             throw new InvocationTargetException JavaDoc(e);
967                         }
968                     }
969                 }
970             };
971             try {
972                 progressService.busyCursorWhile(runnable);
973             }
974             catch (InterruptedException JavaDoc e) {}
975             catch (InvocationTargetException JavaDoc e2) {
976                 handleInvocationTargetException(e2, configuration, mode);
977             }
978         } else {
979             IRunnableWithProgress runnable = new IRunnableWithProgress() {
980                 public void run(IProgressMonitor monitor) throws InvocationTargetException JavaDoc {
981                     /* Setup progress monitor
982                      * - Build & launch (1) */

983                     monitor.beginTask(MessageFormat.format(DebugUIMessages.DebugUIPlugin_25, new Object JavaDoc[] {configuration.getName()}), 1);
984                     try {
985                         buildAndLaunch(configuration, mode, new SubProgressMonitor(monitor, 1));
986                     }
987                     catch (CoreException e) {
988                         throw new InvocationTargetException JavaDoc(e);
989                     }
990                 }
991             };
992             try {
993                 PlatformUI.getWorkbench().getProgressService().busyCursorWhile(runnable);
994             }
995             catch (InvocationTargetException JavaDoc e) {
996                 handleInvocationTargetException(e, configuration, mode);
997             }
998             catch (InterruptedException JavaDoc e) {}
999
1000        }
1001    }
1002    
1003    private static void handleInvocationTargetException(InvocationTargetException JavaDoc e, ILaunchConfiguration configuration, String JavaDoc mode) {
1004        Throwable JavaDoc targetException = e.getTargetException();
1005        Throwable JavaDoc t = e;
1006        if (targetException instanceof CoreException) {
1007            t = targetException;
1008        }
1009        if (t instanceof CoreException) {
1010            CoreException ce = (CoreException)t;
1011            IStatusHandler handler = DebugPlugin.getDefault().getStatusHandler(ce.getStatus());
1012            if (handler != null) {
1013                ILaunchGroup group = DebugUITools.getLaunchGroup(configuration, mode);
1014                if (group != null) {
1015                    DebugUITools.openLaunchConfigurationDialogOnGroup(DebugUIPlugin.getShell(), new StructuredSelection(configuration), group.getIdentifier(), ce.getStatus());
1016                    return;
1017                }
1018            }
1019            if ((ce.getStatus().getSeverity() & (IStatus.ERROR | IStatus.WARNING)) == 0) {
1020                // If the exception is a CoreException with a status other
1021
// than ERROR or WARNING, don't open an error dialog.
1022
return;
1023            }
1024        }
1025        DebugUIPlugin.errorDialog(DebugUIPlugin.getShell(), DebugUIMessages.DebugUITools_Error_1, DebugUIMessages.DebugUITools_Exception_occurred_during_launch_2, t); //
1026
}
1027    
1028    /**
1029     * Saves and builds the workspace according to current preference settings and
1030     * launches the given launch configuration in the specified mode in a background
1031     * Job with progress reported via the Job. Exceptions are reported in the Progress
1032     * view.
1033     *
1034     * @param configuration the configuration to launch
1035     * @param mode launch mode
1036     * @since 3.0
1037     */

1038    public static void launchInBackground(final ILaunchConfiguration configuration, final String JavaDoc mode) {
1039        final IJobManager jobManager = Job.getJobManager();
1040        IPreferenceStore store = DebugUIPlugin.getDefault().getPreferenceStore();
1041        boolean wait = (jobManager.find(ResourcesPlugin.FAMILY_AUTO_BUILD).length > 0) || (jobManager.find(ResourcesPlugin.FAMILY_MANUAL_BUILD).length > 0);
1042        String JavaDoc waitPref = store.getString(IInternalDebugUIConstants.PREF_WAIT_FOR_BUILD);
1043        if (wait) { // if there are build jobs running, do we wait or not??
1044
if (waitPref.equals(MessageDialogWithToggle.PROMPT)) {
1045                MessageDialogWithToggle dialog = MessageDialogWithToggle.openYesNoCancelQuestion(getShell(), DebugUIMessages.DebugUIPlugin_23, DebugUIMessages.DebugUIPlugin_24, null, false, store, IInternalDebugUIConstants.PREF_WAIT_FOR_BUILD); //
1046
switch (dialog.getReturnCode()) {
1047                    case IDialogConstants.CANCEL_ID:
1048                        return;
1049                    case IDialogConstants.YES_ID:
1050                        wait = true;
1051                        break;
1052                    case IDialogConstants.NO_ID:
1053                        wait = false;
1054                        break;
1055                }
1056            }
1057            else {
1058                wait = waitPref.equals(MessageDialogWithToggle.ALWAYS);
1059            }
1060        }
1061        final boolean waitInJob = wait;
1062        Job job = new Job(MessageFormat.format(DebugUIMessages.DebugUIPlugin_25, new Object JavaDoc[] {configuration.getName()})) {
1063            public IStatus run(final IProgressMonitor monitor) {
1064                /* Setup progress monitor
1065                 * - Waiting for jobs to finish (2)
1066                 * - Build & launch (98) */

1067                monitor.beginTask(DebugUIMessages.DebugUITools_3, 100);
1068                try {
1069                    if(waitInJob) {
1070                        StringBuffer JavaDoc buffer = new StringBuffer JavaDoc(configuration.getName());
1071                        buffer.append(DebugUIMessages.DebugUIPlugin_0);
1072                        ILaunchConfigurationWorkingCopy workingCopy = configuration.copy(buffer.toString());
1073                        workingCopy.setAttribute(ATTR_LAUNCHING_CONFIG_HANDLE, configuration.getMemento());
1074                        final ILaunch pendingLaunch = new PendingLaunch(workingCopy, mode, this);
1075                        DebugPlugin.getDefault().getLaunchManager().addLaunch(pendingLaunch);
1076                        IJobChangeListener listener= new IJobChangeListener() {
1077                            public void sleeping(IJobChangeEvent event) {}
1078                            public void scheduled(IJobChangeEvent event) {}
1079                            public void running(IJobChangeEvent event) {}
1080                            public void awake(IJobChangeEvent event) {}
1081                            public void aboutToRun(IJobChangeEvent event) {}
1082                            public void done(IJobChangeEvent event) {
1083                                DebugPlugin dp = DebugPlugin.getDefault();
1084                                if (dp != null) {
1085                                    dp.getLaunchManager().removeLaunch(pendingLaunch);
1086                                }
1087                                removeJobChangeListener(this);
1088                            }
1089                        };
1090                        addJobChangeListener(listener);
1091                        try {
1092                            jobManager.join(ResourcesPlugin.FAMILY_MANUAL_BUILD, new SubProgressMonitor(monitor, 1));
1093                            jobManager.join(ResourcesPlugin.FAMILY_AUTO_BUILD, new SubProgressMonitor(monitor, 1));
1094                        }
1095                        catch (InterruptedException JavaDoc e) {/*just continue.*/}
1096                        DebugPlugin.getDefault().getLaunchManager().removeLaunch(pendingLaunch);
1097                    }
1098                    else {
1099                        monitor.worked(2); /* don't wait for jobs to finish */
1100                    }
1101                    if (!monitor.isCanceled()) {
1102                        buildAndLaunch(configuration, mode, new SubProgressMonitor(monitor, 98));
1103                    }
1104                } catch (CoreException e) {
1105                    final IStatus status = e.getStatus();
1106                    IStatusHandler handler = DebugPlugin.getDefault().getStatusHandler(status);
1107                    if (handler == null) {
1108                        return status;
1109                    }
1110                    final ILaunchGroup group = DebugUITools.getLaunchGroup(configuration, mode);
1111                    if (group == null) {
1112                        return status;
1113                    }
1114                    Runnable JavaDoc r = new Runnable JavaDoc() {
1115                        public void run() {
1116                            DebugUITools.openLaunchConfigurationDialogOnGroup(DebugUIPlugin.getShell(), new StructuredSelection(configuration), group.getIdentifier(), status);
1117                        }
1118                    };
1119                    DebugUIPlugin.getStandardDisplay().asyncExec(r);
1120                }
1121                finally {
1122                    monitor.done();
1123                }
1124                
1125                return Status.OK_STATUS;
1126            }
1127        };
1128
1129        IWorkbench workbench = DebugUIPlugin.getDefault().getWorkbench();
1130        IProgressService progressService = workbench.getProgressService();
1131
1132        job.setPriority(Job.INTERACTIVE);
1133        job.setName(MessageFormat.format(DebugUIMessages.DebugUIPlugin_25, new Object JavaDoc[] {configuration.getName()}));
1134        
1135        if (wait) {
1136            progressService.showInDialog(workbench.getActiveWorkbenchWindow().getShell(), job);
1137        }
1138        job.schedule();
1139    }
1140
1141    /**
1142     * Returns the label with any accelerators removed.
1143     *
1144     * @return label without accelerators
1145     */

1146    public static String JavaDoc removeAccelerators(String JavaDoc label) {
1147        String JavaDoc title = label;
1148        if (title != null) {
1149            // strip out any '&' (accelerators)
1150
int index = title.indexOf('&');
1151            if (index == 0) {
1152                title = title.substring(1);
1153            } else if (index > 0) {
1154                //DBCS languages use "(&X)" format
1155
if (title.charAt(index - 1) == '(' && title.length() >= index + 3 && title.charAt(index + 2) == ')') {
1156                    String JavaDoc first = title.substring(0, index - 1);
1157                    String JavaDoc last = title.substring(index + 3);
1158                    title = first + last;
1159                } else if (index < (title.length() - 1)) {
1160                    String JavaDoc first = title.substring(0, index);
1161                    String JavaDoc last = title.substring(index + 1);
1162                    title = first + last;
1163                }
1164            }
1165        }
1166        return title;
1167    }
1168    
1169    /**
1170     * Returns the label with any DBCS accelerator moved to the end of the string.
1171     * See bug 186921.
1172     *
1173     * @return label with moved accelerator
1174     */

1175    public static String JavaDoc adjustDBCSAccelerator(String JavaDoc label) {
1176        String JavaDoc title = label;
1177        if (title != null) {
1178            // strip out any '&' (accelerators)
1179
int index = title.indexOf('&');
1180            if (index > 0) {
1181                //DBCS languages use "(&X)" format
1182
if (title.charAt(index - 1) == '(' && title.length() >= index + 3 && title.charAt(index + 2) == ')') {
1183                    String JavaDoc first = title.substring(0, index - 1);
1184                    String JavaDoc accel = title.substring(index - 1, index + 3);
1185                    String JavaDoc last = title.substring(index + 3);
1186                    title = first + last;
1187                    if (title.endsWith("...")) { //$NON-NLS-1$
1188
title = title.substring(0, title.length() - 3);
1189                        title = title + accel + "..."; //$NON-NLS-1$
1190
} else {
1191                        title = title + accel;
1192                    }
1193                }
1194            }
1195        }
1196        return title;
1197    }
1198
1199    /**
1200     * Returns the image descriptor registry used for this plug-in.
1201     *
1202     * @since 3.1
1203     */

1204    public static ImageDescriptorRegistry getImageDescriptorRegistry() {
1205        if (getDefault().fImageDescriptorRegistry == null) {
1206            getDefault().fImageDescriptorRegistry = new ImageDescriptorRegistry();
1207        }
1208        return getDefault().fImageDescriptorRegistry;
1209    }
1210    
1211    /**
1212     * Returns an image descriptor for the icon referenced by the given attribute
1213     * and configuration element, or <code>null</code> if none.
1214     *
1215     * @param element
1216     * @param attr
1217     * @return image descriptor or <code>null</code>
1218     */

1219    public static ImageDescriptor getImageDescriptor(IConfigurationElement element, String JavaDoc attr) {
1220        Bundle bundle = Platform.getBundle(element.getContributor().getName());
1221        String JavaDoc iconPath = element.getAttribute(attr);
1222        if (iconPath != null) {
1223            URL JavaDoc iconURL = FileLocator.find(bundle , new Path(iconPath), null);
1224            if (iconURL != null) {
1225                return ImageDescriptor.createFromURL(iconURL);
1226            }
1227        }
1228        return null;
1229    }
1230    
1231    /**
1232     * Returns an image descriptor for the icon referenced by the given path
1233     * and contributor name, or <code>null</code> if none.
1234     *
1235     * @param name the name of the contributor
1236     * @param path the path of the icon (from the configuration element)
1237     * @return image descriptor or <code>null</code>
1238     * @since 3.3
1239     */

1240    public static ImageDescriptor getImageDescriptor(String JavaDoc name, String JavaDoc path) {
1241        Bundle bundle = Platform.getBundle(name);
1242        if (path != null) {
1243            URL JavaDoc iconURL = FileLocator.find(bundle , new Path(path), null);
1244            if (iconURL != null) {
1245                return ImageDescriptor.createFromURL(iconURL);
1246            }
1247        }
1248        return null;
1249    }
1250    
1251    /**
1252     * Performs extra filtering for launch configurations based on the preferences set on the
1253     * Launch Configurations page
1254     * @param config the config to filter
1255     * @return true if it should pass the filter, false otherwise
1256     * @since 3.2
1257     */

1258    public static boolean doLaunchConfigurationFiltering(ILaunchConfiguration config) {
1259        boolean ret = true;
1260        if(DebugUIPlugin.getDefault().getPreferenceStore().getBoolean(IInternalDebugUIConstants.PREF_FILTER_LAUNCH_CLOSED)) {
1261            ret &= new ClosedProjectFilter().select(null, null, config);
1262        }
1263        if(DebugUIPlugin.getDefault().getPreferenceStore().getBoolean(IInternalDebugUIConstants.PREF_FILTER_LAUNCH_DELETED)) {
1264            ret &= new DeletedProjectFilter().select(null, null, config);
1265        }
1266        if(DebugUIPlugin.getDefault().getPreferenceStore().getBoolean(IInternalDebugUIConstants.PREF_FILTER_LAUNCH_TYPES)) {
1267            try {
1268                ret &= new LaunchConfigurationTypeFilter().select(null, null, config.getType());
1269            }
1270            catch(CoreException e) {
1271                DebugUIPlugin.log(e);
1272            }
1273        }
1274        return ret;
1275    }
1276}
1277
1278
Popular Tags