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