KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > ui > internal > WorkbenchPlugin


1 /*******************************************************************************
2  * Copyright (c) 2000, 2007 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11
12 package org.eclipse.ui.internal;
13
14 import java.io.OutputStream JavaDoc;
15 import java.util.Collection JavaDoc;
16 import java.util.HashSet JavaDoc;
17 import java.util.Locale JavaDoc;
18
19 import org.eclipse.core.runtime.CoreException;
20 import org.eclipse.core.runtime.IConfigurationElement;
21 import org.eclipse.core.runtime.IExtensionPoint;
22 import org.eclipse.core.runtime.IPath;
23 import org.eclipse.core.runtime.IStatus;
24 import org.eclipse.core.runtime.Platform;
25 import org.eclipse.core.runtime.Status;
26 import org.eclipse.jface.preference.IPreferenceStore;
27 import org.eclipse.jface.preference.PreferenceManager;
28 import org.eclipse.jface.resource.ImageDescriptor;
29 import org.eclipse.jface.resource.ImageRegistry;
30 import org.eclipse.jface.window.Window;
31 import org.eclipse.swt.SWT;
32 import org.eclipse.swt.custom.BusyIndicator;
33 import org.eclipse.ui.IEditorRegistry;
34 import org.eclipse.ui.IElementFactory;
35 import org.eclipse.ui.IPerspectiveRegistry;
36 import org.eclipse.ui.ISharedImages;
37 import org.eclipse.ui.IWorkbench;
38 import org.eclipse.ui.IWorkingSetManager;
39 import org.eclipse.ui.PlatformUI;
40 import org.eclipse.ui.internal.StartupThreading.StartupRunnable;
41 import org.eclipse.ui.internal.decorators.DecoratorManager;
42 import org.eclipse.ui.internal.dialogs.WorkbenchPreferenceManager;
43 import org.eclipse.ui.internal.intro.IIntroRegistry;
44 import org.eclipse.ui.internal.intro.IntroRegistry;
45 import org.eclipse.ui.internal.misc.StatusUtil;
46 import org.eclipse.ui.internal.operations.WorkbenchOperationSupport;
47 import org.eclipse.ui.internal.progress.ProgressManager;
48 import org.eclipse.ui.internal.registry.ActionSetRegistry;
49 import org.eclipse.ui.internal.registry.EditorRegistry;
50 import org.eclipse.ui.internal.registry.IWorkbenchRegistryConstants;
51 import org.eclipse.ui.internal.registry.PerspectiveRegistry;
52 import org.eclipse.ui.internal.registry.PreferencePageRegistryReader;
53 import org.eclipse.ui.internal.registry.ViewRegistry;
54 import org.eclipse.ui.internal.registry.WorkingSetRegistry;
55 import org.eclipse.ui.internal.themes.IThemeRegistry;
56 import org.eclipse.ui.internal.themes.ThemeRegistry;
57 import org.eclipse.ui.internal.themes.ThemeRegistryReader;
58 import org.eclipse.ui.internal.util.BundleUtility;
59 import org.eclipse.ui.internal.util.SWTResourceUtil;
60 import org.eclipse.ui.internal.wizards.ExportWizardRegistry;
61 import org.eclipse.ui.internal.wizards.ImportWizardRegistry;
62 import org.eclipse.ui.internal.wizards.NewWizardRegistry;
63 import org.eclipse.ui.operations.IWorkbenchOperationSupport;
64 import org.eclipse.ui.plugin.AbstractUIPlugin;
65 import org.eclipse.ui.presentations.AbstractPresentationFactory;
66 import org.eclipse.ui.views.IViewRegistry;
67 import org.eclipse.ui.wizards.IWizardRegistry;
68 import org.osgi.framework.Bundle;
69 import org.osgi.framework.BundleContext;
70 import org.osgi.framework.BundleEvent;
71 import org.osgi.framework.BundleListener;
72 import org.osgi.framework.InvalidSyntaxException;
73 import org.osgi.framework.ServiceReference;
74 import org.osgi.framework.SynchronousBundleListener;
75
76 import com.ibm.icu.text.MessageFormat;
77
78 /**
79  * This class represents the TOP of the workbench UI world
80  * A plugin class is effectively an application wrapper
81  * for a plugin & its classes. This class should be thought
82  * of as the workbench UI's application class.
83  *
84  * This class is responsible for tracking various registries
85  * font, preference, graphics, dialog store.
86  *
87  * This class is explicitly referenced by the
88  * workbench plugin's "plugin.xml" and places it
89  * into the UI start extension point of the main
90  * overall application harness
91  *
92  * When is this class started?
93  * When the Application
94  * calls createExecutableExtension to create an executable
95  * instance of our workbench class.
96  */

