]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.workbench/src/org/simantics/workbench/internal/SimanticsWorkbenchAdvisor.java
Improve startup time for fresh or rollback'd session in index writing
[simantics/platform.git] / bundles / org.simantics.workbench / src / org / simantics / workbench / internal / SimanticsWorkbenchAdvisor.java
1 /*******************************************************************************
2  * Copyright (c) 2007, 2010 Association for Decentralized Information Management
3  * in Industry THTH ry.
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License v1.0
6  * which accompanies this distribution, and is available at
7  * http://www.eclipse.org/legal/epl-v10.html
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 package org.simantics.workbench.internal;
13
14 import java.io.IOException;
15 import java.lang.reflect.InvocationTargetException;
16 import java.net.URL;
17 import java.text.Collator;
18 import java.util.ArrayList;
19 import java.util.Iterator;
20 import java.util.Map;
21 import java.util.TreeMap;
22
23 import org.eclipse.core.internal.resources.Workspace;
24 import org.eclipse.core.net.proxy.IProxyService;
25 import org.eclipse.core.resources.IContainer;
26 import org.eclipse.core.resources.IResource;
27 import org.eclipse.core.resources.ResourcesPlugin;
28 import org.eclipse.core.resources.WorkspaceJob;
29 import org.eclipse.core.runtime.CoreException;
30 import org.eclipse.core.runtime.FileLocator;
31 import org.eclipse.core.runtime.IAdaptable;
32 import org.eclipse.core.runtime.IBundleGroup;
33 import org.eclipse.core.runtime.IBundleGroupProvider;
34 import org.eclipse.core.runtime.ILog;
35 import org.eclipse.core.runtime.IProgressMonitor;
36 import org.eclipse.core.runtime.IStatus;
37 import org.eclipse.core.runtime.MultiStatus;
38 import org.eclipse.core.runtime.Path;
39 import org.eclipse.core.runtime.Platform;
40 import org.eclipse.core.runtime.ProgressMonitorWrapper;
41 import org.eclipse.core.runtime.Status;
42 import org.eclipse.core.runtime.SubMonitor;
43 import org.eclipse.core.runtime.jobs.Job;
44 import org.eclipse.e4.core.contexts.IEclipseContext;
45 import org.eclipse.e4.ui.internal.workbench.E4Workbench;
46 import org.eclipse.jface.dialogs.ErrorDialog;
47 import org.eclipse.jface.dialogs.IDialogSettings;
48 import org.eclipse.jface.dialogs.MessageDialog;
49 import org.eclipse.jface.dialogs.TrayDialog;
50 import org.eclipse.jface.operation.IRunnableWithProgress;
51 import org.eclipse.jface.preference.IPreferenceStore;
52 import org.eclipse.jface.resource.ImageDescriptor;
53 import org.eclipse.jface.util.Policy;
54 import org.eclipse.jface.window.Window;
55 import org.eclipse.swt.SWT;
56 import org.eclipse.swt.events.SelectionAdapter;
57 import org.eclipse.swt.events.SelectionEvent;
58 import org.eclipse.swt.widgets.Composite;
59 import org.eclipse.swt.widgets.Display;
60 import org.eclipse.swt.widgets.Event;
61 import org.eclipse.swt.widgets.Listener;
62 import org.eclipse.swt.widgets.Shell;
63 import org.eclipse.ui.IPerspectiveDescriptor;
64 import org.eclipse.ui.PlatformUI;
65 import org.eclipse.ui.application.IWorkbenchConfigurer;
66 import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
67 import org.eclipse.ui.application.WorkbenchAdvisor;
68 import org.eclipse.ui.application.WorkbenchWindowAdvisor;
69 import org.eclipse.ui.ide.IDE;
70 import org.eclipse.ui.internal.ISelectionConversionService;
71 import org.eclipse.ui.internal.Workbench;
72 import org.eclipse.ui.internal.ide.AboutInfo;
73 import org.eclipse.ui.internal.ide.IDEInternalPreferences;
74 import org.eclipse.ui.internal.ide.IDEInternalWorkbenchImages;
75 import org.eclipse.ui.internal.ide.IDESelectionConversionService;
76 import org.eclipse.ui.internal.ide.IDEWorkbenchActivityHelper;
77 import org.eclipse.ui.internal.ide.IDEWorkbenchErrorHandler;
78 import org.eclipse.ui.internal.ide.IDEWorkbenchMessages;
79 import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin;
80 import org.eclipse.ui.internal.ide.undo.WorkspaceUndoMonitor;
81 import org.eclipse.ui.internal.progress.ProgressMonitorJobsDialog;
82 import org.eclipse.ui.keys.IBindingService;
83 import org.eclipse.ui.progress.IProgressService;
84 import org.eclipse.ui.statushandlers.AbstractStatusHandler;
85 import org.osgi.framework.Bundle;
86 import org.osgi.framework.ServiceReference;
87 import org.osgi.framework.Version;
88 import org.simantics.CancelStartupException;
89 import org.simantics.PlatformException;
90 import org.simantics.Simantics;
91 import org.simantics.SimanticsPlatform;
92 import org.simantics.SimanticsPlatform.OntologyRecoveryPolicy;
93 import org.simantics.SimanticsPlatform.RecoveryPolicy;
94 import org.simantics.TimingProgressMonitor;
95 import org.simantics.application.arguments.IArguments;
96 import org.simantics.application.arguments.SimanticsArguments;
97 import org.simantics.db.common.Indexing;
98 import org.simantics.db.indexing.DatabaseIndexing;
99 import org.simantics.db.procore.server.environment.RebootRequiredException;
100 import org.simantics.db.procore.server.environment.windows.Product;
101 import org.simantics.internal.TimedSessionCache;
102 import org.simantics.project.IProject;
103 import org.simantics.project.ProjectKeys;
104 import org.simantics.ui.SimanticsUI;
105 import org.simantics.ui.jobs.SessionGarbageCollectorJob;
106 import org.simantics.ui.workbench.PerspectiveBarsActivator;
107 import org.simantics.ui.workbench.PerspectiveContextActivator;
108 import org.simantics.utils.logging.TimeLogger;
109 import org.simantics.utils.threads.ThreadUtils;
110 import org.simantics.utils.ui.dialogs.ShowError;
111 import org.simantics.utils.ui.dialogs.ShowMessage;
112 import org.slf4j.Logger;
113 import org.slf4j.LoggerFactory;
114
115
116 /**
117  * @author Tuukka Lehtonen
118  */
119 public class SimanticsWorkbenchAdvisor extends WorkbenchAdvisor {
120     
121     private static final Logger LOGGER = LoggerFactory.getLogger(SimanticsWorkbenchAdvisor.class);
122
123     private static final boolean PROFILE_PLATFORM_STARTUP = false;
124
125     private static final String SHUT_DOWN_TASK = "Shutting down...";
126
127     private static final String SHUT_DOWN_PLATFORM_TASK = "Shutting down platform...";
128
129     private static final String WORKBENCH_PREFERENCE_CATEGORY_ID = "org.eclipse.ui.preferencePages.Workbench"; //$NON-NLS-1$
130
131     /**
132      * The dialog setting key to access the known installed features since the
133      * last time the workbench was run.
134      */
135     private static final String INSTALLED_FEATURES = "installedFeatures"; //$NON-NLS-1$
136
137     /**
138      * The arguments received by the application.
139      */
140     protected final IArguments args;
141
142     protected final boolean restoredPreviousSession = false;
143
144     /**
145      * Only true while opening the initial windows during {@link #openWindows()}.
146      * Used by {@link SimanticsWorkbenchWindowAdvisor#postWindowOpen()} to
147      * recognize when to skip all one-time initialization.
148      */
149     protected boolean workbenchWindowsInitialized = false;
150
151     /**
152      * Whether or not to save unsaved database changes before exiting the
153      * workbench.
154      */
155     protected boolean saveAtExit = false;
156
157     /**
158      * Ordered map of versioned feature ids -> info that are new for this
159      * session; <code>null</code> if uninitialized. Key type:
160      * <code>String</code>, Value type: <code>AboutInfo</code>.
161      */
162     private Map<String, AboutInfo> newlyAddedBundleGroups;
163
164     /**
165      * Array of <code>AboutInfo</code> for all new installed features that
166      * specify a welcome perspective.
167      */
168     private AboutInfo[] welcomePerspectiveInfos = null;
169
170     /**
171      * Helper for managing activites in response to workspace changes.
172      */
173     private IDEWorkbenchActivityHelper activityHelper = null;
174
175     /**
176      * Helper for managing work that is performed when the system is otherwise
177      * idle.
178      */
179     private IDEIdleHelper idleHelper;
180
181     private Listener settingsChangeListener;
182
183     /**
184      * Support class for monitoring workspace changes and periodically
185      * validating the undo history
186      */
187     private WorkspaceUndoMonitor workspaceUndoMonitor;
188
189     /**
190      * The IDE workbench error handler.
191      */
192     private AbstractStatusHandler ideWorkbenchErrorHandler;
193
194     /**
195      * Helper class used to process delayed events.
196      */
197     private DelayedEventsProcessor delayedEventsProcessor;
198     
199     /**
200      * Creates a new workbench advisor instance.
201      * @param processor
202      */
203     public SimanticsWorkbenchAdvisor(IArguments args, DelayedEventsProcessor processor) {
204         super();
205         this.args = args;
206         this.delayedEventsProcessor = processor;
207
208         Listener closeListener = new Listener() {
209             public void handleEvent(Event event) {
210                 boolean doExit = SimanticsWorkbenchWindowAdvisor.promptOnExit(null);
211                 event.doit = doExit;
212                 if (!doExit)
213                     event.type = SWT.None;
214             }
215         };
216         Display.getDefault().addListener(SWT.Close, closeListener);
217     }
218
219     public IArguments getArguments() {
220         return args;
221     }
222
223     public boolean workbenchInitialized() {
224         return workbenchWindowsInitialized;
225     }
226
227     public boolean restoredPreviousSession() {
228         return restoredPreviousSession;
229     }
230
231     boolean saveAtExit() {
232         return saveAtExit;
233     }
234
235     void setSaveAtExit(boolean saveAtExit) {
236         this.saveAtExit = saveAtExit;
237     }
238
239     /*
240      * (non-Javadoc)
241      *
242      * @see org.eclipse.ui.application.WorkbenchAdvisor#initialize
243      */
244     @Override
245     public void initialize(IWorkbenchConfigurer configurer) {
246         // By default, we always save and restore the workbench state.
247         configurer.setSaveAndRestore(true);
248
249         checkWorkspaceDatabaseIndexes();
250
251         // Start tracking the active perspective to activate contexts based on it.
252         new PerspectiveContextActivator();
253         new PerspectiveBarsActivator();
254
255         // register workspace adapters
256         IDE.registerAdapters();
257
258         // register shared images
259         declareWorkbenchImages();
260
261         // initialize the activity helper
262         activityHelper = IDEWorkbenchActivityHelper.getInstance();
263
264         // initialize idle handler
265         idleHelper = new IDEIdleHelper(configurer);
266
267         // initialize the workspace undo monitor
268         workspaceUndoMonitor = WorkspaceUndoMonitor.getInstance();
269
270         // show Help button in JFace dialogs
271         TrayDialog.setDialogHelpAvailable(true);
272
273         Policy.setComparator(Collator.getInstance());
274     }
275
276     private void checkWorkspaceDatabaseIndexes() {
277         try {
278             DatabaseIndexing.validateIndexes();
279         } catch (IOException e) {
280             Activator.logError("Problems encountered while checking database indexes, see exception for details.", e);
281         }
282     }
283
284     public WorkbenchWindowAdvisor createWorkbenchWindowAdvisorClass(SimanticsWorkbenchAdvisor advisor, IWorkbenchWindowConfigurer configurer) {
285         return new SimanticsWorkbenchWindowAdvisor(this, configurer);
286     }
287
288     @Override
289     public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) {
290         // Attach database session watchdog.
291         new SessionWatchdog().attach( Simantics.getSessionContextProvider() );
292
293         return createWorkbenchWindowAdvisorClass(this, configurer);
294     }
295
296     /**
297      * For gaining direct access to super.openWindows() in implementations
298      * inheriting this one.
299      */
300     public boolean openWindowsSuper() {
301         return super.openWindows();
302     }
303
304     /**
305      * Sadly we do not know why key bindings are lost and why this helps. But it
306      * does. Visiting the <code>Keys</code> preference page and pressing OK uses
307      * this the same call and it seems to salvage the bindings that have been in
308      * some cases destroyed by <code>BindingToModelProcessor</code>.
309      * 
310      * <p>
311      * Related links:
312      * https://techblog.ralph-schuster.eu/2013/10/13/eclipsee4-problem-with-key-bindings/comment-page-1/
313      * https://www.eclipse.org/forums/index.php/t/550175/
314      * https://bugs.eclipse.org/bugs/show_bug.cgi?id=461037
315      * 
316      * @see platform issue #6353
317      */
318     private void fixBindings() {
319         try {
320             IBindingService bs = PlatformUI.getWorkbench().getAdapter(IBindingService.class);
321             bs.savePreferences(bs.getActiveScheme(), bs.getBindings());
322         } catch (IOException e) {
323             Activator.logError(getClass().getSimpleName() + ".fixBindings failed", e);
324         }
325     }
326
327     @Override
328     public boolean openWindows() {
329         boolean platformOk = startPlatform();
330         LOGGER.info("startPlatform finished");
331         TimeLogger.log("SimanticsWorkbenchAdvisor.startPlatform finished");
332
333         if (platformOk) {
334             // At this point workbenchConfigurer.getSaveAndRestore()
335             // returns false iff something has gone terribly wrong
336             // before this. Currently saveAndRestore is always true.
337             boolean windowsOpened = super.openWindows();
338             TimeLogger.log("Opened windows");
339             if (windowsOpened) {
340                 workbenchWindowsInitialized = true;
341
342                 // Start the database garbage collector after a short while.
343                 SessionGarbageCollectorJob.getInstance().scheduleAfterQuietTime();
344
345                 // #6353: Workaround for  
346                 fixBindings();
347
348                 return true;
349             }
350         }
351
352         // Make sure platform shutdown is ran if window opening fails.
353         try {
354             platformShutdownRunnable.run(null);
355         } catch (InvocationTargetException e) {
356             Activator.logError(getClass().getSimpleName() + ".openWindows failed", e.getCause());
357         } catch (InterruptedException e) {
358             Activator.logError(getClass().getSimpleName() + ".openWindows failed", e);
359         }
360         return false;
361     }
362
363     protected boolean startPlatform() {
364         // Verify selected perspective
365         if (args.contains(SimanticsArguments.PERSPECTIVE)) {
366             String perspectiveId = args.get(SimanticsArguments.PERSPECTIVE);
367             IPerspectiveDescriptor perspective = PlatformUI.getWorkbench().getPerspectiveRegistry().findPerspectiveWithId(perspectiveId);
368             if (perspective == null) {
369                 StringBuilder msg = new StringBuilder();
370                 msg.append("Requested perspective not found: '" + perspectiveId + "'\n");
371                 msg.append("Valid alternatives are:\n");
372                 for (IPerspectiveDescriptor pd : PlatformUI.getWorkbench().getPerspectiveRegistry().getPerspectives()) {
373                     msg.append("    " + pd.getId() + "\n");
374                 }
375
376                 ShowMessage.syncShowError("Invalid Perspective", msg.toString());
377                 return false;
378             }
379         }
380
381         ILog log = Platform.getLog(Activator.getDefault().getBundle());
382
383         try {
384             //
385             //
386             // Create Simantics Platform Helper.
387             //
388             // If Simantics is started from Eclipse IDE or with -fixerrors option,
389             // there is an attempt to fix errors.
390             //
391             // On ontology mismatch, there is an attempt to merge new ontology to the
392             // existing database. With -reinstall, the database is cleaned and
393             // reinstalled.
394             //
395             //
396
397             RecoveryPolicy workspacePolicy = Platform.inDevelopmentMode() ? RecoveryPolicy.FixError : RecoveryPolicy.ThrowError;
398             OntologyRecoveryPolicy ontologyPolicy = Platform.inDevelopmentMode() ? OntologyRecoveryPolicy.Merge : OntologyRecoveryPolicy.ThrowError;
399
400             if (args.contains(SimanticsArguments.RECOVERY_POLICY_FIX_ERRORS)) {
401                 workspacePolicy = RecoveryPolicy.FixError;
402                 ontologyPolicy = OntologyRecoveryPolicy.Merge;
403             }
404
405             boolean requireSynchronize = true;
406
407             if (args.contains(SimanticsArguments.ONTOLOGY_RECOVERY_POLICY_REINSTALL)) {
408                 ontologyPolicy = OntologyRecoveryPolicy.ReinstallDatabase;
409             }
410
411             if (args.contains(SimanticsArguments.DO_NOT_SYNCHRONIZE_ONTOLOGIES)) {
412                 requireSynchronize = false;
413             }
414             
415             if (args.contains(SimanticsArguments.DISABLE_INDEX)) {
416                 Indexing.setDefaultDependenciesIndexingEnabled(false);
417             }
418
419             if (args.contains(SimanticsArguments.SERVER)) {
420                 String serverAddress = args.get(SimanticsArguments.SERVER);
421                 throw new PlatformException("Argument not supported: " + SimanticsArguments.SERVER + " " + serverAddress);
422             }
423
424             String databaseDriverId = Simantics.getDefaultDatabaseDriver();
425             if (args.contains(SimanticsArguments.DATABASE_ID)) {
426                 databaseDriverId = args.get(SimanticsArguments.DATABASE_ID);
427                 Simantics.setDefaultDatabaseDriver(databaseDriverId);
428             }
429             
430             IProgressMonitor mon = null;
431             if (PROFILE_PLATFORM_STARTUP)
432                 mon = new TimingProgressMonitor();
433             SimanticsPlatform.INSTANCE.startUp(databaseDriverId, mon, workspacePolicy, ontologyPolicy, requireSynchronize, new JFaceUserAgent());
434
435             // Make sure that the default perspective comes from the project if
436             // the project has set ProjectKeys#DEFAULT_PERSPECTIVE.
437             // This might go wrong if project features interact with
438             // PerspectiveRegistry while configuring themselves, since that will
439             // cause an invocation to #getInitialWindowPerspectiveId() while
440             // the project has not yet been properly initialized.
441             getWorkbenchConfigurer().getWorkbench().getPerspectiveRegistry().setDefaultPerspective(getInitialWindowPerspectiveId());
442             TimeLogger.log("Completed setting default perspective");
443
444             return true;
445         } catch (CancelStartupException e) {
446             return false;
447         } catch (PlatformException e) {
448             boolean hasStackTrace = e.getStackTrace().length > 0;
449             Throwable ee = e;
450             while (ee.getCause() != null) {
451                 ee = ee.getCause();
452                 hasStackTrace = ee.getStackTrace().length > 0;
453             }
454
455             log.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), hasStackTrace ? e : null));
456             if (hasStackTrace) {
457                 new ShowError("Platform Initialization Failed", "Simantics Platform initialization failed:\n\n" + e.getMessage(), e, true);
458             } else {
459                 StringBuilder sb = new StringBuilder(256);
460                 sb.append(e.getMessage());
461                 for (Throwable c=e.getCause(); null != c && null != c.getMessage(); c=c.getCause())
462                     sb.append("\ncause: ").append(c.getMessage());
463                 new ShowError("Startup Failed", sb.toString(), (Exception) null, true);
464             }
465
466             return false;
467         } catch (Exception e) {
468             log.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e));
469
470             Throwable cause = e.getCause();
471             if (cause instanceof RebootRequiredException) {
472                 RebootRequiredException rre = (RebootRequiredException) cause;
473                 StringBuilder msg = new StringBuilder();
474                 msg.append("The application must be restarted after installing the following products:\n");
475                 for (Product product : rre.products)
476                     msg.append("\t" + product + "\n");
477                 msg.append("\nThe application will now close.");
478                 MessageDialog.openInformation(null, "Restart Required", msg.toString());
479             } else {
480                 new ShowError("Platform Startup Failed", "Simantics Platform startup failed:\n\n" + e.getMessage(), e, true);
481             }
482             return false;
483         }
484
485     }
486
487     /*
488      * (non-Javadoc)
489      *
490      * @see org.eclipse.ui.application.WorkbenchAdvisor#preStartup()
491      */
492     @Override
493     public void preStartup() {
494
495         // Suspend background jobs while we startup
496         Job.getJobManager().suspend();
497
498         // Register the build actions
499         IProgressService service = PlatformUI.getWorkbench()
500         .getProgressService();
501         ImageDescriptor newImage = IDEInternalWorkbenchImages
502         .getImageDescriptor(IDEInternalWorkbenchImages.IMG_ETOOL_BUILD_EXEC);
503         service.registerIconForFamily(newImage,
504                 ResourcesPlugin.FAMILY_MANUAL_BUILD);
505         service.registerIconForFamily(newImage,
506                 ResourcesPlugin.FAMILY_AUTO_BUILD);
507     }
508
509     /*
510      * (non-Javadoc)
511      *
512      * @see org.eclipse.ui.application.WorkbenchAdvisor#postStartup()
513      */
514     @Override
515     public void postStartup() {
516         try {
517             refreshFromLocal();
518             activateProxyService();
519             ((Workbench) PlatformUI.getWorkbench()).registerService(
520                     ISelectionConversionService.class,
521                     new IDESelectionConversionService());
522
523             initializeSettingsChangeListener();
524             Display.getCurrent().addListener(SWT.Settings,
525                     settingsChangeListener);
526         } finally {// Resume background jobs after we startup
527             Job.getJobManager().resume();
528         }
529     }
530
531     /**
532      * Activate the proxy service by obtaining it.
533      */
534     private void activateProxyService() {
535         Bundle bundle = Platform.getBundle("org.eclipse.ui.ide"); //$NON-NLS-1$
536         Object proxyService = null;
537         if (bundle != null) {
538             ServiceReference<?> ref = bundle.getBundleContext().getServiceReference(IProxyService.class.getName());
539             if (ref != null)
540                 proxyService = bundle.getBundleContext().getService(ref);
541         }
542         if (proxyService == null) {
543             IDEWorkbenchPlugin.log("Proxy service could not be found."); //$NON-NLS-1$
544         }
545     }
546
547     /**
548      * Initialize the listener for settings changes.
549      */
550     private void initializeSettingsChangeListener() {
551         settingsChangeListener = new Listener() {
552
553             boolean currentHighContrast = Display.getCurrent()
554             .getHighContrast();
555
556             @Override
557             public void handleEvent(org.eclipse.swt.widgets.Event event) {
558                 if (Display.getCurrent().getHighContrast() == currentHighContrast)
559                     return;
560
561                 currentHighContrast = !currentHighContrast;
562
563                 // make sure they really want to do this
564                 if (new MessageDialog(null,
565                         IDEWorkbenchMessages.SystemSettingsChange_title, null,
566                         IDEWorkbenchMessages.SystemSettingsChange_message,
567                         MessageDialog.QUESTION, new String[] {
568                         IDEWorkbenchMessages.SystemSettingsChange_yes,
569                         IDEWorkbenchMessages.SystemSettingsChange_no },
570                         1).open() == Window.OK) {
571                     PlatformUI.getWorkbench().restart();
572                 }
573             }
574         };
575
576     }
577
578     /*
579      * (non-Javadoc)
580      *
581      * @see org.eclipse.ui.application.WorkbenchAdvisor#postShutdown
582      */
583     @Override
584     public void postShutdown() {
585         if (activityHelper != null) {
586             activityHelper.shutdown();
587             activityHelper = null;
588         }
589         if (idleHelper != null) {
590             idleHelper.shutdown();
591             idleHelper = null;
592         }
593         if (workspaceUndoMonitor != null) {
594             workspaceUndoMonitor.shutdown();
595             workspaceUndoMonitor = null;
596         }
597         if (IDEWorkbenchPlugin.getPluginWorkspace() != null) {
598             disconnectFromWorkspace();
599         }
600     }
601
602     /*
603      * (non-Javadoc)
604      *
605      * @see org.eclipse.ui.application.WorkbenchAdvisor#preShutdown()
606      */
607     @Override
608     public boolean preShutdown() {
609         Display.getCurrent().removeListener(SWT.Settings,
610                 settingsChangeListener);
611         return super.preShutdown();
612     }
613
614     /**
615      * Return true if the intro plugin is present and false otherwise.
616      *
617      * @return boolean
618      */
619     public boolean hasIntro() {
620         return getWorkbenchConfigurer().getWorkbench().getIntroManager()
621                 .hasIntro();
622     }
623
624     private void refreshFromLocal() {
625         String[] commandLineArgs = Platform.getCommandLineArgs();
626         IPreferenceStore store = IDEWorkbenchPlugin.getDefault()
627                 .getPreferenceStore();
628         boolean refresh = store
629                 .getBoolean(IDEInternalPreferences.REFRESH_WORKSPACE_ON_STARTUP);
630         if (!refresh) {
631             return;
632         }
633
634         // Do not refresh if it was already done by core on startup.
635         for (int i = 0; i < commandLineArgs.length; i++) {
636             if (commandLineArgs[i].equalsIgnoreCase("-refresh")) { //$NON-NLS-1$
637                 return;
638             }
639         }
640
641         final IContainer root = ResourcesPlugin.getWorkspace().getRoot();
642         Job job = new WorkspaceJob(IDEWorkbenchMessages.Workspace_refreshing) {
643             @Override
644             public IStatus runInWorkspace(IProgressMonitor monitor)
645                     throws CoreException {
646                 root.refreshLocal(IResource.DEPTH_INFINITE, monitor);
647                 return Status.OK_STATUS;
648             }
649         };
650         job.setRule(root);
651         job.schedule();
652     }
653
654     private static class CancelableProgressMonitorWrapper extends ProgressMonitorWrapper {
655         private double total = 0;
656         private ProgressMonitorJobsDialog dialog;
657
658         CancelableProgressMonitorWrapper(IProgressMonitor monitor,
659                 ProgressMonitorJobsDialog dialog) {
660             super(monitor);
661             this.dialog = dialog;
662         }
663
664         /*
665          * (non-Javadoc)
666          * @see org.eclipse.core.runtime.ProgressMonitorWrapper#internalWorked(double)
667          */
668         public void internalWorked(double work) {
669             super.internalWorked(work);
670             total += work;
671             updateProgressDetails();
672         }
673
674         /*
675          * (non-Javadoc)
676          * @see org.eclipse.core.runtime.ProgressMonitorWrapper#worked(int)
677          */
678         public void worked(int work) {
679             super.worked(work);
680             total += work;
681             updateProgressDetails();
682         }
683
684         public void beginTask(String name, int totalWork) {
685             super.beginTask(name, totalWork);
686             subTask(IDEWorkbenchMessages.IDEWorkbenchAdvisor_preHistoryCompaction);
687         }
688
689         private void updateProgressDetails() {
690             if (!isCanceled() && Math.abs(total - 4.0) < 0.0001 /* right before history compacting */) {
691                 subTask(IDEWorkbenchMessages.IDEWorkbenchAdvisor_cancelHistoryPruning);
692                 dialog.setCancelable(true);
693             }
694             if (Math.abs(total - 5.0) < 0.0001 /* history compacting finished */) {
695                 subTask(IDEWorkbenchMessages.IDEWorkbenchAdvisor_postHistoryCompaction);
696                 dialog.setCancelable(false);
697             }
698         }
699     }
700
701     private static class CancelableProgressMonitorJobsDialog extends ProgressMonitorJobsDialog {
702
703         public CancelableProgressMonitorJobsDialog(Shell parent) {
704             super(parent);
705         }
706
707         /*
708          * (non-Javadoc)
709          * @see org.eclipse.ui.internal.progress.ProgressMonitorJobsDialog#createDetailsButton(org.eclipse.swt.widgets.Composite)
710          */
711         protected void createButtonsForButtonBar(Composite parent) {
712             super.createButtonsForButtonBar(parent);
713             registerCancelButtonListener();
714         }
715
716         public void registerCancelButtonListener() {
717             cancel.addSelectionListener(new SelectionAdapter() {
718                 public void widgetSelected(SelectionEvent e) {
719                     subTaskLabel.setText(""); //$NON-NLS-1$
720                 }
721             });
722         }
723     }
724
725
726     final IRunnableWithProgress platformShutdownRunnable = new IRunnableWithProgress() {
727         /**
728          * @param monitor
729          *            the progress monitor to use for reporting progress to the
730          *            user, or <code>null</code> indicating that no progress
731          *            should be reported and the operation cannot be cancelled.
732          */
733         @Override
734         public void run(IProgressMonitor monitor) {
735             SubMonitor progress = SubMonitor.convert(monitor, SHUT_DOWN_PLATFORM_TASK, 100);
736             try {
737                 try {
738                     progress.subTask("Platform");
739                     SimanticsPlatform.INSTANCE.shutdown(progress.newChild(50));
740                 } catch (PlatformException e) {
741                     Activator.logError("Problems encountered while shutting down Simantics platform, see exception for details.", e);
742                 }
743
744                 progress.subTask("Remaining database connections");
745                 SimanticsUI.closeSessions();
746                 progress.worked(20);
747                 TimedSessionCache.close();
748                 progress.worked(20);
749
750                 progress.subTask("Thread pools");
751                 ThreadUtils.shutdown();
752                 progress.worked(5);
753
754                 progress.subTask("Clear index status");
755                 try {
756                     // Everything ok, clear index dirty state.
757                     DatabaseIndexing.clearAllDirty();
758                 } catch (IOException e) {
759                     Activator.logError("Problems encountered while refreshing database index states, see exception for details.", e);
760                 }
761                 progress.worked(5);
762
763                 progress.setWorkRemaining(0);
764             } finally {
765                 if (monitor != null) {
766                     monitor.done();
767                 }
768             }
769         }
770     };
771
772     /**
773      * Disconnect from the workspace and close ProCore sessions.
774      */
775     private void disconnectFromWorkspace() {
776         // save the workspace
777         final MultiStatus status = new MultiStatus(
778                 IDEWorkbenchPlugin.IDE_WORKBENCH, 1,
779                 IDEWorkbenchMessages.ProblemSavingWorkbench, null);
780
781         final ProgressMonitorJobsDialog p = new CancelableProgressMonitorJobsDialog(
782                 null);
783
784         final boolean applyPolicy = ResourcesPlugin.getWorkspace()
785                 .getDescription().isApplyFileStatePolicy();
786
787         final IRunnableWithProgress workspaceShutdownRunnable = new IRunnableWithProgress() {
788             @Override
789             public void run(IProgressMonitor monitor) {
790                 try {
791                     status.merge(((Workspace) ResourcesPlugin.getWorkspace()).save(true, true, monitor));
792                 } catch (CoreException e) {
793                     status.merge(e.getStatus());
794                 }
795             }
796         };
797
798         IRunnableWithProgress shutdownRunnable = new IRunnableWithProgress() {
799             @Override
800             public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
801                 if (applyPolicy)
802                     monitor = new CancelableProgressMonitorWrapper(
803                             monitor, p);
804
805                 SubMonitor progress = SubMonitor.convert(monitor, SHUT_DOWN_TASK, 2);
806                 try {
807                     workspaceShutdownRunnable.run(progress.newChild(1, SubMonitor.SUPPRESS_NONE));
808                     platformShutdownRunnable.run(progress.newChild(1, SubMonitor.SUPPRESS_NONE));
809                 } finally {
810                     monitor.done();
811                 }
812             }
813         };
814
815         try {
816             new ProgressMonitorJobsDialog(null).run(true, false, shutdownRunnable);
817         } catch (InvocationTargetException e) {
818             status.merge(new Status(IStatus.ERROR,
819                     IDEWorkbenchPlugin.IDE_WORKBENCH, 1,
820                     IDEWorkbenchMessages.InternalError, e.getTargetException()));
821         } catch (InterruptedException e) {
822             status.merge(new Status(IStatus.ERROR,
823                     IDEWorkbenchPlugin.IDE_WORKBENCH, 1,
824                     IDEWorkbenchMessages.InternalError, e));
825         }
826         ErrorDialog.openError(null,
827                 IDEWorkbenchMessages.ProblemsSavingWorkspace, null, status,
828                 IStatus.ERROR | IStatus.WARNING);
829         if (!status.isOK()) {
830             IDEWorkbenchPlugin.log(
831                     IDEWorkbenchMessages.ProblemsSavingWorkspace, status);
832         }
833     }
834
835     /*
836      * (non-Javadoc)
837      *
838      * @see org.eclipse.ui.application.WorkbenchAdvisor#getDefaultPageInput
839      */
840     @Override
841     public IAdaptable getDefaultPageInput() {
842         return ResourcesPlugin.getWorkspace().getRoot();
843     }
844
845     /*
846      * (non-Javadoc)
847      *
848      * @see org.eclipse.ui.application.WorkbenchAdvisor
849      */
850     @Override
851     public String getInitialWindowPerspectiveId() {
852         int index = PlatformUI.getWorkbench().getWorkbenchWindowCount() - 1;
853
854         String perspectiveId = null;
855         AboutInfo[] welcomeInfos = getWelcomePerspectiveInfos();
856         if (index >= 0 && welcomeInfos != null && index < welcomeInfos.length) {
857             perspectiveId = welcomeInfos[index].getWelcomePerspectiveId();
858         }
859
860         if (perspectiveId == null && args.contains(SimanticsArguments.PERSPECTIVE)) {
861             String id = args.get(SimanticsArguments.PERSPECTIVE);
862             IPerspectiveDescriptor perspective = PlatformUI.getWorkbench().getPerspectiveRegistry().findPerspectiveWithId(id);
863             if (perspective != null)
864                 perspectiveId = id;
865         }
866
867         if (perspectiveId == null) {
868             IProject project = SimanticsUI.peekProject();
869             if (project != null)
870                 perspectiveId = project.getHint(ProjectKeys.DEFAULT_PERSPECTIVE);
871         }
872
873         //System.out.println("Initial perspective: " + perspectiveId);
874
875         return perspectiveId;
876     }
877
878     /**
879      * Returns the map of versioned feature ids -> info object for all installed
880      * features. The format of the versioned feature id (the key of the map) is
881      * featureId + ":" + versionId.
882      *
883      * @return map of versioned feature ids -> info object (key type:
884      *         <code>String</code>, value type: <code>AboutInfo</code>)
885      * @since 3.0
886      */
887     private Map<String, AboutInfo> computeBundleGroupMap() {
888         // use tree map to get predicable order
889         Map<String, AboutInfo> ids = new TreeMap<String, AboutInfo>();
890
891         IBundleGroupProvider[] providers = Platform.getBundleGroupProviders();
892         for (int i = 0; i < providers.length; ++i) {
893             IBundleGroup[] groups = providers[i].getBundleGroups();
894             for (int j = 0; j < groups.length; ++j) {
895                 IBundleGroup group = groups[j];
896                 AboutInfo info = new AboutInfo(group);
897
898                 String version = info.getVersionId();
899                 version = version == null ? "0.0.0" //$NON-NLS-1$
900                         : new Version(version).toString();
901                 String versionedFeature = group.getIdentifier() + ":" + version; //$NON-NLS-1$
902
903                 ids.put(versionedFeature, info);
904             }
905         }
906
907         return ids;
908     }
909
910     /**
911      * Returns the ordered map of versioned feature ids -> AboutInfo that are
912      * new for this session.
913      *
914      * @return ordered map of versioned feature ids (key type:
915      *         <code>String</code>) -> infos (value type:
916      *         <code>AboutInfo</code>).
917      */
918     public Map<String, AboutInfo> getNewlyAddedBundleGroups() {
919         if (newlyAddedBundleGroups == null) {
920             newlyAddedBundleGroups = createNewBundleGroupsMap();
921         }
922         return newlyAddedBundleGroups;
923     }
924
925     /**
926      * Updates the old features setting and returns a map of new features.
927      */
928     private Map<String, AboutInfo> createNewBundleGroupsMap() {
929         // retrieve list of installed bundle groups from last session
930         IDialogSettings settings = IDEWorkbenchPlugin.getDefault()
931                 .getDialogSettings();
932         String[] previousFeaturesArray = settings.getArray(INSTALLED_FEATURES);
933
934         // get a map of currently installed bundle groups and store it for next
935         // session
936         Map<String, AboutInfo> bundleGroups = computeBundleGroupMap();
937         String[] currentFeaturesArray = new String[bundleGroups.size()];
938         bundleGroups.keySet().toArray(currentFeaturesArray);
939         settings.put(INSTALLED_FEATURES, currentFeaturesArray);
940
941         // remove the previously known from the current set
942         if (previousFeaturesArray != null) {
943             for (int i = 0; i < previousFeaturesArray.length; ++i) {
944                 bundleGroups.remove(previousFeaturesArray[i]);
945             }
946         }
947
948         return bundleGroups;
949     }
950
951     /**
952      * Declares all IDE-specific workbench images. This includes both "shared"
953      * images (named in {@link IDE.SharedImages}) and internal images (named in
954      * {@link org.eclipse.ui.internal.ide.IDEInternalWorkbenchImages}).
955      *
956      * @see IWorkbenchConfigurer#declareImage
957      */
958     private void declareWorkbenchImages() {
959
960         final String ICONS_PATH = "$nl$/icons/full/";//$NON-NLS-1$
961         final String PATH_ELOCALTOOL = ICONS_PATH + "elcl16/"; // Enabled //$NON-NLS-1$
962
963         // toolbar
964         // icons.
965         final String PATH_DLOCALTOOL = ICONS_PATH + "dlcl16/"; // Disabled //$NON-NLS-1$
966         // //$NON-NLS-1$
967         // toolbar
968         // icons.
969         final String PATH_ETOOL = ICONS_PATH + "etool16/"; // Enabled toolbar //$NON-NLS-1$
970         // //$NON-NLS-1$
971         // icons.
972         final String PATH_DTOOL = ICONS_PATH + "dtool16/"; // Disabled toolbar //$NON-NLS-1$
973         // //$NON-NLS-1$
974         // icons.
975         final String PATH_OBJECT = ICONS_PATH + "obj16/"; // Model object //$NON-NLS-1$
976         // //$NON-NLS-1$
977         // icons
978         final String PATH_WIZBAN = ICONS_PATH + "wizban/"; // Wizard //$NON-NLS-1$
979         // //$NON-NLS-1$
980         // icons
981
982         Bundle ideBundle = Platform.getBundle(IDEWorkbenchPlugin.IDE_WORKBENCH);
983
984         declareWorkbenchImage(ideBundle,
985                 IDEInternalWorkbenchImages.IMG_ETOOL_BUILD_EXEC, PATH_ETOOL
986                 + "build_exec.gif", false); //$NON-NLS-1$
987         declareWorkbenchImage(ideBundle,
988                 IDEInternalWorkbenchImages.IMG_ETOOL_BUILD_EXEC_HOVER,
989                 PATH_ETOOL + "build_exec.gif", false); //$NON-NLS-1$
990         declareWorkbenchImage(ideBundle,
991                 IDEInternalWorkbenchImages.IMG_ETOOL_BUILD_EXEC_DISABLED,
992                 PATH_DTOOL + "build_exec.gif", false); //$NON-NLS-1$
993
994         declareWorkbenchImage(ideBundle,
995                 IDEInternalWorkbenchImages.IMG_ETOOL_SEARCH_SRC, PATH_ETOOL
996                 + "search_src.gif", false); //$NON-NLS-1$
997         declareWorkbenchImage(ideBundle,
998                 IDEInternalWorkbenchImages.IMG_ETOOL_SEARCH_SRC_HOVER,
999                 PATH_ETOOL + "search_src.gif", false); //$NON-NLS-1$
1000         declareWorkbenchImage(ideBundle,
1001                 IDEInternalWorkbenchImages.IMG_ETOOL_SEARCH_SRC_DISABLED,
1002                 PATH_DTOOL + "search_src.gif", false); //$NON-NLS-1$
1003
1004         declareWorkbenchImage(ideBundle,
1005                 IDEInternalWorkbenchImages.IMG_ETOOL_NEXT_NAV, PATH_ETOOL
1006                 + "next_nav.gif", false); //$NON-NLS-1$
1007
1008         declareWorkbenchImage(ideBundle,
1009                 IDEInternalWorkbenchImages.IMG_ETOOL_PREVIOUS_NAV, PATH_ETOOL
1010                 + "prev_nav.gif", false); //$NON-NLS-1$
1011
1012         declareWorkbenchImage(ideBundle,
1013                 IDEInternalWorkbenchImages.IMG_WIZBAN_NEWPRJ_WIZ, PATH_WIZBAN
1014                 + "newprj_wiz.png", false); //$NON-NLS-1$
1015         declareWorkbenchImage(ideBundle,
1016                 IDEInternalWorkbenchImages.IMG_WIZBAN_NEWFOLDER_WIZ,
1017                 PATH_WIZBAN + "newfolder_wiz.png", false); //$NON-NLS-1$
1018         declareWorkbenchImage(ideBundle,
1019                 IDEInternalWorkbenchImages.IMG_WIZBAN_NEWFILE_WIZ, PATH_WIZBAN
1020                 + "newfile_wiz.png", false); //$NON-NLS-1$
1021
1022         declareWorkbenchImage(ideBundle,
1023                 IDEInternalWorkbenchImages.IMG_WIZBAN_IMPORTDIR_WIZ,
1024                 PATH_WIZBAN + "importdir_wiz.png", false); //$NON-NLS-1$
1025         declareWorkbenchImage(ideBundle,
1026                 IDEInternalWorkbenchImages.IMG_WIZBAN_IMPORTZIP_WIZ,
1027                 PATH_WIZBAN + "importzip_wiz.png", false); //$NON-NLS-1$
1028
1029         declareWorkbenchImage(ideBundle,
1030                 IDEInternalWorkbenchImages.IMG_WIZBAN_EXPORTDIR_WIZ,
1031                 PATH_WIZBAN + "exportdir_wiz.png", false); //$NON-NLS-1$
1032         declareWorkbenchImage(ideBundle,
1033                 IDEInternalWorkbenchImages.IMG_WIZBAN_EXPORTZIP_WIZ,
1034                 PATH_WIZBAN + "exportzip_wiz.png", false); //$NON-NLS-1$
1035
1036         declareWorkbenchImage(ideBundle,
1037                 IDEInternalWorkbenchImages.IMG_WIZBAN_RESOURCEWORKINGSET_WIZ,
1038                 PATH_WIZBAN + "workset_wiz.png", false); //$NON-NLS-1$
1039
1040         declareWorkbenchImage(ideBundle,
1041                 IDEInternalWorkbenchImages.IMG_DLGBAN_SAVEAS_DLG, PATH_WIZBAN
1042                 + "saveas_wiz.png", false); //$NON-NLS-1$
1043
1044         declareWorkbenchImage(ideBundle,
1045                 IDEInternalWorkbenchImages.IMG_DLGBAN_QUICKFIX_DLG, PATH_WIZBAN
1046                 + "quick_fix.png", false); //$NON-NLS-1$
1047
1048         declareWorkbenchImage(ideBundle, IDE.SharedImages.IMG_OBJ_PROJECT,
1049                 PATH_OBJECT + "prj_obj.gif", true); //$NON-NLS-1$
1050         declareWorkbenchImage(ideBundle,
1051                 IDE.SharedImages.IMG_OBJ_PROJECT_CLOSED, PATH_OBJECT
1052                 + "cprj_obj.gif", true); //$NON-NLS-1$
1053         declareWorkbenchImage(ideBundle, IDE.SharedImages.IMG_OPEN_MARKER,
1054                 PATH_ELOCALTOOL + "gotoobj_tsk.gif", true); //$NON-NLS-1$
1055
1056         declareWorkbenchImage(ideBundle,
1057                 IDEInternalWorkbenchImages.IMG_ELCL_QUICK_FIX_ENABLED,
1058                 PATH_ELOCALTOOL + "smartmode_co.gif", true); //$NON-NLS-1$
1059
1060         declareWorkbenchImage(ideBundle,
1061                 IDEInternalWorkbenchImages.IMG_DLCL_QUICK_FIX_DISABLED,
1062                 PATH_DLOCALTOOL + "smartmode_co.gif", true); //$NON-NLS-1$
1063
1064         // task objects
1065         // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_HPRIO_TSK,
1066         // PATH_OBJECT+"hprio_tsk.gif");
1067         // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_MPRIO_TSK,
1068         // PATH_OBJECT+"mprio_tsk.gif");
1069         // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_LPRIO_TSK,
1070         // PATH_OBJECT+"lprio_tsk.gif");
1071
1072         declareWorkbenchImage(ideBundle, IDE.SharedImages.IMG_OBJS_TASK_TSK,
1073                 PATH_OBJECT + "taskmrk_tsk.gif", true); //$NON-NLS-1$
1074         declareWorkbenchImage(ideBundle, IDE.SharedImages.IMG_OBJS_BKMRK_TSK,
1075                 PATH_OBJECT + "bkmrk_tsk.gif", true); //$NON-NLS-1$
1076
1077         declareWorkbenchImage(ideBundle,
1078                 IDEInternalWorkbenchImages.IMG_OBJS_COMPLETE_TSK, PATH_OBJECT
1079                 + "complete_tsk.gif", true); //$NON-NLS-1$
1080         declareWorkbenchImage(ideBundle,
1081                 IDEInternalWorkbenchImages.IMG_OBJS_INCOMPLETE_TSK, PATH_OBJECT
1082                 + "incomplete_tsk.gif", true); //$NON-NLS-1$
1083         declareWorkbenchImage(ideBundle,
1084                 IDEInternalWorkbenchImages.IMG_OBJS_WELCOME_ITEM, PATH_OBJECT
1085                 + "welcome_item.gif", true); //$NON-NLS-1$
1086         declareWorkbenchImage(ideBundle,
1087                 IDEInternalWorkbenchImages.IMG_OBJS_WELCOME_BANNER, PATH_OBJECT
1088                 + "welcome_banner.gif", true); //$NON-NLS-1$
1089         declareWorkbenchImage(ideBundle,
1090                 IDEInternalWorkbenchImages.IMG_OBJS_ERROR_PATH, PATH_OBJECT
1091                 + "error_tsk.gif", true); //$NON-NLS-1$
1092         declareWorkbenchImage(ideBundle,
1093                 IDEInternalWorkbenchImages.IMG_OBJS_WARNING_PATH, PATH_OBJECT
1094                 + "warn_tsk.gif", true); //$NON-NLS-1$
1095         declareWorkbenchImage(ideBundle,
1096                 IDEInternalWorkbenchImages.IMG_OBJS_INFO_PATH, PATH_OBJECT
1097                 + "info_tsk.gif", true); //$NON-NLS-1$
1098
1099         declareWorkbenchImage(ideBundle,
1100                 IDEInternalWorkbenchImages.IMG_LCL_FLAT_LAYOUT, PATH_ELOCALTOOL
1101                 + "flatLayout.gif", true); //$NON-NLS-1$
1102         declareWorkbenchImage(ideBundle,
1103                 IDEInternalWorkbenchImages.IMG_LCL_HIERARCHICAL_LAYOUT,
1104                 PATH_ELOCALTOOL + "hierarchicalLayout.gif", true); //$NON-NLS-1$
1105         declareWorkbenchImage(ideBundle,
1106                 IDEInternalWorkbenchImages.IMG_ETOOL_PROBLEM_CATEGORY,
1107                 PATH_ETOOL + "problem_category.gif", true); //$NON-NLS-1$
1108         /*
1109         declareWorkbenchImage(ideBundle,
1110                 IDEInternalWorkbenchImages.IMG_LCL_LINKTO_HELP, PATH_ELOCALTOOL
1111                         + "linkto_help.gif", false); //$NON-NLS-1$
1112          */
1113
1114         // synchronization indicator objects
1115         // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_WBET_STAT,
1116         // PATH_OVERLAY+"wbet_stat.gif");
1117         // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_SBET_STAT,
1118         // PATH_OVERLAY+"sbet_stat.gif");
1119         // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_CONFLICT_STAT,
1120         // PATH_OVERLAY+"conflict_stat.gif");
1121
1122         // content locality indicator objects
1123         // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_NOTLOCAL_STAT,
1124         // PATH_STAT+"notlocal_stat.gif");
1125         // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_LOCAL_STAT,
1126         // PATH_STAT+"local_stat.gif");
1127         // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_FILLLOCAL_STAT,
1128         // PATH_STAT+"filllocal_stat.gif");
1129     }
1130
1131     /**
1132      * Declares an IDE-specific workbench image.
1133      *
1134      * @param symbolicName
1135      *            the symbolic name of the image
1136      * @param path
1137      *            the path of the image file; this path is relative to the base
1138      *            of the IDE plug-in
1139      * @param shared
1140      *            <code>true</code> if this is a shared image, and
1141      *            <code>false</code> if this is not a shared image
1142      * @see IWorkbenchConfigurer#declareImage
1143      */
1144     private void declareWorkbenchImage(Bundle ideBundle, String symbolicName,
1145             String path, boolean shared) {
1146         URL url = FileLocator.find(ideBundle, new Path(path), null);
1147         ImageDescriptor desc = ImageDescriptor.createFromURL(url);
1148         getWorkbenchConfigurer().declareImage(symbolicName, desc, shared);
1149     }
1150
1151     /*
1152      * (non-Javadoc)
1153      *
1154      * @see org.eclipse.ui.application.WorkbenchAdvisor#getMainPreferencePageId
1155      */
1156     @Override
1157     public String getMainPreferencePageId() {
1158         // indicate that we want the Workench preference page to be prominent
1159         return WORKBENCH_PREFERENCE_CATEGORY_ID;
1160     }
1161
1162     /**
1163      * @return the workspace location string, or <code>null</code> if the
1164      *         location is not being shown
1165      */
1166     public String getWorkspaceLocation() {
1167                 // read command line, which has priority
1168                 IEclipseContext context = getWorkbenchConfigurer().getWorkbench().getService(IEclipseContext.class);
1169                 String location = context != null ? (String) context.get(E4Workbench.FORCED_SHOW_LOCATION) : null;
1170                 if (location != null) {
1171                         return location;
1172                 }
1173                 // read the preference
1174                 if (IDEWorkbenchPlugin.getDefault().getPreferenceStore().getBoolean(IDEInternalPreferences.SHOW_LOCATION)) {
1175                         return Platform.getLocation().toOSString();
1176                 }
1177                 return null;
1178     }
1179
1180     /**
1181      * @return the welcome perspective infos, or <code>null</code> if none or
1182      *         if they should be ignored due to the new intro being present
1183      */
1184     public AboutInfo[] getWelcomePerspectiveInfos() {
1185         if (welcomePerspectiveInfos == null) {
1186             // support old welcome perspectives if intro plugin is not present
1187             if (!hasIntro()) {
1188                 Map<String, AboutInfo> m = getNewlyAddedBundleGroups();
1189                 ArrayList<AboutInfo> list = new ArrayList<AboutInfo>(m.size());
1190                 for (Iterator<AboutInfo> i = m.values().iterator(); i.hasNext();) {
1191                     AboutInfo info = i.next();
1192                     if (info != null && info.getWelcomePerspectiveId() != null
1193                             && info.getWelcomePageURL() != null) {
1194                         list.add(info);
1195                     }
1196                 }
1197                 welcomePerspectiveInfos = new AboutInfo[list.size()];
1198                 list.toArray(welcomePerspectiveInfos);
1199             }
1200         }
1201         return welcomePerspectiveInfos;
1202     }
1203
1204     /*
1205      * (non-Javadoc)
1206      *
1207      * @see org.eclipse.ui.application.WorkbenchAdvisor#getWorkbenchErrorHandler()
1208      */
1209     @Override
1210     public AbstractStatusHandler getWorkbenchErrorHandler() {
1211         if (ideWorkbenchErrorHandler == null) {
1212             ideWorkbenchErrorHandler = new IDEWorkbenchErrorHandler(
1213                     getWorkbenchConfigurer());
1214         }
1215         return ideWorkbenchErrorHandler;
1216     }
1217
1218     /* (non-Javadoc)
1219      * @see org.eclipse.ui.application.WorkbenchAdvisor#eventLoopIdle(org.eclipse.swt.widgets.Display)
1220      */
1221     @Override
1222     public void eventLoopIdle(Display display) {
1223         if (delayedEventsProcessor != null)
1224             delayedEventsProcessor.catchUp(display);
1225         super.eventLoopIdle(display);
1226     }
1227
1228 }