]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.workbench/src/org/simantics/workbench/internal/SimanticsWorkbenchAdvisor.java
Merge "Easier baselines"
[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.eclipse.ui.statushandlers.StatusAdapter;
86 import org.osgi.framework.Bundle;
87 import org.osgi.framework.BundleContext;
88 import org.osgi.framework.ServiceReference;
89 import org.osgi.framework.Version;
90 import org.simantics.CancelStartupException;
91 import org.simantics.DatabaseBaselines;
92 import org.simantics.PlatformException;
93 import org.simantics.Simantics;
94 import org.simantics.SimanticsPlatform;
95 import org.simantics.SimanticsPlatform.OntologyRecoveryPolicy;
96 import org.simantics.SimanticsPlatform.RecoveryPolicy;
97 import org.simantics.TimingProgressMonitor;
98 import org.simantics.UnhandledExceptionService;
99 import org.simantics.application.arguments.IArguments;
100 import org.simantics.application.arguments.SimanticsArguments;
101 import org.simantics.db.common.Indexing;
102 import org.simantics.db.indexing.DatabaseIndexing;
103 import org.simantics.project.IProject;
104 import org.simantics.project.ProjectKeys;
105 import org.simantics.ui.SimanticsUI;
106 import org.simantics.ui.jobs.SessionGarbageCollectorJob;
107 import org.simantics.ui.workbench.PerspectiveBarsActivator;
108 import org.simantics.ui.workbench.PerspectiveContextActivator;
109 import org.simantics.utils.logging.TimeLogger;
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                 ontologyPolicy = OntologyRecoveryPolicy.Bypass;
414             }
415             
416             if (args.contains(SimanticsArguments.DISABLE_INDEX)) {
417                 Indexing.setDefaultDependenciesIndexingEnabled(false);
418             }
419
420             if (args.contains(SimanticsArguments.SERVER)) {
421                 String serverAddress = args.get(SimanticsArguments.SERVER);
422                 throw new PlatformException("Argument not supported: " + SimanticsArguments.SERVER + " " + serverAddress);
423             }
424
425             String databaseDriverId = Simantics.getDefaultDatabaseDriver();
426             if (args.contains(SimanticsArguments.DATABASE_ID)) {
427                 databaseDriverId = args.get(SimanticsArguments.DATABASE_ID);
428                 Simantics.setDefaultDatabaseDriver(databaseDriverId);
429             }
430             
431             IProgressMonitor mon = null;
432             if (PROFILE_PLATFORM_STARTUP)
433                 mon = new TimingProgressMonitor();
434             SimanticsPlatform.INSTANCE.startUp(databaseDriverId, mon, workspacePolicy, ontologyPolicy, requireSynchronize, new JFaceUserAgent());
435             if(DatabaseBaselines.shouldCreateAutomaticBaseline(SimanticsPlatform.INSTANCE.databaseExists() != null)) {
436                 SimanticsPlatform.INSTANCE.shutdown(null);
437                 DatabaseBaselines.createAutomaticBaseline(SimanticsPlatform.INSTANCE.dbLocation());
438                 SimanticsPlatform.INSTANCE.reconnect(Simantics.getDefaultDatabaseDriver());
439             }
440
441             // Make sure that the default perspective comes from the project if
442             // the project has set ProjectKeys#DEFAULT_PERSPECTIVE.
443             // This might go wrong if project features interact with
444             // PerspectiveRegistry while configuring themselves, since that will
445             // cause an invocation to #getInitialWindowPerspectiveId() while
446             // the project has not yet been properly initialized.
447             getWorkbenchConfigurer().getWorkbench().getPerspectiveRegistry().setDefaultPerspective(getInitialWindowPerspectiveId());
448             TimeLogger.log("Completed setting default perspective");
449
450             return true;
451         } catch (CancelStartupException e) {
452             return false;
453         } catch (PlatformException e) {
454             boolean hasStackTrace = e.getStackTrace().length > 0;
455             Throwable ee = e;
456             while (ee.getCause() != null) {
457                 ee = ee.getCause();
458                 hasStackTrace = ee.getStackTrace().length > 0;
459             }
460
461             log.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), hasStackTrace ? e : null));
462             if (hasStackTrace) {
463                 new ShowError("Platform Initialization Failed", "Simantics Platform initialization failed:\n\n" + e.getMessage(), e, true);
464             } else {
465                 StringBuilder sb = new StringBuilder(256);
466                 sb.append(e.getMessage());
467                 for (Throwable c=e.getCause(); null != c && null != c.getMessage(); c=c.getCause())
468                     sb.append("\ncause: ").append(c.getMessage());
469                 new ShowError("Startup Failed", sb.toString(), (Exception) null, true);
470             }
471
472             return false;
473         } catch (Exception e) {
474             log.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e));
475             new ShowError("Platform Startup Failed", "Simantics Platform startup failed:\n\n" + e.getMessage(), e, true);
476             return false;
477         }
478
479     }
480
481     /*
482      * (non-Javadoc)
483      *
484      * @see org.eclipse.ui.application.WorkbenchAdvisor#preStartup()
485      */
486     @Override
487     public void preStartup() {
488
489         // Suspend background jobs while we startup
490         Job.getJobManager().suspend();
491
492         // Register the build actions
493         IProgressService service = PlatformUI.getWorkbench()
494         .getProgressService();
495         ImageDescriptor newImage = IDEInternalWorkbenchImages
496         .getImageDescriptor(IDEInternalWorkbenchImages.IMG_ETOOL_BUILD_EXEC);
497         service.registerIconForFamily(newImage,
498                 ResourcesPlugin.FAMILY_MANUAL_BUILD);
499         service.registerIconForFamily(newImage,
500                 ResourcesPlugin.FAMILY_AUTO_BUILD);
501     }
502
503     /*
504      * (non-Javadoc)
505      *
506      * @see org.eclipse.ui.application.WorkbenchAdvisor#postStartup()
507      */
508     @Override
509     public void postStartup() {
510         try {
511             refreshFromLocal();
512             activateProxyService();
513             ((Workbench) PlatformUI.getWorkbench()).registerService(
514                     ISelectionConversionService.class,
515                     new IDESelectionConversionService());
516
517             initializeSettingsChangeListener();
518             Display.getCurrent().addListener(SWT.Settings,
519                     settingsChangeListener);
520         } finally {// Resume background jobs after we startup
521             Job.getJobManager().resume();
522         }
523     }
524
525     /**
526      * Activate the proxy service by obtaining it.
527      */
528     private void activateProxyService() {
529         Bundle bundle = Platform.getBundle("org.eclipse.ui.ide"); //$NON-NLS-1$
530         Object proxyService = null;
531         if (bundle != null) {
532             ServiceReference<?> ref = bundle.getBundleContext().getServiceReference(IProxyService.class.getName());
533             if (ref != null)
534                 proxyService = bundle.getBundleContext().getService(ref);
535         }
536         if (proxyService == null) {
537             IDEWorkbenchPlugin.log("Proxy service could not be found."); //$NON-NLS-1$
538         }
539     }
540
541     /**
542      * Initialize the listener for settings changes.
543      */
544     private void initializeSettingsChangeListener() {
545         settingsChangeListener = new Listener() {
546
547             boolean currentHighContrast = Display.getCurrent()
548             .getHighContrast();
549
550             @Override
551             public void handleEvent(org.eclipse.swt.widgets.Event event) {
552                 if (Display.getCurrent().getHighContrast() == currentHighContrast)
553                     return;
554
555                 currentHighContrast = !currentHighContrast;
556
557                 // make sure they really want to do this
558                 if (new MessageDialog(null,
559                         IDEWorkbenchMessages.SystemSettingsChange_title, null,
560                         IDEWorkbenchMessages.SystemSettingsChange_message,
561                         MessageDialog.QUESTION, new String[] {
562                         IDEWorkbenchMessages.SystemSettingsChange_yes,
563                         IDEWorkbenchMessages.SystemSettingsChange_no },
564                         1).open() == Window.OK) {
565                     PlatformUI.getWorkbench().restart();
566                 }
567             }
568         };
569
570     }
571
572     /*
573      * (non-Javadoc)
574      *
575      * @see org.eclipse.ui.application.WorkbenchAdvisor#postShutdown
576      */
577     @Override
578     public void postShutdown() {
579         if (activityHelper != null) {
580             activityHelper.shutdown();
581             activityHelper = null;
582         }
583         if (idleHelper != null) {
584             idleHelper.shutdown();
585             idleHelper = null;
586         }
587         if (workspaceUndoMonitor != null) {
588             workspaceUndoMonitor.shutdown();
589             workspaceUndoMonitor = null;
590         }
591         if (IDEWorkbenchPlugin.getPluginWorkspace() != null) {
592             disconnectFromWorkspace();
593         }
594     }
595
596     /*
597      * (non-Javadoc)
598      *
599      * @see org.eclipse.ui.application.WorkbenchAdvisor#preShutdown()
600      */
601     @Override
602     public boolean preShutdown() {
603         Display.getCurrent().removeListener(SWT.Settings,
604                 settingsChangeListener);
605         return super.preShutdown();
606     }
607
608     /**
609      * Return true if the intro plugin is present and false otherwise.
610      *
611      * @return boolean
612      */
613     public boolean hasIntro() {
614         return getWorkbenchConfigurer().getWorkbench().getIntroManager()
615                 .hasIntro();
616     }
617
618     private void refreshFromLocal() {
619         String[] commandLineArgs = Platform.getCommandLineArgs();
620         IPreferenceStore store = IDEWorkbenchPlugin.getDefault()
621                 .getPreferenceStore();
622         boolean refresh = store
623                 .getBoolean(IDEInternalPreferences.REFRESH_WORKSPACE_ON_STARTUP);
624         if (!refresh) {
625             return;
626         }
627
628         // Do not refresh if it was already done by core on startup.
629         for (int i = 0; i < commandLineArgs.length; i++) {
630             if (commandLineArgs[i].equalsIgnoreCase("-refresh")) { //$NON-NLS-1$
631                 return;
632             }
633         }
634
635         final IContainer root = ResourcesPlugin.getWorkspace().getRoot();
636         Job job = new WorkspaceJob(IDEWorkbenchMessages.Workspace_refreshing) {
637             @Override
638             public IStatus runInWorkspace(IProgressMonitor monitor)
639                     throws CoreException {
640                 root.refreshLocal(IResource.DEPTH_INFINITE, monitor);
641                 return Status.OK_STATUS;
642             }
643         };
644         job.setRule(root);
645         job.schedule();
646     }
647
648     private static class CancelableProgressMonitorWrapper extends ProgressMonitorWrapper {
649         private double total = 0;
650         private ProgressMonitorJobsDialog dialog;
651
652         CancelableProgressMonitorWrapper(IProgressMonitor monitor,
653                 ProgressMonitorJobsDialog dialog) {
654             super(monitor);
655             this.dialog = dialog;
656         }
657
658         /*
659          * (non-Javadoc)
660          * @see org.eclipse.core.runtime.ProgressMonitorWrapper#internalWorked(double)
661          */
662         public void internalWorked(double work) {
663             super.internalWorked(work);
664             total += work;
665             updateProgressDetails();
666         }
667
668         /*
669          * (non-Javadoc)
670          * @see org.eclipse.core.runtime.ProgressMonitorWrapper#worked(int)
671          */
672         public void worked(int work) {
673             super.worked(work);
674             total += work;
675             updateProgressDetails();
676         }
677
678         public void beginTask(String name, int totalWork) {
679             super.beginTask(name, totalWork);
680             subTask(IDEWorkbenchMessages.IDEWorkbenchAdvisor_preHistoryCompaction);
681         }
682
683         private void updateProgressDetails() {
684             if (!isCanceled() && Math.abs(total - 4.0) < 0.0001 /* right before history compacting */) {
685                 subTask(IDEWorkbenchMessages.IDEWorkbenchAdvisor_cancelHistoryPruning);
686                 dialog.setCancelable(true);
687             }
688             if (Math.abs(total - 5.0) < 0.0001 /* history compacting finished */) {
689                 subTask(IDEWorkbenchMessages.IDEWorkbenchAdvisor_postHistoryCompaction);
690                 dialog.setCancelable(false);
691             }
692         }
693     }
694
695     private static class CancelableProgressMonitorJobsDialog extends ProgressMonitorJobsDialog {
696
697         public CancelableProgressMonitorJobsDialog(Shell parent) {
698             super(parent);
699         }
700
701         /*
702          * (non-Javadoc)
703          * @see org.eclipse.ui.internal.progress.ProgressMonitorJobsDialog#createDetailsButton(org.eclipse.swt.widgets.Composite)
704          */
705         protected void createButtonsForButtonBar(Composite parent) {
706             super.createButtonsForButtonBar(parent);
707             registerCancelButtonListener();
708         }
709
710         public void registerCancelButtonListener() {
711             cancel.addSelectionListener(new SelectionAdapter() {
712                 public void widgetSelected(SelectionEvent e) {
713                     subTaskLabel.setText(""); //$NON-NLS-1$
714                 }
715             });
716         }
717     }
718
719
720     final IRunnableWithProgress platformShutdownRunnable = new IRunnableWithProgress() {
721         /**
722          * @param monitor
723          *            the progress monitor to use for reporting progress to the
724          *            user, or <code>null</code> indicating that no progress
725          *            should be reported and the operation cannot be cancelled.
726          */
727         @Override
728         public void run(IProgressMonitor monitor) {
729             SubMonitor progress = SubMonitor.convert(monitor, SHUT_DOWN_PLATFORM_TASK, 100);
730             try {
731                 try {
732                     progress.subTask("Platform");
733                     SimanticsPlatform.INSTANCE.shutdown(progress.newChild(100));
734                 } catch (PlatformException e) {
735                     Activator.logError("Problems encountered while shutting down Simantics platform, see exception for details.", e);
736                 }
737
738                 progress.subTask("Remaining database connections");
739                 SimanticsUI.closeSessions();
740
741                 progress.setWorkRemaining(0);
742             } finally {
743                 if (monitor != null) {
744                     monitor.done();
745                 }
746             }
747         }
748     };
749
750     /**
751      * Disconnect from the workspace and close ProCore sessions.
752      */
753     private void disconnectFromWorkspace() {
754         // save the workspace
755         final MultiStatus status = new MultiStatus(
756                 IDEWorkbenchPlugin.IDE_WORKBENCH, 1,
757                 IDEWorkbenchMessages.ProblemSavingWorkbench, null);
758
759         final ProgressMonitorJobsDialog p = new CancelableProgressMonitorJobsDialog(
760                 null);
761
762         final boolean applyPolicy = ResourcesPlugin.getWorkspace()
763                 .getDescription().isApplyFileStatePolicy();
764
765         final IRunnableWithProgress workspaceShutdownRunnable = new IRunnableWithProgress() {
766             @Override
767             public void run(IProgressMonitor monitor) {
768                 try {
769                     status.merge(((Workspace) ResourcesPlugin.getWorkspace()).save(true, true, monitor));
770                 } catch (CoreException e) {
771                     status.merge(e.getStatus());
772                 }
773             }
774         };
775
776         IRunnableWithProgress shutdownRunnable = new IRunnableWithProgress() {
777             @Override
778             public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
779                 if (applyPolicy)
780                     monitor = new CancelableProgressMonitorWrapper(
781                             monitor, p);
782
783                 SubMonitor progress = SubMonitor.convert(monitor, SHUT_DOWN_TASK, 2);
784                 try {
785                     workspaceShutdownRunnable.run(progress.newChild(1, SubMonitor.SUPPRESS_NONE));
786                     platformShutdownRunnable.run(progress.newChild(1, SubMonitor.SUPPRESS_NONE));
787                 } finally {
788                     monitor.done();
789                 }
790             }
791         };
792
793         try {
794             new ProgressMonitorJobsDialog(null).run(true, false, shutdownRunnable);
795         } catch (InvocationTargetException e) {
796             status.merge(new Status(IStatus.ERROR,
797                     IDEWorkbenchPlugin.IDE_WORKBENCH, 1,
798                     IDEWorkbenchMessages.InternalError, e.getTargetException()));
799         } catch (InterruptedException e) {
800             status.merge(new Status(IStatus.ERROR,
801                     IDEWorkbenchPlugin.IDE_WORKBENCH, 1,
802                     IDEWorkbenchMessages.InternalError, e));
803         }
804         ErrorDialog.openError(null,
805                 IDEWorkbenchMessages.ProblemsSavingWorkspace, null, status,
806                 IStatus.ERROR | IStatus.WARNING);
807         if (!status.isOK()) {
808             IDEWorkbenchPlugin.log(
809                     IDEWorkbenchMessages.ProblemsSavingWorkspace, status);
810         }
811     }
812
813     /*
814      * (non-Javadoc)
815      *
816      * @see org.eclipse.ui.application.WorkbenchAdvisor#getDefaultPageInput
817      */
818     @Override
819     public IAdaptable getDefaultPageInput() {
820         return ResourcesPlugin.getWorkspace().getRoot();
821     }
822
823     /*
824      * (non-Javadoc)
825      *
826      * @see org.eclipse.ui.application.WorkbenchAdvisor
827      */
828     @Override
829     public String getInitialWindowPerspectiveId() {
830         int index = PlatformUI.getWorkbench().getWorkbenchWindowCount() - 1;
831
832         String perspectiveId = null;
833         AboutInfo[] welcomeInfos = getWelcomePerspectiveInfos();
834         if (index >= 0 && welcomeInfos != null && index < welcomeInfos.length) {
835             perspectiveId = welcomeInfos[index].getWelcomePerspectiveId();
836         }
837
838         if (perspectiveId == null && args.contains(SimanticsArguments.PERSPECTIVE)) {
839             String id = args.get(SimanticsArguments.PERSPECTIVE);
840             IPerspectiveDescriptor perspective = PlatformUI.getWorkbench().getPerspectiveRegistry().findPerspectiveWithId(id);
841             if (perspective != null)
842                 perspectiveId = id;
843         }
844
845         if (perspectiveId == null) {
846             IProject project = Simantics.peekProject();
847             if (project != null)
848                 perspectiveId = project.getHint(ProjectKeys.DEFAULT_PERSPECTIVE);
849         }
850
851         //System.out.println("Initial perspective: " + perspectiveId);
852
853         return perspectiveId;
854     }
855
856     /**
857      * Returns the map of versioned feature ids -> info object for all installed
858      * features. The format of the versioned feature id (the key of the map) is
859      * featureId + ":" + versionId.
860      *
861      * @return map of versioned feature ids -> info object (key type:
862      *         <code>String</code>, value type: <code>AboutInfo</code>)
863      * @since 3.0
864      */
865     private Map<String, AboutInfo> computeBundleGroupMap() {
866         // use tree map to get predicable order
867         Map<String, AboutInfo> ids = new TreeMap<String, AboutInfo>();
868
869         IBundleGroupProvider[] providers = Platform.getBundleGroupProviders();
870         for (int i = 0; i < providers.length; ++i) {
871             IBundleGroup[] groups = providers[i].getBundleGroups();
872             for (int j = 0; j < groups.length; ++j) {
873                 IBundleGroup group = groups[j];
874                 AboutInfo info = new AboutInfo(group);
875
876                 String version = info.getVersionId();
877                 version = version == null ? "0.0.0" //$NON-NLS-1$
878                         : new Version(version).toString();
879                 String versionedFeature = group.getIdentifier() + ":" + version; //$NON-NLS-1$
880
881                 ids.put(versionedFeature, info);
882             }
883         }
884
885         return ids;
886     }
887
888     /**
889      * Returns the ordered map of versioned feature ids -> AboutInfo that are
890      * new for this session.
891      *
892      * @return ordered map of versioned feature ids (key type:
893      *         <code>String</code>) -> infos (value type:
894      *         <code>AboutInfo</code>).
895      */
896     public Map<String, AboutInfo> getNewlyAddedBundleGroups() {
897         if (newlyAddedBundleGroups == null) {
898             newlyAddedBundleGroups = createNewBundleGroupsMap();
899         }
900         return newlyAddedBundleGroups;
901     }
902
903     /**
904      * Updates the old features setting and returns a map of new features.
905      */
906     private Map<String, AboutInfo> createNewBundleGroupsMap() {
907         // retrieve list of installed bundle groups from last session
908         IDialogSettings settings = IDEWorkbenchPlugin.getDefault()
909                 .getDialogSettings();
910         String[] previousFeaturesArray = settings.getArray(INSTALLED_FEATURES);
911
912         // get a map of currently installed bundle groups and store it for next
913         // session
914         Map<String, AboutInfo> bundleGroups = computeBundleGroupMap();
915         String[] currentFeaturesArray = new String[bundleGroups.size()];
916         bundleGroups.keySet().toArray(currentFeaturesArray);
917         settings.put(INSTALLED_FEATURES, currentFeaturesArray);
918
919         // remove the previously known from the current set
920         if (previousFeaturesArray != null) {
921             for (int i = 0; i < previousFeaturesArray.length; ++i) {
922                 bundleGroups.remove(previousFeaturesArray[i]);
923             }
924         }
925
926         return bundleGroups;
927     }
928
929     /**
930      * Declares all IDE-specific workbench images. This includes both "shared"
931      * images (named in {@link IDE.SharedImages}) and internal images (named in
932      * {@link org.eclipse.ui.internal.ide.IDEInternalWorkbenchImages}).
933      *
934      * @see IWorkbenchConfigurer#declareImage
935      */
936     private void declareWorkbenchImages() {
937
938         final String ICONS_PATH = "$nl$/icons/full/";//$NON-NLS-1$
939         final String PATH_ELOCALTOOL = ICONS_PATH + "elcl16/"; // Enabled //$NON-NLS-1$
940
941         // toolbar
942         // icons.
943         final String PATH_DLOCALTOOL = ICONS_PATH + "dlcl16/"; // Disabled //$NON-NLS-1$
944         // //$NON-NLS-1$
945         // toolbar
946         // icons.
947         final String PATH_ETOOL = ICONS_PATH + "etool16/"; // Enabled toolbar //$NON-NLS-1$
948         // //$NON-NLS-1$
949         // icons.
950         final String PATH_DTOOL = ICONS_PATH + "dtool16/"; // Disabled toolbar //$NON-NLS-1$
951         // //$NON-NLS-1$
952         // icons.
953         final String PATH_OBJECT = ICONS_PATH + "obj16/"; // Model object //$NON-NLS-1$
954         // //$NON-NLS-1$
955         // icons
956         final String PATH_WIZBAN = ICONS_PATH + "wizban/"; // Wizard //$NON-NLS-1$
957         // //$NON-NLS-1$
958         // icons
959
960         Bundle ideBundle = Platform.getBundle(IDEWorkbenchPlugin.IDE_WORKBENCH);
961
962         declareWorkbenchImage(ideBundle,
963                 IDEInternalWorkbenchImages.IMG_ETOOL_BUILD_EXEC, PATH_ETOOL
964                 + "build_exec.gif", false); //$NON-NLS-1$
965         declareWorkbenchImage(ideBundle,
966                 IDEInternalWorkbenchImages.IMG_ETOOL_BUILD_EXEC_HOVER,
967                 PATH_ETOOL + "build_exec.gif", false); //$NON-NLS-1$
968         declareWorkbenchImage(ideBundle,
969                 IDEInternalWorkbenchImages.IMG_ETOOL_BUILD_EXEC_DISABLED,
970                 PATH_DTOOL + "build_exec.gif", false); //$NON-NLS-1$
971
972         declareWorkbenchImage(ideBundle,
973                 IDEInternalWorkbenchImages.IMG_ETOOL_SEARCH_SRC, PATH_ETOOL
974                 + "search_src.gif", false); //$NON-NLS-1$
975         declareWorkbenchImage(ideBundle,
976                 IDEInternalWorkbenchImages.IMG_ETOOL_SEARCH_SRC_HOVER,
977                 PATH_ETOOL + "search_src.gif", false); //$NON-NLS-1$
978         declareWorkbenchImage(ideBundle,
979                 IDEInternalWorkbenchImages.IMG_ETOOL_SEARCH_SRC_DISABLED,
980                 PATH_DTOOL + "search_src.gif", false); //$NON-NLS-1$
981
982         declareWorkbenchImage(ideBundle,
983                 IDEInternalWorkbenchImages.IMG_ETOOL_NEXT_NAV, PATH_ETOOL
984                 + "next_nav.gif", false); //$NON-NLS-1$
985
986         declareWorkbenchImage(ideBundle,
987                 IDEInternalWorkbenchImages.IMG_ETOOL_PREVIOUS_NAV, PATH_ETOOL
988                 + "prev_nav.gif", false); //$NON-NLS-1$
989
990         declareWorkbenchImage(ideBundle,
991                 IDEInternalWorkbenchImages.IMG_WIZBAN_NEWPRJ_WIZ, PATH_WIZBAN
992                 + "newprj_wiz.png", false); //$NON-NLS-1$
993         declareWorkbenchImage(ideBundle,
994                 IDEInternalWorkbenchImages.IMG_WIZBAN_NEWFOLDER_WIZ,
995                 PATH_WIZBAN + "newfolder_wiz.png", false); //$NON-NLS-1$
996         declareWorkbenchImage(ideBundle,
997                 IDEInternalWorkbenchImages.IMG_WIZBAN_NEWFILE_WIZ, PATH_WIZBAN
998                 + "newfile_wiz.png", false); //$NON-NLS-1$
999
1000         declareWorkbenchImage(ideBundle,
1001                 IDEInternalWorkbenchImages.IMG_WIZBAN_IMPORTDIR_WIZ,
1002                 PATH_WIZBAN + "importdir_wiz.png", false); //$NON-NLS-1$
1003         declareWorkbenchImage(ideBundle,
1004                 IDEInternalWorkbenchImages.IMG_WIZBAN_IMPORTZIP_WIZ,
1005                 PATH_WIZBAN + "importzip_wiz.png", false); //$NON-NLS-1$
1006
1007         declareWorkbenchImage(ideBundle,
1008                 IDEInternalWorkbenchImages.IMG_WIZBAN_EXPORTDIR_WIZ,
1009                 PATH_WIZBAN + "exportdir_wiz.png", false); //$NON-NLS-1$
1010         declareWorkbenchImage(ideBundle,
1011                 IDEInternalWorkbenchImages.IMG_WIZBAN_EXPORTZIP_WIZ,
1012                 PATH_WIZBAN + "exportzip_wiz.png", false); //$NON-NLS-1$
1013
1014         declareWorkbenchImage(ideBundle,
1015                 IDEInternalWorkbenchImages.IMG_WIZBAN_RESOURCEWORKINGSET_WIZ,
1016                 PATH_WIZBAN + "workset_wiz.png", false); //$NON-NLS-1$
1017
1018         declareWorkbenchImage(ideBundle,
1019                 IDEInternalWorkbenchImages.IMG_DLGBAN_SAVEAS_DLG, PATH_WIZBAN
1020                 + "saveas_wiz.png", false); //$NON-NLS-1$
1021
1022         declareWorkbenchImage(ideBundle,
1023                 IDEInternalWorkbenchImages.IMG_DLGBAN_QUICKFIX_DLG, PATH_WIZBAN
1024                 + "quick_fix.png", false); //$NON-NLS-1$
1025
1026         declareWorkbenchImage(ideBundle, IDE.SharedImages.IMG_OBJ_PROJECT,
1027                 PATH_OBJECT + "prj_obj.gif", true); //$NON-NLS-1$
1028         declareWorkbenchImage(ideBundle,
1029                 IDE.SharedImages.IMG_OBJ_PROJECT_CLOSED, PATH_OBJECT
1030                 + "cprj_obj.gif", true); //$NON-NLS-1$
1031         declareWorkbenchImage(ideBundle, IDE.SharedImages.IMG_OPEN_MARKER,
1032                 PATH_ELOCALTOOL + "gotoobj_tsk.gif", true); //$NON-NLS-1$
1033
1034         declareWorkbenchImage(ideBundle,
1035                 IDEInternalWorkbenchImages.IMG_ELCL_QUICK_FIX_ENABLED,
1036                 PATH_ELOCALTOOL + "smartmode_co.gif", true); //$NON-NLS-1$
1037
1038         declareWorkbenchImage(ideBundle,
1039                 IDEInternalWorkbenchImages.IMG_DLCL_QUICK_FIX_DISABLED,
1040                 PATH_DLOCALTOOL + "smartmode_co.gif", true); //$NON-NLS-1$
1041
1042         // task objects
1043         // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_HPRIO_TSK,
1044         // PATH_OBJECT+"hprio_tsk.gif");
1045         // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_MPRIO_TSK,
1046         // PATH_OBJECT+"mprio_tsk.gif");
1047         // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_LPRIO_TSK,
1048         // PATH_OBJECT+"lprio_tsk.gif");
1049
1050         declareWorkbenchImage(ideBundle, IDE.SharedImages.IMG_OBJS_TASK_TSK,
1051                 PATH_OBJECT + "taskmrk_tsk.gif", true); //$NON-NLS-1$
1052         declareWorkbenchImage(ideBundle, IDE.SharedImages.IMG_OBJS_BKMRK_TSK,
1053                 PATH_OBJECT + "bkmrk_tsk.gif", true); //$NON-NLS-1$
1054
1055         declareWorkbenchImage(ideBundle,
1056                 IDEInternalWorkbenchImages.IMG_OBJS_COMPLETE_TSK, PATH_OBJECT
1057                 + "complete_tsk.gif", true); //$NON-NLS-1$
1058         declareWorkbenchImage(ideBundle,
1059                 IDEInternalWorkbenchImages.IMG_OBJS_INCOMPLETE_TSK, PATH_OBJECT
1060                 + "incomplete_tsk.gif", true); //$NON-NLS-1$
1061         declareWorkbenchImage(ideBundle,
1062                 IDEInternalWorkbenchImages.IMG_OBJS_WELCOME_ITEM, PATH_OBJECT
1063                 + "welcome_item.gif", true); //$NON-NLS-1$
1064         declareWorkbenchImage(ideBundle,
1065                 IDEInternalWorkbenchImages.IMG_OBJS_WELCOME_BANNER, PATH_OBJECT
1066                 + "welcome_banner.gif", true); //$NON-NLS-1$
1067         declareWorkbenchImage(ideBundle,
1068                 IDEInternalWorkbenchImages.IMG_OBJS_ERROR_PATH, PATH_OBJECT
1069                 + "error_tsk.gif", true); //$NON-NLS-1$
1070         declareWorkbenchImage(ideBundle,
1071                 IDEInternalWorkbenchImages.IMG_OBJS_WARNING_PATH, PATH_OBJECT
1072                 + "warn_tsk.gif", true); //$NON-NLS-1$
1073         declareWorkbenchImage(ideBundle,
1074                 IDEInternalWorkbenchImages.IMG_OBJS_INFO_PATH, PATH_OBJECT
1075                 + "info_tsk.gif", true); //$NON-NLS-1$
1076
1077         declareWorkbenchImage(ideBundle,
1078                 IDEInternalWorkbenchImages.IMG_LCL_FLAT_LAYOUT, PATH_ELOCALTOOL
1079                 + "flatLayout.gif", true); //$NON-NLS-1$
1080         declareWorkbenchImage(ideBundle,
1081                 IDEInternalWorkbenchImages.IMG_LCL_HIERARCHICAL_LAYOUT,
1082                 PATH_ELOCALTOOL + "hierarchicalLayout.gif", true); //$NON-NLS-1$
1083         declareWorkbenchImage(ideBundle,
1084                 IDEInternalWorkbenchImages.IMG_ETOOL_PROBLEM_CATEGORY,
1085                 PATH_ETOOL + "problem_category.gif", true); //$NON-NLS-1$
1086         /*
1087         declareWorkbenchImage(ideBundle,
1088                 IDEInternalWorkbenchImages.IMG_LCL_LINKTO_HELP, PATH_ELOCALTOOL
1089                         + "linkto_help.gif", false); //$NON-NLS-1$
1090          */
1091
1092         // synchronization indicator objects
1093         // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_WBET_STAT,
1094         // PATH_OVERLAY+"wbet_stat.gif");
1095         // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_SBET_STAT,
1096         // PATH_OVERLAY+"sbet_stat.gif");
1097         // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_CONFLICT_STAT,
1098         // PATH_OVERLAY+"conflict_stat.gif");
1099
1100         // content locality indicator objects
1101         // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_NOTLOCAL_STAT,
1102         // PATH_STAT+"notlocal_stat.gif");
1103         // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_LOCAL_STAT,
1104         // PATH_STAT+"local_stat.gif");
1105         // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_FILLLOCAL_STAT,
1106         // PATH_STAT+"filllocal_stat.gif");
1107     }
1108
1109     /**
1110      * Declares an IDE-specific workbench image.
1111      *
1112      * @param symbolicName
1113      *            the symbolic name of the image
1114      * @param path
1115      *            the path of the image file; this path is relative to the base
1116      *            of the IDE plug-in
1117      * @param shared
1118      *            <code>true</code> if this is a shared image, and
1119      *            <code>false</code> if this is not a shared image
1120      * @see IWorkbenchConfigurer#declareImage
1121      */
1122     private void declareWorkbenchImage(Bundle ideBundle, String symbolicName,
1123             String path, boolean shared) {
1124         URL url = FileLocator.find(ideBundle, new Path(path), null);
1125         ImageDescriptor desc = ImageDescriptor.createFromURL(url);
1126         getWorkbenchConfigurer().declareImage(symbolicName, desc, shared);
1127     }
1128
1129     /*
1130      * (non-Javadoc)
1131      *
1132      * @see org.eclipse.ui.application.WorkbenchAdvisor#getMainPreferencePageId
1133      */
1134     @Override
1135     public String getMainPreferencePageId() {
1136         // indicate that we want the Workench preference page to be prominent
1137         return WORKBENCH_PREFERENCE_CATEGORY_ID;
1138     }
1139
1140     /**
1141      * @return the workspace location string, or <code>null</code> if the
1142      *         location is not being shown
1143      */
1144     public String getWorkspaceLocation() {
1145         // read command line, which has priority
1146         IEclipseContext context = getWorkbenchConfigurer().getWorkbench().getService(IEclipseContext.class);
1147         String location = context != null ? (String) context.get(E4Workbench.FORCED_SHOW_LOCATION) : null;
1148         if (location != null) {
1149             return location;
1150         }
1151         // read the preference
1152         if (IDEWorkbenchPlugin.getDefault().getPreferenceStore().getBoolean(IDEInternalPreferences.SHOW_LOCATION)) {
1153             return Platform.getLocation().toOSString();
1154         }
1155         return null;
1156     }
1157
1158     /**
1159      * @return the welcome perspective infos, or <code>null</code> if none or
1160      *         if they should be ignored due to the new intro being present
1161      */
1162     public AboutInfo[] getWelcomePerspectiveInfos() {
1163         if (welcomePerspectiveInfos == null) {
1164             // support old welcome perspectives if intro plugin is not present
1165             if (!hasIntro()) {
1166                 Map<String, AboutInfo> m = getNewlyAddedBundleGroups();
1167                 ArrayList<AboutInfo> list = new ArrayList<AboutInfo>(m.size());
1168                 for (Iterator<AboutInfo> i = m.values().iterator(); i.hasNext();) {
1169                     AboutInfo info = i.next();
1170                     if (info != null && info.getWelcomePerspectiveId() != null
1171                             && info.getWelcomePageURL() != null) {
1172                         list.add(info);
1173                     }
1174                 }
1175                 welcomePerspectiveInfos = new AboutInfo[list.size()];
1176                 list.toArray(welcomePerspectiveInfos);
1177             }
1178         }
1179         return welcomePerspectiveInfos;
1180     }
1181
1182     /*
1183      * (non-Javadoc)
1184      *
1185      * @see org.eclipse.ui.application.WorkbenchAdvisor#getWorkbenchErrorHandler()
1186      */
1187
1188     private AbstractStatusHandler workbenchErrorHandler = new AbstractStatusHandler() {
1189
1190         @Override
1191         public void handle(StatusAdapter statusAdapter, int style) {
1192             if (ideWorkbenchErrorHandler == null) {
1193                 ideWorkbenchErrorHandler = new IDEWorkbenchErrorHandler(
1194                         getWorkbenchConfigurer());
1195             }
1196             ideWorkbenchErrorHandler.handle(statusAdapter, style);
1197
1198             BundleContext context = Activator.getDefault().getBundle().getBundleContext();
1199             ServiceReference<?> ref = context.getServiceReference(UnhandledExceptionService.class.getName());
1200             UnhandledExceptionService unhandled = (UnhandledExceptionService)context.getService(ref);
1201             Throwable t = statusAdapter.getStatus().getException();
1202             if(t != null)
1203                 unhandled.handle(t);
1204
1205         }
1206     };
1207
1208     @Override
1209     public AbstractStatusHandler getWorkbenchErrorHandler() {
1210         return workbenchErrorHandler;
1211     }
1212
1213     /* (non-Javadoc)
1214      * @see org.eclipse.ui.application.WorkbenchAdvisor#eventLoopIdle(org.eclipse.swt.widgets.Display)
1215      */
1216     @Override
1217     public void eventLoopIdle(Display display) {
1218         if (delayedEventsProcessor != null)
1219             delayedEventsProcessor.catchUp(display);
1220         super.eventLoopIdle(display);
1221     }
1222
1223 }