97 public class WorkbenchPlugin extends AbstractUIPlugin {
98     
99     private static final String JavaDoc LEFT_TO_RIGHT = "ltr"; //$NON-NLS-1$
100
private static final String JavaDoc RIGHT_TO_LEFT = "rtl";//$NON-NLS-1$
101
private static final String JavaDoc ORIENTATION_COMMAND_LINE = "-dir";//$NON-NLS-1$
102
private static final String JavaDoc ORIENTATION_PROPERTY = "eclipse.orientation";//$NON-NLS-1$
103
private static final String JavaDoc NL_USER_PROPERTY = "osgi.nl.user"; //$NON-NLS-1$
104
private static final String JavaDoc UI_BUNDLE_ACTIVATOR = "org.eclipse.ui.internal.UIPlugin"; //$NON-NLS-1$
105

106     // Default instance of the receiver
107
private static WorkbenchPlugin inst;
108
109     // Manager that maps resources to descriptors of editors to use
110
private EditorRegistry editorRegistry;
111
112     // Manager for the DecoratorManager
113
private DecoratorManager decoratorManager;
114
115     // Theme registry
116
private ThemeRegistry themeRegistry;
117
118     // Manager for working sets (IWorkingSet)
119
private WorkingSetManager workingSetManager;
120
121     // Working set registry, stores working set dialogs
122
private WorkingSetRegistry workingSetRegistry;
123
124     // The context within which this plugin was started.
125
private BundleContext bundleContext;
126
127     // The set of currently starting bundles
128
private Collection JavaDoc startingBundles = new HashSet JavaDoc();
129
130     /**
131      * Global workbench ui plugin flag. Only workbench implementation is allowed to use this flag
132      * All other plugins, examples, or test cases must *not* use this flag.
133      */

134     public static boolean DEBUG = false;
135
136     /**
137      * The workbench plugin ID.
138      *
139      * @issue we should just drop this constant and use PlatformUI.PLUGIN_ID instead
140      */

141     public static String JavaDoc PI_WORKBENCH = PlatformUI.PLUGIN_ID;
142
143     /**
144      * The character used to separate preference page category ids
145      */

146     public static char PREFERENCE_PAGE_CATEGORY_SEPARATOR = '/';
147
148     // Other data.
149
private WorkbenchPreferenceManager preferenceManager;
150
151     private ViewRegistry viewRegistry;
152
153     private PerspectiveRegistry perspRegistry;
154
155     private ActionSetRegistry actionSetRegistry;
156
157     private SharedImages sharedImages;
158
159     /**
160      * Information describing the product (formerly called "primary plugin"); lazily
161      * initialized.
162      * @since 3.0
163      */

164     private ProductInfo productInfo = null;
165
166     private IntroRegistry introRegistry;
167     
168     private WorkbenchOperationSupport operationSupport;
169     private BundleListener bundleListener;
170         
171     
172     /**
173      * Create an instance of the WorkbenchPlugin. The workbench plugin is
174      * effectively the "application" for the workbench UI. The entire UI
175      * operates as a good plugin citizen.
176      */

177     public WorkbenchPlugin() {
178         super();
179         inst = this;
180     }
181
182     /**
183      * Unload all members. This can be used to run a second instance of a workbench.
184      * @since 3.0
185      */

186     void reset() {
187         editorRegistry = null;
188
189         if (decoratorManager != null) {
190             decoratorManager.dispose();
191             decoratorManager = null;
192         }
193
194         ProgressManager.shutdownProgressManager();
195
196         themeRegistry = null;
197         if (workingSetManager != null) {
198             workingSetManager.dispose();
199             workingSetManager = null;
200         }
201         workingSetRegistry = null;
202
203         preferenceManager = null;
204         if (viewRegistry != null) {
205             viewRegistry.dispose();
206             viewRegistry = null;
207         }
208         if (perspRegistry != null) {
209             perspRegistry.dispose();
210             perspRegistry = null;
211         }
212         actionSetRegistry = null;
213         sharedImages = null;
214
215         productInfo = null;
216         introRegistry = null;
217         
218         if (operationSupport != null) {
219             operationSupport.dispose();
220             operationSupport = null;
221         }
222
223         DEBUG = false;
224          
225     }
226
227     /**
228      * Creates an extension. If the extension plugin has not
229      * been loaded a busy cursor will be activated during the duration of
230      * the load.
231      *
232      * @param element the config element defining the extension
233      * @param classAttribute the name of the attribute carrying the class
234      * @return the extension object
235      * @throws CoreException if the extension cannot be created
236      */

237     public static Object JavaDoc createExtension(final IConfigurationElement element,
238             final String JavaDoc classAttribute) throws CoreException {
239         try {
240             // If plugin has been loaded create extension.
241
// Otherwise, show busy cursor then create extension.
242
if (BundleUtility.isActivated(element.getDeclaringExtension()
243                     .getNamespace())) {
244                 return element.createExecutableExtension(classAttribute);
245             }
246             final Object JavaDoc[] ret = new Object JavaDoc[1];
247             final CoreException[] exc = new CoreException[1];
248             BusyIndicator.showWhile(null, new Runnable JavaDoc() {
249                 public void run() {
250                     try {
251                         ret[0] = element
252                                 .createExecutableExtension(classAttribute);
253                     } catch (CoreException e) {
254                         exc[0] = e;
255                     }
256                 }
257             });
258             if (exc[0] != null) {
259                 throw exc[0];
260             }
261             return ret[0];
262
263         } catch (CoreException core) {
264             throw core;
265         } catch (Exception JavaDoc e) {
266             throw new CoreException(new Status(IStatus.ERROR, PI_WORKBENCH,
267                     IStatus.ERROR, WorkbenchMessages.WorkbenchPlugin_extension,e));
268         }
269     }
270     
271     /**
272      * Answers whether the provided element either has an attribute with the
273      * given name or a child element with the given name with an attribute
274      * called class.
275      *
276      * @param element
277      * the element to test
278      * @param extensionName
279      * the name of the extension to test for
280      * @return whether or not the extension is declared
281      * @since 3.3
282      */

283     public static boolean hasExecutableExtension(IConfigurationElement element,
284             String JavaDoc extensionName) {
285
286         if (element.getAttribute(extensionName) != null)
287             return true;
288         String JavaDoc elementText = element.getValue();
289         if (elementText != null && !elementText.equals("")) //$NON-NLS-1$
290
return true;
291         IConfigurationElement [] children = element.getChildren(extensionName);
292         if (children.length == 1) {
293             if (children[0].getAttribute(IWorkbenchRegistryConstants.ATT_CLASS) != null)
294                 return true;
295         }
296         return false;
297     }
298     
299     /**
300      * Checks to see if the provided element has the syntax for an executable
301      * extension with a given name that resides in a bundle that is already
302      * active. Determining the bundle happens in one of two ways:<br/>
303      * <ul>
304      * <li>The element has an attribute with the specified name or element text
305      * in the form <code>bundle.id/class.name[:optional attributes]</code></li>
306      * <li>The element has a child element with the specified name that has a
307      * <code>plugin</code> attribute</li>
308      * </ul>
309      *
310      * @param element
311      * the element to test
312      * @param extensionName
313      * the name of the extension to test for
314      * @return whether or not the bundle expressed by the above criteria is
315      * active. If the bundle cannot be determined then the state of the
316      * bundle that declared the element is returned.
317      * @since 3.3
318      */

319     public static boolean isBundleLoadedForExecutableExtension(
320             IConfigurationElement element, String JavaDoc extensionName) {
321         Bundle bundle = getBundleForExecutableExtension(element, extensionName);
322
323         if (bundle == null)
324             return true;
325         return bundle.getState() == Bundle.ACTIVE;
326     }
327     
328     /**
329      * Returns the bundle that contains the class referenced by an executable
330      * extension. Determining the bundle happens in one of two ways:<br/>
331      * <ul>
332      * <li>The element has an attribute with the specified name or element text
333      * in the form <code>bundle.id/class.name[:optional attributes]</code></li>
334      * <li>The element has a child element with the specified name that has a
335      * <code>plugin</code> attribute</li>
336      * </ul>
337      *
338      * @param element
339      * the element to test
340      * @param extensionName
341      * the name of the extension to test for
342      * @return the bundle referenced by the extension. If that bundle cannot be
343      * determined the bundle that declared the element is returned. Note
344      * that this may be <code>null</code>.
345      * @since 3.3
346      */

347     public static Bundle getBundleForExecutableExtension(IConfigurationElement element, String JavaDoc extensionName) {
348         // this code is derived heavily from
349
// ConfigurationElement.createExecutableExtension.
350
String JavaDoc prop = null;
351         String JavaDoc executable;
352         String JavaDoc contributorName = null;
353         int i;
354
355         if (extensionName != null)
356             prop = element.getAttribute(extensionName);
357         else {
358             // property not specified, try as element value
359
prop = element.getValue();
360             if (prop != null) {
361                 prop = prop.trim();
362                 if (prop.equals("")) //$NON-NLS-1$
363
prop = null;
364             }
365         }
366
367         if (prop == null) {
368             // property not defined, try as a child element
369
IConfigurationElement[] exec = element.getChildren(extensionName);
370             if (exec.length != 0)
371                 contributorName = exec[0].getAttribute("plugin"); //$NON-NLS-1$
372
} else {
373             // simple property or element value, parse it into its components
374
i = prop.indexOf(':');
375             if (i != -1)
376                 executable = prop.substring(0, i).trim();
377             else
378                 executable = prop;
379
380             i = executable.indexOf('/');
381             if (i != -1)
382                 contributorName = executable.substring(0, i).trim();
383                 
384         }
385         
386         if (contributorName == null)
387             contributorName = element.getContributor().getName();
388         
389         return Platform.getBundle(contributorName);
390     }
391
392     /**
393      * Returns the image registry for this plugin.
394      *
395      * Where are the images? The images (typically gifs) are found in the same
396      * plugins directory.
397      *
398      * @see ImageRegistry
399      *
400      * Note: The workbench uses the standard JFace ImageRegistry to track its
401      * images. In addition the class WorkbenchGraphicResources provides
402      * convenience access to the graphics resources and fast field access for
403      * some of the commonly used graphical images.
404      */

405     protected ImageRegistry createImageRegistry() {
406         return WorkbenchImages.getImageRegistry();
407     }
408
409     /**
410      * Returns the action set registry for the workbench.
411      *
412      * @return the workbench action set registry
413      */

414     public ActionSetRegistry getActionSetRegistry() {
415         if (actionSetRegistry == null) {
416             actionSetRegistry = new ActionSetRegistry();
417         }
418         return actionSetRegistry;
419     }
420
421     /**
422      * Return the default instance of the receiver. This represents the runtime plugin.
423      * @return WorkbenchPlugin
424      * @see AbstractUIPlugin for the typical implementation pattern for plugin classes.
425      */

426     public static WorkbenchPlugin getDefault() {
427         return inst;
428     }
429
430     /**
431      * Answer the manager that maps resource types to a the
432      * description of the editor to use
433      * @return IEditorRegistry the editor registry used
434      * by this plug-in.
435      */

436
437     public IEditorRegistry getEditorRegistry() {
438         if (editorRegistry == null) {
439             editorRegistry = new EditorRegistry();
440         }
441         return editorRegistry;
442     }
443
444     /**
445      * Answer the element factory for an id, or <code>null</code. if not found.
446      * @param targetID
447      * @return IElementFactory
448      */

449     public IElementFactory getElementFactory(String JavaDoc targetID) {
450
451         // Get the extension point registry.
452
IExtensionPoint extensionPoint;
453         extensionPoint = Platform.getExtensionRegistry().getExtensionPoint(
454                 PI_WORKBENCH, IWorkbenchRegistryConstants.PL_ELEMENT_FACTORY);
455
456         if (extensionPoint == null) {
457             WorkbenchPlugin
458                     .log("Unable to find element factory. Extension point: " + IWorkbenchRegistryConstants.PL_ELEMENT_FACTORY + " not found"); //$NON-NLS-2$ //$NON-NLS-1$
459
return null;
460         }
461
462         // Loop through the config elements.
463
IConfigurationElement targetElement = null;
464         IConfigurationElement[] configElements = extensionPoint
465                 .getConfigurationElements();
466         for (int j = 0; j < configElements.length; j++) {
467             String JavaDoc strID = configElements[j].getAttribute("id"); //$NON-NLS-1$
468
if (targetID.equals(strID)) {
469                 targetElement = configElements[j];
470                 break;
471             }
472         }
473         if (targetElement == null) {
474             // log it since we cannot safely display a dialog.
475
WorkbenchPlugin.log("Unable to find element factory: " + targetID); //$NON-NLS-1$
476
return null;
477         }
478
479         // Create the extension.
480
IElementFactory factory = null;
481         try {
482             factory = (IElementFactory) createExtension(targetElement, "class"); //$NON-NLS-1$
483
} catch (CoreException e) {
484             // log it since we cannot safely display a dialog.
485
WorkbenchPlugin.log(
486                     "Unable to create element factory.", e.getStatus()); //$NON-NLS-1$
487
factory = null;
488         }
489         return factory;
490     }
491
492     /**
493      * Returns the presentation factory with the given id, or <code>null</code> if not found.
494      * @param targetID The id of the presentation factory to use.
495      * @return AbstractPresentationFactory or <code>null</code>
496      * if not factory matches that id.
497      */

498     public AbstractPresentationFactory getPresentationFactory(String JavaDoc targetID) {
499         Object JavaDoc o = createExtension(
500                 IWorkbenchRegistryConstants.PL_PRESENTATION_FACTORIES,
501                 "factory", targetID); //$NON-NLS-1$
502
if (o instanceof AbstractPresentationFactory) {
503             return (AbstractPresentationFactory) o;
504         }
505         WorkbenchPlugin
506                 .log("Error creating presentation factory: " + targetID + " -- class is not an AbstractPresentationFactory"); //$NON-NLS-1$ //$NON-NLS-2$
507
return null;
508     }
509
510     /**
511      * Looks up the configuration element with the given id on the given extension point
512      * and instantiates the class specified by the class attributes.
513      *
514      * @param extensionPointId the extension point id (simple id)
515      * @param elementName the name of the configuration element, or <code>null</code>
516      * to match any element
517      * @param targetID the target id
518      * @return the instantiated extension object, or <code>null</code> if not found
519      */

520     private Object JavaDoc createExtension(String JavaDoc extensionPointId, String JavaDoc elementName,
521             String JavaDoc targetID) {
522         IExtensionPoint extensionPoint = Platform.getExtensionRegistry()
523                 .getExtensionPoint(PI_WORKBENCH, extensionPointId);
524         if (extensionPoint == null) {
525             WorkbenchPlugin
526                     .log("Unable to find extension. Extension point: " + extensionPointId + " not found"); //$NON-NLS-1$ //$NON-NLS-2$
527
return null;
528         }
529
530         // Loop through the config elements.
531
IConfigurationElement targetElement = null;
532         IConfigurationElement[] elements = extensionPoint
533                 .getConfigurationElements();
534         for (int j = 0; j < elements.length; j++) {
535             IConfigurationElement element = elements[j];
536             if (elementName == null || elementName.equals(element.getName())) {
537                 String JavaDoc strID = element.getAttribute("id"); //$NON-NLS-1$
538
if (targetID.equals(strID)) {
539                     targetElement = element;
540                     break;
541                 }
542             }
543         }
544         if (targetElement == null) {
545             // log it since we cannot safely display a dialog.
546
WorkbenchPlugin.log("Unable to find extension: " + targetID //$NON-NLS-1$
547
+ " in extension point: " + extensionPointId); //$NON-NLS-1$
548
return null;
549         }
550
551         // Create the extension.
552
try {
553             return createExtension(targetElement, "class"); //$NON-NLS-1$
554
} catch (CoreException e) {
555             // log it since we cannot safely display a dialog.
556
WorkbenchPlugin.log("Unable to create extension: " + targetID //$NON-NLS-1$
557
+ " in extension point: " + extensionPointId //$NON-NLS-1$
558
+ ", status: ", e.getStatus()); //$NON-NLS-1$
559
}
560         return null;
561     }
562
563     /**
564      * Return the perspective registry.
565      * @return IPerspectiveRegistry. The registry for the receiver.
566      */

567     public IPerspectiveRegistry getPerspectiveRegistry() {
568         if (perspRegistry == null) {
569             perspRegistry = new PerspectiveRegistry();
570             // the load methods can touch on WorkbenchImages if an image is
571
// missing so we need to wrap the call in
572
// a startup block for the case where a custom descriptor exists on
573
// startup that does not have an image
574
// associated with it. See bug 196352.
575
StartupThreading.runWithoutExceptions(new StartupRunnable() {
576                 public void runWithException() throws Throwable JavaDoc {
577                     perspRegistry.load();
578                 }
579             });
580             
581         }
582         return perspRegistry;
583     }
584
585     /**
586      * Returns the working set manager
587      *
588      * @return the working set manager
589      * @since 2.0
590      */

591     public IWorkingSetManager getWorkingSetManager() {
592         if (workingSetManager == null) {
593             workingSetManager = new WorkingSetManager(bundleContext);
594             workingSetManager.restoreState();
595         }
596         return workingSetManager;
597     }
598
599     /**
600      * Returns the working set registry
601      *
602      * @return the working set registry
603      * @since 2.0
604      */

605     public WorkingSetRegistry getWorkingSetRegistry() {
606         if (workingSetRegistry == null) {
607             workingSetRegistry = new WorkingSetRegistry();
608             workingSetRegistry.load();
609         }
610         return workingSetRegistry;
611     }
612
613     /**
614      * Returns the introduction registry.
615      *
616      * @return the introduction registry.
617      * @since 3.0
618      */

619     public IIntroRegistry getIntroRegistry() {
620         if (introRegistry == null) {
621             introRegistry = new IntroRegistry();
622         }
623         return introRegistry;
624     }
625     
626     /**
627      * Returns the operation support.
628      *
629      * @return the workbench operation support.
630      * @since 3.1
631      */

632     public IWorkbenchOperationSupport getOperationSupport() {
633         if (operationSupport == null) {
634             operationSupport = new WorkbenchOperationSupport();
635         }
636         return operationSupport;
637     }
638     
639
640     /**
641      * Get the preference manager.
642      * @return PreferenceManager the preference manager for
643      * the receiver.
644      */

645     public PreferenceManager getPreferenceManager() {
646         if (preferenceManager == null) {
647             preferenceManager = new WorkbenchPreferenceManager(
648                     PREFERENCE_PAGE_CATEGORY_SEPARATOR);
649
650             //Get the pages from the registry
651
PreferencePageRegistryReader registryReader = new PreferencePageRegistryReader(
652                     getWorkbench());
653             registryReader
654                     .loadFromRegistry(Platform.getExtensionRegistry());
655             preferenceManager.addPages(registryReader.getTopLevelNodes());
656            
657         }
658         return preferenceManager;
659     }
660
661     /**
662      * Returns the shared images for the workbench.
663      *
664      * @return the shared image manager
665      */

666     public ISharedImages getSharedImages() {
667         if (sharedImages == null) {
668             sharedImages = new SharedImages();
669         }
670         return sharedImages;
671     }
672
673     /**
674      * Returns the theme registry for the workbench.
675      *
676      * @return the theme registry
677      */

678     public IThemeRegistry getThemeRegistry() {
679         if (themeRegistry == null) {
680             themeRegistry = new ThemeRegistry();
681             ThemeRegistryReader reader = new ThemeRegistryReader();
682             reader.readThemes(Platform.getExtensionRegistry(),
683                     themeRegistry);
684         }
685         return themeRegistry;
686     }
687
688     /**
689      * Answer the view registry.
690      * @return IViewRegistry the view registry for the
691      * receiver.
692      */

693     public IViewRegistry getViewRegistry() {
694         if (viewRegistry == null) {
695             viewRegistry = new ViewRegistry();
696         }
697         return viewRegistry;
698     }
699
700     /**
701      * Answer the workbench.
702      * @deprecated Use <code>PlatformUI.getWorkbench()</code> instead.
703      */

704     public IWorkbench getWorkbench() {
705         return PlatformUI.getWorkbench();
706     }
707
708     /**
709      * Set default preference values.
710      * This method must be called whenever the preference store is initially loaded
711      * because the default values are not stored in the preference store.
712      */

713     protected void initializeDefaultPreferences(IPreferenceStore store) {
714         // Do nothing. This should not be called.
715
// Prefs are initialized in WorkbenchPreferenceInitializer.
716
}
717
718     /**
719      * Logs the given message to the platform log.
720      *
721      * If you have an exception in hand, call log(String, Throwable) instead.
722      *
723      * If you have a status object in hand call log(String, IStatus) instead.
724      *
725      * This convenience method is for internal use by the Workbench only and
726      * must not be called outside the Workbench.
727      *
728      * @param message
729      * A high level UI message describing when the problem happened.
730      */

731     public static void log(String JavaDoc message) {
732         getDefault().getLog().log(
733                 StatusUtil.newStatus(IStatus.ERROR, message, null));
734     }
735     
736     /**
737      * Log the throwable.
738      * @param t
739      */

740     public static void log(Throwable JavaDoc t) {
741         getDefault().getLog().log(getStatus(t));
742     }
743
744     /**
745      * Return the status from throwable
746      * @param t throwable
747      * @return IStatus
748      */

749     public static IStatus getStatus(Throwable JavaDoc t) {
750         String JavaDoc message = StatusUtil.getLocalizedMessage(t);
751
752         return newError(message, t);
753     }
754
755     /**
756      * Create a new error from the message and the
757      * throwable.
758      * @param message
759      * @param t
760      * @return IStatus
761      */

762     public static IStatus newError(String JavaDoc message, Throwable JavaDoc t) {
763         String JavaDoc pluginId = "org.eclipse.ui.workbench"; //$NON-NLS-1$
764
int errorCode = IStatus.OK;
765
766         // If this was a CoreException, keep the original plugin ID and error
767
// code
768
if (t instanceof CoreException) {
769             CoreException ce = (CoreException) t;
770             pluginId = ce.getStatus().getPlugin();
771             errorCode = ce.getStatus().getCode();
772         }
773
774         return new Status(IStatus.ERROR, pluginId, errorCode, message,
775                 StatusUtil.getCause(t));
776     }
777     
778     /**
779      * Logs the given message and throwable to the platform log.
780      *
781      * If you have a status object in hand call log(String, IStatus) instead.
782      *
783      * This convenience method is for internal use by the Workbench only and
784      * must not be called outside the Workbench.
785      *
786      * @param message
787      * A high level UI message describing when the problem happened.
788      * @param t
789      * The throwable from where the problem actually occurred.
790      */

791     public static void log(String JavaDoc message, Throwable JavaDoc t) {
792         IStatus status = StatusUtil.newStatus(IStatus.ERROR, message, t);
793         log(message, status);
794     }
795     
796     /**
797      * Logs the given throwable to the platform log, indicating the class and
798      * method from where it is being logged (this is not necessarily where it
799      * occurred).
800      *
801      * This convenience method is for internal use by the Workbench only and
802      * must not be called outside the Workbench.
803      *
804      * @param clazz
805      * The calling class.
806      * @param methodName
807      * The calling method name.
808      * @param t
809      * The throwable from where the problem actually occurred.
810      */

811     public static void log(Class JavaDoc clazz, String JavaDoc methodName, Throwable JavaDoc t) {
812         String JavaDoc msg = MessageFormat.format("Exception in {0}.{1}: {2}", //$NON-NLS-1$
813
new Object JavaDoc[] { clazz.getName(), methodName, t });
814         log(msg, t);
815     }
816     
817     /**
818      * Logs the given message and status to the platform log.
819      *
820      * This convenience method is for internal use by the Workbench only and
821      * must not be called outside the Workbench.
822      *
823      * @param message
824      * A high level UI message describing when the problem happened.
825      * May be <code>null</code>.
826      * @param status
827      * The status describing the problem. Must not be null.
828      */

829     public static void log(String JavaDoc message, IStatus status) {
830
831         //1FTUHE0: ITPCORE:ALL - API - Status & logging - loss of semantic info
832

833         if (message != null) {
834             getDefault().getLog().log(
835                     StatusUtil.newStatus(IStatus.ERROR, message, null));
836         }
837
838         getDefault().getLog().log(status);
839     }
840
841     /**
842      * Log the status to the default log.
843      * @param status
844      */

845     public static void log(IStatus status) {
846         getDefault().getLog().log(status);
847     }
848     
849     /**
850      * Get the decorator manager for the receiver
851      * @return DecoratorManager the decorator manager
852      * for the receiver.
853      */

854     public DecoratorManager getDecoratorManager() {
855         if (this.decoratorManager == null) {
856             this.decoratorManager = new DecoratorManager();
857         }
858         return decoratorManager;
859     }
860
861     /*
862      * (non-Javadoc)
863      * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
864      */

865     public void start(BundleContext context) throws Exception JavaDoc {
866         context.addBundleListener(getBundleListener());
867         super.start(context);
868         bundleContext = context;
869         
870         JFaceUtil.initializeJFace();
871         
872          Window.setDefaultOrientation(getDefaultOrientation());
873
874         // The UI plugin needs to be initialized so that it can install the callback in PrefUtil,
875
// which needs to be done as early as possible, before the workbench
876
// accesses any API preferences.
877
Bundle uiBundle = Platform.getBundle(PlatformUI.PLUGIN_ID);
878         try {
879             // Attempt to load the activator of the ui bundle. This will force lazy start
880
// of the ui bundle. Using the bundle activator class here because it is a
881
// class that needs to be loaded anyway so it should not cause extra classes
882
// to be loaded.
883
if(uiBundle != null)
884                 uiBundle.loadClass(UI_BUNDLE_ACTIVATOR);
885         } catch (ClassNotFoundException JavaDoc e) {
886             WorkbenchPlugin.log("Unable to load UI activator", e); //$NON-NLS-1$
887
}
888         /*
889          * DO NOT RUN ANY OTHER CODE AFTER THIS LINE. If you do, then you are
890          * likely to cause a deadlock in class loader code. Please see Bug 86450
891          * for more information.
892          */

893
894     }
895
896     /**
897      * Get the default orientation from the command line
898      * arguments. If there are no arguments imply the
899      * orientation.
900      * @return int
901      * @see SWT#NONE
902      * @see SWT#RIGHT_TO_LEFT
903      * @see SWT#LEFT_TO_RIGHT
904      */

905     private int getDefaultOrientation() {
906         
907         String JavaDoc[] commandLineArgs = Platform.getCommandLineArgs();
908         
909         int orientation = getCommandLineOrientation(commandLineArgs);
910         
911         if(orientation != SWT.NONE) {
912             return orientation;
913         }
914         
915         orientation = getSystemPropertyOrientation();
916         
917         if(orientation != SWT.NONE) {
918             return orientation;
919         }
920
921         return checkCommandLineLocale(); //Use the default value if there is nothing specified
922
}
923     
924     /**
925      * Check to see if the command line parameter for -nl
926      * has been set. If so imply the orientation from this
927      * specified Locale. If it is a bidirectional Locale
928      * return SWT#RIGHT_TO_LEFT.
929      * If it has not been set or has been set to
930      * a unidirectional Locale then return SWT#NONE.
931      *
932      * Locale is determined differently by different JDKs
933      * and may not be consistent with the users expectations.
934      *
935
936      * @return int
937      * @see SWT#NONE
938      * @see SWT#RIGHT_TO_LEFT
939      */

940     private int checkCommandLineLocale() {
941         
942         //Check if the user property is set. If not do not
943
//rely on the vm.
944
if(System.getProperty(NL_USER_PROPERTY) == null) {
945             return SWT.NONE;
946         }
947         
948         Locale JavaDoc locale = Locale.getDefault();
949         String JavaDoc lang = locale.getLanguage();
950
951         if ("iw".equals(lang) || "he".equals(lang) || "ar".equals(lang) || //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
952
"fa".equals(lang) || "ur".equals(lang)) { //$NON-NLS-1$ //$NON-NLS-2$
953
return SWT.RIGHT_TO_LEFT;
954         }
955             
956         return SWT.NONE;
957     }
958
959     /**
960      * Check to see if the orientation was set in the
961      * system properties. If there is no orientation
962      * specified return SWT#NONE.
963      * @return int
964      * @see SWT#NONE
965      * @see SWT#RIGHT_TO_LEFT
966      * @see SWT#LEFT_TO_RIGHT
967      */

968     private int getSystemPropertyOrientation() {
969         String JavaDoc orientation = System.getProperty(ORIENTATION_PROPERTY);
970         if(RIGHT_TO_LEFT.equals(orientation)) {
971             return SWT.RIGHT_TO_LEFT;
972         }
973         if(LEFT_TO_RIGHT.equals(orientation)) {
974             return SWT.LEFT_TO_RIGHT;
975         }
976         return SWT.NONE;
977     }
978
979     /**
980      * Find the orientation in the commandLineArgs. If there
981      * is no orientation specified return SWT#NONE.
982      * @param commandLineArgs
983      * @return int
984      * @see SWT#NONE
985      * @see SWT#RIGHT_TO_LEFT
986      * @see SWT#LEFT_TO_RIGHT
987      */

988     private int getCommandLineOrientation(String JavaDoc[] commandLineArgs) {
989         //Do not process the last one as it will never have a parameter
990
for (int i = 0; i < commandLineArgs.length - 1; i++) {
991             if(commandLineArgs[i].equalsIgnoreCase(ORIENTATION_COMMAND_LINE)){
992                 String JavaDoc orientation = commandLineArgs[i+1];
993                 if(orientation.equals(RIGHT_TO_LEFT)){
994                     System.setProperty(ORIENTATION_PROPERTY,RIGHT_TO_LEFT);
995                     return SWT.RIGHT_TO_LEFT;
996                 }
997                 if(orientation.equals(LEFT_TO_RIGHT)){
998                     System.setProperty(ORIENTATION_PROPERTY,LEFT_TO_RIGHT);
999                     return SWT.LEFT_TO_RIGHT;
1000                }
1001            }
1002        }
1003        
1004        return SWT.NONE;
1005    }
1006
1007    /**
1008     * Return an array of all bundles contained in this workbench.
1009     *
1010     * @return an array of bundles in the workbench or an empty array if none
1011     * @since 3.0
1012     */

1013    public Bundle[] getBundles() {
1014        return bundleContext == null ? new Bundle[0] : bundleContext
1015                .getBundles();
1016    }
1017    
1018    /**
1019     * Returns the bundle context associated with the workbench plug-in.
1020     *
1021     * @return the bundle context
1022     * @since 3.1
1023     */

1024    public BundleContext getBundleContext() {
1025        return bundleContext;
1026    }
1027
1028    /**
1029     * Returns the application name.
1030     * <p>
1031     * Note this is never shown to the user.
1032     * It is used to initialize the SWT Display.
1033     * On Motif, for example, this can be used
1034     * to set the name used for resource lookup.
1035     * </p>
1036     *
1037     * @return the application name, or <code>null</code>
1038     * @see org.eclipse.swt.widgets.Display#setAppName
1039     * @since 3.0
1040     */

1041    public String JavaDoc getAppName() {
1042        return getProductInfo().getAppName();
1043    }
1044
1045    /**
1046     * Returns the name of the product.
1047     *
1048     * @return the product name, or <code>null</code> if none
1049     * @since 3.0
1050     */

1051    public String JavaDoc getProductName() {
1052        return getProductInfo().getProductName();
1053    }
1054
1055    /**
1056     * Returns the image descriptors for the window image to use for this product.
1057     *
1058     * @return an array of the image descriptors for the window image, or
1059     * <code>null</code> if none
1060     * @since 3.0
1061     */

1062    public ImageDescriptor[] getWindowImages() {
1063        return getProductInfo().getWindowImages();
1064    }
1065
1066    /**
1067     * Returns an instance that describes this plugin's product (formerly "primary
1068     * plugin").
1069     * @return ProductInfo the product info for the receiver
1070     */

1071    private ProductInfo getProductInfo() {
1072        if (productInfo == null) {
1073            productInfo = new ProductInfo(Platform.getProduct());
1074        }
1075        return productInfo;
1076    }
1077
1078    /* (non-Javadoc)
1079     * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
1080     */

1081    public void stop(BundleContext context) throws Exception JavaDoc {
1082        if (bundleListener!=null) {
1083            context.removeBundleListener(bundleListener);
1084            bundleListener = null;
1085        }
1086        // TODO normally super.stop(*) would be the last statement in this
1087
// method
1088
super.stop(context);
1089        if (workingSetManager != null) {
1090            workingSetManager.dispose();
1091            workingSetManager= null;
1092        }
1093        SWTResourceUtil.shutdown();
1094    }
1095    
1096    /**
1097     * Return the new wizard registry.
1098     *
1099     * @return the new wizard registry
1100     * @since 3.1
1101     */

1102    public IWizardRegistry getNewWizardRegistry() {
1103        return NewWizardRegistry.getInstance();
1104    }
1105    
1106    /**
1107     * Return the import wizard registry.
1108     *
1109     * @return the import wizard registry
1110     * @since 3.1
1111     */

1112    public IWizardRegistry getImportWizardRegistry() {
1113        return ImportWizardRegistry.getInstance();
1114    }
1115    
1116    /**
1117     * Return the export wizard registry.
1118     *
1119     * @return the export wizard registry
1120     * @since 3.1
1121     */

1122    public IWizardRegistry getExportWizardRegistry() {
1123        return ExportWizardRegistry.getInstance();
1124    }
1125    
1126    /**
1127     * FOR INTERNAL WORKBENCH USE ONLY.
1128     *
1129     * Returns the path to a location in the file system that can be used
1130     * to persist/restore state between workbench invocations.
1131     * If the location did not exist prior to this call it will be created.
1132     * Returns <code>null</code> if no such location is available.
1133     *
1134     * @return path to a location in the file system where this plug-in can
1135     * persist data between sessions, or <code>null</code> if no such
1136     * location is available.
1137     * @since 3.1
1138     */

1139    public IPath getDataLocation() {
1140        try {
1141            return getStateLocation();
1142        } catch (IllegalStateException JavaDoc e) {
1143            // This occurs if -data=@none is explicitly specified, so ignore this silently.
1144
// Is this OK? See bug 85071.
1145
return null;
1146        }
1147    }
1148
1149    /* package */ void addBundleListener(BundleListener bundleListener) {
1150        bundleContext.addBundleListener(bundleListener);
1151    }
1152
1153    /* package */ void removeBundleListener(BundleListener bundleListener) {
1154        bundleContext.removeBundleListener(bundleListener);
1155    }
1156    
1157    /* package */ int getBundleCount() {
1158        return bundleContext.getBundles().length;
1159    }
1160    
1161    /* package */ OutputStream JavaDoc getSplashStream() {
1162        // assumes the output stream is available as a service
1163
// see EclipseStarter.publishSplashScreen
1164
ServiceReference[] ref;
1165        try {
1166            ref = bundleContext.getServiceReferences(OutputStream JavaDoc.class.getName(), null);
1167        } catch (InvalidSyntaxException e) {
1168            return null;
1169        }
1170        if(ref==null) {
1171            return null;
1172        }
1173        for (int i = 0; i < ref.length; i++) {
1174            String JavaDoc name = (String JavaDoc) ref[i].getProperty("name"); //$NON-NLS-1$
1175
if (name != null && name.equals("splashstream")) { //$NON-NLS-1$
1176
Object JavaDoc result = bundleContext.getService(ref[i]);
1177                bundleContext.ungetService(ref[i]);
1178                return (OutputStream JavaDoc) result;
1179            }
1180        }
1181        return null;
1182    }
1183
1184    /**
1185     * @return
1186     */

1187    private BundleListener getBundleListener() {
1188        if (bundleListener == null) {
1189            bundleListener = new SynchronousBundleListener() {
1190                public void bundleChanged(BundleEvent event) {
1191                    WorkbenchPlugin.this.bundleChanged(event);
1192                }
1193            };
1194        }
1195        return bundleListener;
1196    }
1197
1198    private void bundleChanged(BundleEvent event) {
1199        // a bundle in the STARTING state generates 2 events, LAZY_ACTIVATION
1200
// when it enters STARTING and STARTING when it exists STARTING :-)
1201
synchronized (startingBundles) {
1202            switch (event.getType()) {
1203                case BundleEvent.STARTING :
1204                    startingBundles.add(event.getBundle());
1205                    break;
1206                case BundleEvent.STARTED :
1207                case BundleEvent.STOPPED :
1208                    startingBundles.remove(event.getBundle());
1209                    break;
1210                default :
1211                    break;
1212            }
1213        }
1214    }
1215
1216    public boolean isStarting(Bundle bundle) {
1217        synchronized (startingBundles) {
1218            return startingBundles.contains(bundle);
1219        }
1220    }
1221    
1222}
1223
Popular Tags