]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.workbench/src/org/simantics/workbench/internal/SimanticsWorkbenchAdvisor.java
Allow "doNotSynchronizeOntologies" to work.
[simantics/platform.git] / bundles / org.simantics.workbench / src / org / simantics / workbench / internal / SimanticsWorkbenchAdvisor.java
1 /*******************************************************************************
2  * Copyright (c) 2007, 2010 Association for Decentralized Information Management
3  * in Industry THTH ry.
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License v1.0
6  * which accompanies this distribution, and is available at
7  * http://www.eclipse.org/legal/epl-v10.html
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 package org.simantics.workbench.internal;
13
14 import java.io.IOException;
15 import java.lang.reflect.InvocationTargetException;
16 import java.net.URL;
17 import java.text.Collator;
18 import java.util.ArrayList;
19 import java.util.Iterator;
20 import java.util.Map;
21 import java.util.TreeMap;
22
23 import org.eclipse.core.internal.resources.Workspace;
24 import org.eclipse.core.net.proxy.IProxyService;
25 import org.eclipse.core.resources.IContainer;
26 import org.eclipse.core.resources.IResource;
27 import org.eclipse.core.resources.ResourcesPlugin;
28 import org.eclipse.core.resources.WorkspaceJob;
29 import org.eclipse.core.runtime.CoreException;
30 import org.eclipse.core.runtime.FileLocator;
31 import org.eclipse.core.runtime.IAdaptable;
32 import org.eclipse.core.runtime.IBundleGroup;
33 import org.eclipse.core.runtime.IBundleGroupProvider;
34 import org.eclipse.core.runtime.ILog;
35 import org.eclipse.core.runtime.IProgressMonitor;
36 import org.eclipse.core.runtime.IStatus;
37 import org.eclipse.core.runtime.MultiStatus;
38 import org.eclipse.core.runtime.Path;
39 import org.eclipse.core.runtime.Platform;
40 import org.eclipse.core.runtime.ProgressMonitorWrapper;
41 import org.eclipse.core.runtime.Status;
42 import org.eclipse.core.runtime.SubMonitor;
43 import org.eclipse.core.runtime.jobs.Job;
44 import org.eclipse.e4.core.contexts.IEclipseContext;
45 import org.eclipse.e4.ui.internal.workbench.E4Workbench;
46 import org.eclipse.jface.dialogs.ErrorDialog;
47 import org.eclipse.jface.dialogs.IDialogSettings;
48 import org.eclipse.jface.dialogs.MessageDialog;
49 import org.eclipse.jface.dialogs.TrayDialog;
50 import org.eclipse.jface.operation.IRunnableWithProgress;
51 import org.eclipse.jface.preference.IPreferenceStore;
52 import org.eclipse.jface.resource.ImageDescriptor;
53 import org.eclipse.jface.util.Policy;
54 import org.eclipse.jface.window.Window;
55 import org.eclipse.swt.SWT;
56 import org.eclipse.swt.events.SelectionAdapter;
57 import org.eclipse.swt.events.SelectionEvent;
58 import org.eclipse.swt.widgets.Composite;
59 import org.eclipse.swt.widgets.Display;
60 import org.eclipse.swt.widgets.Event;
61 import org.eclipse.swt.widgets.Listener;
62 import org.eclipse.swt.widgets.Shell;
63 import org.eclipse.ui.IPerspectiveDescriptor;
64 import org.eclipse.ui.PlatformUI;
65 import org.eclipse.ui.application.IWorkbenchConfigurer;
66 import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
67 import org.eclipse.ui.application.WorkbenchAdvisor;
68 import org.eclipse.ui.application.WorkbenchWindowAdvisor;
69 import org.eclipse.ui.ide.IDE;
70 import org.eclipse.ui.internal.ISelectionConversionService;
71 import org.eclipse.ui.internal.Workbench;
72 import org.eclipse.ui.internal.ide.AboutInfo;
73 import org.eclipse.ui.internal.ide.IDEInternalPreferences;
74 import org.eclipse.ui.internal.ide.IDEInternalWorkbenchImages;
75 import org.eclipse.ui.internal.ide.IDESelectionConversionService;
76 import org.eclipse.ui.internal.ide.IDEWorkbenchActivityHelper;
77 import org.eclipse.ui.internal.ide.IDEWorkbenchErrorHandler;
78 import org.eclipse.ui.internal.ide.IDEWorkbenchMessages;
79 import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin;
80 import org.eclipse.ui.internal.ide.undo.WorkspaceUndoMonitor;
81 import org.eclipse.ui.internal.progress.ProgressMonitorJobsDialog;
82 import org.eclipse.ui.keys.IBindingService;
83 import org.eclipse.ui.progress.IProgressService;
84 import org.eclipse.ui.statushandlers.AbstractStatusHandler;
85 import org.osgi.framework.Bundle;
86 import org.osgi.framework.ServiceReference;
87 import org.osgi.framework.Version;
88 import org.simantics.CancelStartupException;
89 import org.simantics.PlatformException;
90 import org.simantics.Simantics;
91 import org.simantics.SimanticsPlatform;
92 import org.simantics.SimanticsPlatform.OntologyRecoveryPolicy;
93 import org.simantics.SimanticsPlatform.RecoveryPolicy;
94 import org.simantics.TimingProgressMonitor;
95 import org.simantics.application.arguments.IArguments;
96 import org.simantics.application.arguments.SimanticsArguments;
97 import org.simantics.db.common.Indexing;
98 import org.simantics.db.indexing.DatabaseIndexing;
99 import org.simantics.db.procore.server.environment.RebootRequiredException;
100 import org.simantics.db.procore.server.environment.windows.Product;
101 import org.simantics.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.ui.dialogs.ShowError;
109 import org.simantics.utils.ui.dialogs.ShowMessage;
110 import org.slf4j.Logger;
111 import org.slf4j.LoggerFactory;
112
113
114 /**
115  * @author Tuukka Lehtonen
116  */
117 public class SimanticsWorkbenchAdvisor extends WorkbenchAdvisor {
118     
119     private static final Logger LOGGER = LoggerFactory.getLogger(SimanticsWorkbenchAdvisor.class);
120
121     private static final boolean PROFILE_PLATFORM_STARTUP = false;
122
123     private static final String SHUT_DOWN_TASK = "Shutting down...";
124
125     private static final String SHUT_DOWN_PLATFORM_TASK = "Shutting down platform...";
126
127     private static final String WORKBENCH_PREFERENCE_CATEGORY_ID = "org.eclipse.ui.preferencePages.Workbench"; //$NON-NLS-1$
128
129     /**
130      * The dialog setting key to access the known installed features since the
131      * last time the workbench was run.
132      */
133     private static final String INSTALLED_FEATURES = "installedFeatures"; //$NON-NLS-1$
134
135     /**
136      * The arguments received by the application.
137      */
138     protected final IArguments args;
139
140     protected final boolean restoredPreviousSession = false;
141
142     /**
143      * Only true while opening the initial windows during {@link #openWindows()}.
144      * Used by {@link SimanticsWorkbenchWindowAdvisor#postWindowOpen()} to
145      * recognize when to skip all one-time initialization.
146      */
147     protected boolean workbenchWindowsInitialized = false;
148
149     /**
150      * Whether or not to save unsaved database changes before exiting the
151      * workbench.
152      */
153     protected boolean saveAtExit = false;
154
155     /**
156      * Ordered map of versioned feature ids -> info that are new for this
157      * session; <code>null</code> if uninitialized. Key type:
158      * <code>String</code>, Value type: <code>AboutInfo</code>.
159      */
160     private Map<String, AboutInfo> newlyAddedBundleGroups;
161
162     /**
163      * Array of <code>AboutInfo</code> for all new installed features that
164      * specify a welcome perspective.
165      */
166     private AboutInfo[] welcomePerspectiveInfos = null;
167
168     /**
169      * Helper for managing activites in response to workspace changes.
170      */
171     private IDEWorkbenchActivityHelper activityHelper = null;
172
173     /**
174      * Helper for managing work that is performed when the system is otherwise
175      * idle.
176      */
177     private IDEIdleHelper idleHelper;
178
179     private Listener settingsChangeListener;
180
181     /**
182      * Support class for monitoring workspace changes and periodically
183      * validating the undo history
184      */
185     private WorkspaceUndoMonitor workspaceUndoMonitor;
186
187     /**
188      * The IDE workbench error handler.
189      */
190     private AbstractStatusHandler ideWorkbenchErrorHandler;
191
192     /**
193      * Helper class used to process delayed events.
194      */
195     private DelayedEventsProcessor delayedEventsProcessor;
196     
197     /**
198      * Creates a new workbench advisor instance.
199      * @param processor
200      */
201     public SimanticsWorkbenchAdvisor(IArguments args, DelayedEventsProcessor processor) {
202         super();
203         this.args = args;
204         this.delayedEventsProcessor = processor;
205
206         Listener closeListener = new Listener() {
207             public void handleEvent(Event event) {
208                 boolean doExit = SimanticsWorkbenchWindowAdvisor.promptOnExit(null);
209                 event.doit = doExit;
210                 if (!doExit)
211                     event.type = SWT.None;
212             }
213         };
214         Display.getDefault().addListener(SWT.Close, closeListener);
215     }
216
217     public IArguments getArguments() {
218         return args;
219     }
220
221     public boolean workbenchInitialized() {
222         return workbenchWindowsInitialized;
223     }
224
225     public boolean restoredPreviousSession() {
226         return restoredPreviousSession;
227     }
228
229     boolean saveAtExit() {
230         return saveAtExit;
231     }
232
233     void setSaveAtExit(boolean saveAtExit) {
234         this.saveAtExit = saveAtExit;
235     }
236
237     /*
238      * (non-Javadoc)
239      *
240      * @see org.eclipse.ui.application.WorkbenchAdvisor#initialize
241      */
242     @Override
243     public void initialize(IWorkbenchConfigurer configurer) {
244         // By default, we always save and restore the workbench state.
245         configurer.setSaveAndRestore(true);
246
247         checkWorkspaceDatabaseIndexes();
248
249         // Start tracking the active perspective to activate contexts based on it.
250         new PerspectiveContextActivator();
251         new PerspectiveBarsActivator();
252
253         // register workspace adapters
254         IDE.registerAdapters();
255
256         // register shared images
257         declareWorkbenchImages();
258
259         // initialize the activity helper
260         activityHelper = IDEWorkbenchActivityHelper.getInstance();
261
262         // initialize idle handler
263         idleHelper = new IDEIdleHelper(configurer);
264
265         // initialize the workspace undo monitor
266         workspaceUndoMonitor = WorkspaceUndoMonitor.getInstance();
267
268         // show Help button in JFace dialogs
269         TrayDialog.setDialogHelpAvailable(true);
270
271         Policy.setComparator(Collator.getInstance());
272     }
273
274     private void checkWorkspaceDatabaseIndexes() {
275         try {
276             DatabaseIndexing.validateIndexes();
277         } catch (IOException e) {
278             Activator.logError("Problems encountered while checking database indexes, see exception for details.", e);
279         }
280     }
281
282     public WorkbenchWindowAdvisor createWorkbenchWindowAdvisorClass(SimanticsWorkbenchAdvisor advisor, IWorkbenchWindowConfigurer configurer) {
283         return new SimanticsWorkbenchWindowAdvisor(this, configurer);
284     }
285
286     @Override
287     public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) {
288         // Attach database session watchdog.
289         new SessionWatchdog().attach( Simantics.getSessionContextProvider() );
290
291         return createWorkbenchWindowAdvisorClass(this, configurer);
292     }
293
294     /**
295      * For gaining direct access to super.openWindows() in implementations
296      * inheriting this one.
297      */
298     public boolean openWindowsSuper() {
299         return super.openWindows();
300     }
301
302     /**
303      * Sadly we do not know why key bindings are lost and why this helps. But it
304      * does. Visiting the <code>Keys</code> preference page and pressing OK uses
305      * this the same call and it seems to salvage the bindings that have been in
306      * some cases destroyed by <code>BindingToModelProcessor</code>.
307      * 
308      * <p>
309      * Related links:
310      * https://techblog.ralph-schuster.eu/2013/10/13/eclipsee4-problem-with-key-bindings/comment-page-1/
311      * https://www.eclipse.org/forums/index.php/t/550175/
312      * https://bugs.eclipse.org/bugs/show_bug.cgi?id=461037
313      * 
314      * @see platform issue #6353
315      */
316     private void fixBindings() {
317         try {
318             IBindingService bs = PlatformUI.getWorkbench().getAdapter(IBindingService.class);
319             bs.savePreferences(bs.getActiveScheme(), bs.getBindings());
320         } catch (IOException e) {
321             Activator.logError(getClass().getSimpleName() + ".fixBindings failed", e);
322         }
323     }
324
325     @Override
326     public boolean openWindows() {
327         boolean platformOk = startPlatform();
328         LOGGER.info("startPlatform finished");
329         TimeLogger.log("SimanticsWorkbenchAdvisor.startPlatform finished");
330
331         if (platformOk) {
332             // At this point workbenchConfigurer.getSaveAndRestore()
333             // returns false iff something has gone terribly wrong
334             // before this. Currently saveAndRestore is always true.
335             boolean windowsOpened = super.openWindows();
336             TimeLogger.log("Opened windows");
337             if (windowsOpened) {
338                 workbenchWindowsInitialized = true;
339
340                 // Start the database garbage collector after a short while.
341                 SessionGarbageCollectorJob.getInstance().scheduleAfterQuietTime();
342
343                 // #6353: Workaround for  
344                 fixBindings();
345
346                 return true;
347             }
348         }
349
350         // Make sure platform shutdown is ran if window opening fails.
351         try {
352             platformShutdownRunnable.run(null);
353         } catch (InvocationTargetException e) {
354             Activator.logError(getClass().getSimpleName() + ".openWindows failed", e.getCause());
355         } catch (InterruptedException e) {
356             Activator.logError(getClass().getSimpleName() + ".openWindows failed", e);
357         }
358         return false;
359     }
360
361     protected boolean startPlatform() {
362         // Verify selected perspective
363         if (args.contains(SimanticsArguments.PERSPECTIVE)) {
364             String perspectiveId = args.get(SimanticsArguments.PERSPECTIVE);
365             IPerspectiveDescriptor perspective = PlatformUI.getWorkbench().getPerspectiveRegistry().findPerspectiveWithId(perspectiveId);
366             if (perspective == null) {
367                 StringBuilder msg = new StringBuilder();
368                 msg.append("Requested perspective not found: '" + perspectiveId + "'\n");
369                 msg.append("Valid alternatives are:\n");
370                 for (IPerspectiveDescriptor pd : PlatformUI.getWorkbench().getPerspectiveRegistry().getPerspectives()) {
371                     msg.append("    " + pd.getId() + "\n");
372                 }
373
374                 ShowMessage.syncShowError("Invalid Perspective", msg.toString());
375                 return false;
376             }
377         }
378
379         ILog log = Platform.getLog(Activator.getDefault().getBundle());
380
381         try {
382             //
383             //
384             // Create Simantics Platform Helper.
385             //
386             // If Simantics is started from Eclipse IDE or with -fixerrors option,
387             // there is an attempt to fix errors.
388             //
389             // On ontology mismatch, there is an attempt to merge new ontology to the
390             // existing database. With -reinstall, the database is cleaned and
391             // reinstalled.
392             //
393             //
394
395             RecoveryPolicy workspacePolicy = Platform.inDevelopmentMode() ? RecoveryPolicy.FixError : RecoveryPolicy.ThrowError;
396             OntologyRecoveryPolicy ontologyPolicy = Platform.inDevelopmentMode() ? OntologyRecoveryPolicy.Merge : OntologyRecoveryPolicy.ThrowError;
397
398             if (args.contains(SimanticsArguments.RECOVERY_POLICY_FIX_ERRORS)) {
399                 workspacePolicy = RecoveryPolicy.FixError;
400                 ontologyPolicy = OntologyRecoveryPolicy.Merge;
401             }
402
403             boolean requireSynchronize = true;
404
405             if (args.contains(SimanticsArguments.ONTOLOGY_RECOVERY_POLICY_REINSTALL)) {
406                 ontologyPolicy = OntologyRecoveryPolicy.ReinstallDatabase;
407             }
408
409             if (args.contains(SimanticsArguments.DO_NOT_SYNCHRONIZE_ONTOLOGIES)) {
410                 requireSynchronize = false;
411                 ontologyPolicy = OntologyRecoveryPolicy.Bypass;
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(100));
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
746                 progress.setWorkRemaining(0);
747             } finally {
748                 if (monitor != null) {
749                     monitor.done();
750                 }
751             }
752         }
753     };
754
755     /**
756      * Disconnect from the workspace and close ProCore sessions.
757      */
758     private void disconnectFromWorkspace() {
759         // save the workspace
760         final MultiStatus status = new MultiStatus(
761                 IDEWorkbenchPlugin.IDE_WORKBENCH, 1,
762                 IDEWorkbenchMessages.ProblemSavingWorkbench, null);
763
764         final ProgressMonitorJobsDialog p = new CancelableProgressMonitorJobsDialog(
765                 null);
766
767         final boolean applyPolicy = ResourcesPlugin.getWorkspace()
768                 .getDescription().isApplyFileStatePolicy();
769
770         final IRunnableWithProgress workspaceShutdownRunnable = new IRunnableWithProgress() {
771             @Override
772             public void run(IProgressMonitor monitor) {
773                 try {
774                     status.merge(((Workspace) ResourcesPlugin.getWorkspace()).save(true, true, monitor));
775                 } catch (CoreException e) {
776                     status.merge(e.getStatus());
777                 }
778             }
779         };
780
781         IRunnableWithProgress shutdownRunnable = new IRunnableWithProgress() {
782             @Override
783             public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
784                 if (applyPolicy)
785                     monitor = new CancelableProgressMonitorWrapper(
786                             monitor, p);
787
788                 SubMonitor progress = SubMonitor.convert(monitor, SHUT_DOWN_TASK, 2);
789                 try {
790                     workspaceShutdownRunnable.run(progress.newChild(1, SubMonitor.SUPPRESS_NONE));
791                     platformShutdownRunnable.run(progress.newChild(1, SubMonitor.SUPPRESS_NONE));
792                 } finally {
793                     monitor.done();
794                 }
795             }
796         };
797
798         try {
799             new ProgressMonitorJobsDialog(null).run(true, false, shutdownRunnable);
800         } catch (InvocationTargetException e) {
801             status.merge(new Status(IStatus.ERROR,
802                     IDEWorkbenchPlugin.IDE_WORKBENCH, 1,
803                     IDEWorkbenchMessages.InternalError, e.getTargetException()));
804         } catch (InterruptedException e) {
805             status.merge(new Status(IStatus.ERROR,
806                     IDEWorkbenchPlugin.IDE_WORKBENCH, 1,
807                     IDEWorkbenchMessages.InternalError, e));
808         }
809         ErrorDialog.openError(null,
810                 IDEWorkbenchMessages.ProblemsSavingWorkspace, null, status,
811                 IStatus.ERROR | IStatus.WARNING);
812         if (!status.isOK()) {
813             IDEWorkbenchPlugin.log(
814                     IDEWorkbenchMessages.ProblemsSavingWorkspace, status);
815         }
816     }
817
818     /*
819      * (non-Javadoc)
820      *
821      * @see org.eclipse.ui.application.WorkbenchAdvisor#getDefaultPageInput
822      */
823     @Override
824     public IAdaptable getDefaultPageInput() {
825         return ResourcesPlugin.getWorkspace().getRoot();
826     }
827
828     /*
829      * (non-Javadoc)
830      *
831      * @see org.eclipse.ui.application.WorkbenchAdvisor
832      */
833     @Override
834     public String getInitialWindowPerspectiveId() {
835         int index = PlatformUI.getWorkbench().getWorkbenchWindowCount() - 1;
836
837         String perspectiveId = null;
838         AboutInfo[] welcomeInfos = getWelcomePerspectiveInfos();
839         if (index >= 0 && welcomeInfos != null && index < welcomeInfos.length) {
840             perspectiveId = welcomeInfos[index].getWelcomePerspectiveId();
841         }
842
843         if (perspectiveId == null && args.contains(SimanticsArguments.PERSPECTIVE)) {
844             String id = args.get(SimanticsArguments.PERSPECTIVE);
845             IPerspectiveDescriptor perspective = PlatformUI.getWorkbench().getPerspectiveRegistry().findPerspectiveWithId(id);
846             if (perspective != null)
847                 perspectiveId = id;
848         }
849
850         if (perspectiveId == null) {
851             IProject project = Simantics.peekProject();
852             if (project != null)
853                 perspectiveId = project.getHint(ProjectKeys.DEFAULT_PERSPECTIVE);
854         }
855
856         //System.out.println("Initial perspective: " + perspectiveId);
857
858         return perspectiveId;
859     }
860
861     /**
862      * Returns the map of versioned feature ids -> info object for all installed
863      * features. The format of the versioned feature id (the key of the map) is
864      * featureId + ":" + versionId.
865      *
866      * @return map of versioned feature ids -> info object (key type:
867      *         <code>String</code>, value type: <code>AboutInfo</code>)
868      * @since 3.0
869      */
870     private Map<String, AboutInfo> computeBundleGroupMap() {
871         // use tree map to get predicable order
872         Map<String, AboutInfo> ids = new TreeMap<String, AboutInfo>();
873
874         IBundleGroupProvider[] providers = Platform.getBundleGroupProviders();
875         for (int i = 0; i < providers.length; ++i) {
876             IBundleGroup[] groups = providers[i].getBundleGroups();
877             for (int j = 0; j < groups.length; ++j) {
878                 IBundleGroup group = groups[j];
879                 AboutInfo info = new AboutInfo(group);
880
881                 String version = info.getVersionId();
882                 version = version == null ? "0.0.0" //$NON-NLS-1$
883                         : new Version(version).toString();
884                 String versionedFeature = group.getIdentifier() + ":" + version; //$NON-NLS-1$
885
886                 ids.put(versionedFeature, info);
887             }
888         }
889
890         return ids;
891     }
892
893     /**
894      * Returns the ordered map of versioned feature ids -> AboutInfo that are
895      * new for this session.
896      *
897      * @return ordered map of versioned feature ids (key type:
898      *         <code>String</code>) -> infos (value type:
899      *         <code>AboutInfo</code>).
900      */
901     public Map<String, AboutInfo> getNewlyAddedBundleGroups() {
902         if (newlyAddedBundleGroups == null) {
903             newlyAddedBundleGroups = createNewBundleGroupsMap();
904         }
905         return newlyAddedBundleGroups;
906     }
907
908     /**
909      * Updates the old features setting and returns a map of new features.
910      */
911     private Map<String, AboutInfo> createNewBundleGroupsMap() {
912         // retrieve list of installed bundle groups from last session
913         IDialogSettings settings = IDEWorkbenchPlugin.getDefault()
914                 .getDialogSettings();
915         String[] previousFeaturesArray = settings.getArray(INSTALLED_FEATURES);
916
917         // get a map of currently installed bundle groups and store it for next
918         // session
919         Map<String, AboutInfo> bundleGroups = computeBundleGroupMap();
920         String[] currentFeaturesArray = new String[bundleGroups.size()];
921         bundleGroups.keySet().toArray(currentFeaturesArray);
922         settings.put(INSTALLED_FEATURES, currentFeaturesArray);
923
924         // remove the previously known from the current set
925         if (previousFeaturesArray != null) {
926             for (int i = 0; i < previousFeaturesArray.length; ++i) {
927                 bundleGroups.remove(previousFeaturesArray[i]);
928             }
929         }
930
931         return bundleGroups;
932     }
933
934     /**
935      * Declares all IDE-specific workbench images. This includes both "shared"
936      * images (named in {@link IDE.SharedImages}) and internal images (named in
937      * {@link org.eclipse.ui.internal.ide.IDEInternalWorkbenchImages}).
938      *
939      * @see IWorkbenchConfigurer#declareImage
940      */
941     private void declareWorkbenchImages() {
942
943         final String ICONS_PATH = "$nl$/icons/full/";//$NON-NLS-1$
944         final String PATH_ELOCALTOOL = ICONS_PATH + "elcl16/"; // Enabled //$NON-NLS-1$
945
946         // toolbar
947         // icons.
948         final String PATH_DLOCALTOOL = ICONS_PATH + "dlcl16/"; // Disabled //$NON-NLS-1$
949         // //$NON-NLS-1$
950         // toolbar
951         // icons.
952         final String PATH_ETOOL = ICONS_PATH + "etool16/"; // Enabled toolbar //$NON-NLS-1$
953         // //$NON-NLS-1$
954         // icons.
955         final String PATH_DTOOL = ICONS_PATH + "dtool16/"; // Disabled toolbar //$NON-NLS-1$
956         // //$NON-NLS-1$
957         // icons.
958         final String PATH_OBJECT = ICONS_PATH + "obj16/"; // Model object //$NON-NLS-1$
959         // //$NON-NLS-1$
960         // icons
961         final String PATH_WIZBAN = ICONS_PATH + "wizban/"; // Wizard //$NON-NLS-1$
962         // //$NON-NLS-1$
963         // icons
964
965         Bundle ideBundle = Platform.getBundle(IDEWorkbenchPlugin.IDE_WORKBENCH);
966
967         declareWorkbenchImage(ideBundle,
968                 IDEInternalWorkbenchImages.IMG_ETOOL_BUILD_EXEC, PATH_ETOOL
969                 + "build_exec.gif", false); //$NON-NLS-1$
970         declareWorkbenchImage(ideBundle,
971                 IDEInternalWorkbenchImages.IMG_ETOOL_BUILD_EXEC_HOVER,
972                 PATH_ETOOL + "build_exec.gif", false); //$NON-NLS-1$
973         declareWorkbenchImage(ideBundle,
974                 IDEInternalWorkbenchImages.IMG_ETOOL_BUILD_EXEC_DISABLED,
975                 PATH_DTOOL + "build_exec.gif", false); //$NON-NLS-1$
976
977         declareWorkbenchImage(ideBundle,
978                 IDEInternalWorkbenchImages.IMG_ETOOL_SEARCH_SRC, PATH_ETOOL
979                 + "search_src.gif", false); //$NON-NLS-1$
980         declareWorkbenchImage(ideBundle,
981                 IDEInternalWorkbenchImages.IMG_ETOOL_SEARCH_SRC_HOVER,
982                 PATH_ETOOL + "search_src.gif", false); //$NON-NLS-1$
983         declareWorkbenchImage(ideBundle,
984                 IDEInternalWorkbenchImages.IMG_ETOOL_SEARCH_SRC_DISABLED,
985                 PATH_DTOOL + "search_src.gif", false); //$NON-NLS-1$
986
987         declareWorkbenchImage(ideBundle,
988                 IDEInternalWorkbenchImages.IMG_ETOOL_NEXT_NAV, PATH_ETOOL
989                 + "next_nav.gif", false); //$NON-NLS-1$
990
991         declareWorkbenchImage(ideBundle,
992                 IDEInternalWorkbenchImages.IMG_ETOOL_PREVIOUS_NAV, PATH_ETOOL
993                 + "prev_nav.gif", false); //$NON-NLS-1$
994
995         declareWorkbenchImage(ideBundle,
996                 IDEInternalWorkbenchImages.IMG_WIZBAN_NEWPRJ_WIZ, PATH_WIZBAN
997                 + "newprj_wiz.png", false); //$NON-NLS-1$
998         declareWorkbenchImage(ideBundle,
999                 IDEInternalWorkbenchImages.IMG_WIZBAN_NEWFOLDER_WIZ,
1000                 PATH_WIZBAN + "newfolder_wiz.png", false); //$NON-NLS-1$
1001         declareWorkbenchImage(ideBundle,
1002                 IDEInternalWorkbenchImages.IMG_WIZBAN_NEWFILE_WIZ, PATH_WIZBAN
1003                 + "newfile_wiz.png", false); //$NON-NLS-1$
1004
1005         declareWorkbenchImage(ideBundle,
1006                 IDEInternalWorkbenchImages.IMG_WIZBAN_IMPORTDIR_WIZ,
1007                 PATH_WIZBAN + "importdir_wiz.png", false); //$NON-NLS-1$
1008         declareWorkbenchImage(ideBundle,
1009                 IDEInternalWorkbenchImages.IMG_WIZBAN_IMPORTZIP_WIZ,
1010                 PATH_WIZBAN + "importzip_wiz.png", false); //$NON-NLS-1$
1011
1012         declareWorkbenchImage(ideBundle,
1013                 IDEInternalWorkbenchImages.IMG_WIZBAN_EXPORTDIR_WIZ,
1014                 PATH_WIZBAN + "exportdir_wiz.png", false); //$NON-NLS-1$
1015         declareWorkbenchImage(ideBundle,
1016                 IDEInternalWorkbenchImages.IMG_WIZBAN_EXPORTZIP_WIZ,
1017                 PATH_WIZBAN + "exportzip_wiz.png", false); //$NON-NLS-1$
1018
1019         declareWorkbenchImage(ideBundle,
1020                 IDEInternalWorkbenchImages.IMG_WIZBAN_RESOURCEWORKINGSET_WIZ,
1021                 PATH_WIZBAN + "workset_wiz.png", false); //$NON-NLS-1$
1022
1023         declareWorkbenchImage(ideBundle,
1024                 IDEInternalWorkbenchImages.IMG_DLGBAN_SAVEAS_DLG, PATH_WIZBAN
1025                 + "saveas_wiz.png", false); //$NON-NLS-1$
1026
1027         declareWorkbenchImage(ideBundle,
1028                 IDEInternalWorkbenchImages.IMG_DLGBAN_QUICKFIX_DLG, PATH_WIZBAN
1029                 + "quick_fix.png", false); //$NON-NLS-1$
1030
1031         declareWorkbenchImage(ideBundle, IDE.SharedImages.IMG_OBJ_PROJECT,
1032                 PATH_OBJECT + "prj_obj.gif", true); //$NON-NLS-1$
1033         declareWorkbenchImage(ideBundle,
1034                 IDE.SharedImages.IMG_OBJ_PROJECT_CLOSED, PATH_OBJECT
1035                 + "cprj_obj.gif", true); //$NON-NLS-1$
1036         declareWorkbenchImage(ideBundle, IDE.SharedImages.IMG_OPEN_MARKER,
1037                 PATH_ELOCALTOOL + "gotoobj_tsk.gif", true); //$NON-NLS-1$
1038
1039         declareWorkbenchImage(ideBundle,
1040                 IDEInternalWorkbenchImages.IMG_ELCL_QUICK_FIX_ENABLED,
1041                 PATH_ELOCALTOOL + "smartmode_co.gif", true); //$NON-NLS-1$
1042
1043         declareWorkbenchImage(ideBundle,
1044                 IDEInternalWorkbenchImages.IMG_DLCL_QUICK_FIX_DISABLED,
1045                 PATH_DLOCALTOOL + "smartmode_co.gif", true); //$NON-NLS-1$
1046
1047         // task objects
1048         // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_HPRIO_TSK,
1049         // PATH_OBJECT+"hprio_tsk.gif");
1050         // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_MPRIO_TSK,
1051         // PATH_OBJECT+"mprio_tsk.gif");
1052         // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_LPRIO_TSK,
1053         // PATH_OBJECT+"lprio_tsk.gif");
1054
1055         declareWorkbenchImage(ideBundle, IDE.SharedImages.IMG_OBJS_TASK_TSK,
1056                 PATH_OBJECT + "taskmrk_tsk.gif", true); //$NON-NLS-1$
1057         declareWorkbenchImage(ideBundle, IDE.SharedImages.IMG_OBJS_BKMRK_TSK,
1058                 PATH_OBJECT + "bkmrk_tsk.gif", true); //$NON-NLS-1$
1059
1060         declareWorkbenchImage(ideBundle,
1061                 IDEInternalWorkbenchImages.IMG_OBJS_COMPLETE_TSK, PATH_OBJECT
1062                 + "complete_tsk.gif", true); //$NON-NLS-1$
1063         declareWorkbenchImage(ideBundle,
1064                 IDEInternalWorkbenchImages.IMG_OBJS_INCOMPLETE_TSK, PATH_OBJECT
1065                 + "incomplete_tsk.gif", true); //$NON-NLS-1$
1066         declareWorkbenchImage(ideBundle,
1067                 IDEInternalWorkbenchImages.IMG_OBJS_WELCOME_ITEM, PATH_OBJECT
1068                 + "welcome_item.gif", true); //$NON-NLS-1$
1069         declareWorkbenchImage(ideBundle,
1070                 IDEInternalWorkbenchImages.IMG_OBJS_WELCOME_BANNER, PATH_OBJECT
1071                 + "welcome_banner.gif", true); //$NON-NLS-1$
1072         declareWorkbenchImage(ideBundle,
1073                 IDEInternalWorkbenchImages.IMG_OBJS_ERROR_PATH, PATH_OBJECT
1074                 + "error_tsk.gif", true); //$NON-NLS-1$
1075         declareWorkbenchImage(ideBundle,
1076                 IDEInternalWorkbenchImages.IMG_OBJS_WARNING_PATH, PATH_OBJECT
1077                 + "warn_tsk.gif", true); //$NON-NLS-1$
1078         declareWorkbenchImage(ideBundle,
1079                 IDEInternalWorkbenchImages.IMG_OBJS_INFO_PATH, PATH_OBJECT
1080                 + "info_tsk.gif", true); //$NON-NLS-1$
1081
1082         declareWorkbenchImage(ideBundle,
1083                 IDEInternalWorkbenchImages.IMG_LCL_FLAT_LAYOUT, PATH_ELOCALTOOL
1084                 + "flatLayout.gif", true); //$NON-NLS-1$
1085         declareWorkbenchImage(ideBundle,
1086                 IDEInternalWorkbenchImages.IMG_LCL_HIERARCHICAL_LAYOUT,
1087                 PATH_ELOCALTOOL + "hierarchicalLayout.gif", true); //$NON-NLS-1$
1088         declareWorkbenchImage(ideBundle,
1089                 IDEInternalWorkbenchImages.IMG_ETOOL_PROBLEM_CATEGORY,
1090                 PATH_ETOOL + "problem_category.gif", true); //$NON-NLS-1$
1091         /*
1092         declareWorkbenchImage(ideBundle,
1093                 IDEInternalWorkbenchImages.IMG_LCL_LINKTO_HELP, PATH_ELOCALTOOL
1094                         + "linkto_help.gif", false); //$NON-NLS-1$
1095          */
1096
1097         // synchronization indicator objects
1098         // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_WBET_STAT,
1099         // PATH_OVERLAY+"wbet_stat.gif");
1100         // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_SBET_STAT,
1101         // PATH_OVERLAY+"sbet_stat.gif");
1102         // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_CONFLICT_STAT,
1103         // PATH_OVERLAY+"conflict_stat.gif");
1104
1105         // content locality indicator objects
1106         // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_NOTLOCAL_STAT,
1107         // PATH_STAT+"notlocal_stat.gif");
1108         // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_LOCAL_STAT,
1109         // PATH_STAT+"local_stat.gif");
1110         // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_FILLLOCAL_STAT,
1111         // PATH_STAT+"filllocal_stat.gif");
1112     }
1113
1114     /**
1115      * Declares an IDE-specific workbench image.
1116      *
1117      * @param symbolicName
1118      *            the symbolic name of the image
1119      * @param path
1120      *            the path of the image file; this path is relative to the base
1121      *            of the IDE plug-in
1122      * @param shared
1123      *            <code>true</code> if this is a shared image, and
1124      *            <code>false</code> if this is not a shared image
1125      * @see IWorkbenchConfigurer#declareImage
1126      */
1127     private void declareWorkbenchImage(Bundle ideBundle, String symbolicName,
1128             String path, boolean shared) {
1129         URL url = FileLocator.find(ideBundle, new Path(path), null);
1130         ImageDescriptor desc = ImageDescriptor.createFromURL(url);
1131         getWorkbenchConfigurer().declareImage(symbolicName, desc, shared);
1132     }
1133
1134     /*
1135      * (non-Javadoc)
1136      *
1137      * @see org.eclipse.ui.application.WorkbenchAdvisor#getMainPreferencePageId
1138      */
1139     @Override
1140     public String getMainPreferencePageId() {
1141         // indicate that we want the Workench preference page to be prominent
1142         return WORKBENCH_PREFERENCE_CATEGORY_ID;
1143     }
1144
1145     /**
1146      * @return the workspace location string, or <code>null</code> if the
1147      *         location is not being shown
1148      */
1149     public String getWorkspaceLocation() {
1150                 // read command line, which has priority
1151                 IEclipseContext context = getWorkbenchConfigurer().getWorkbench().getService(IEclipseContext.class);
1152                 String location = context != null ? (String) context.get(E4Workbench.FORCED_SHOW_LOCATION) : null;
1153                 if (location != null) {
1154                         return location;
1155                 }
1156                 // read the preference
1157                 if (IDEWorkbenchPlugin.getDefault().getPreferenceStore().getBoolean(IDEInternalPreferences.SHOW_LOCATION)) {
1158                         return Platform.getLocation().toOSString();
1159                 }
1160                 return null;
1161     }
1162
1163     /**
1164      * @return the welcome perspective infos, or <code>null</code> if none or
1165      *         if they should be ignored due to the new intro being present
1166      */
1167     public AboutInfo[] getWelcomePerspectiveInfos() {
1168         if (welcomePerspectiveInfos == null) {
1169             // support old welcome perspectives if intro plugin is not present
1170             if (!hasIntro()) {
1171                 Map<String, AboutInfo> m = getNewlyAddedBundleGroups();
1172                 ArrayList<AboutInfo> list = new ArrayList<AboutInfo>(m.size());
1173                 for (Iterator<AboutInfo> i = m.values().iterator(); i.hasNext();) {
1174                     AboutInfo info = i.next();
1175                     if (info != null && info.getWelcomePerspectiveId() != null
1176                             && info.getWelcomePageURL() != null) {
1177                         list.add(info);
1178                     }
1179                 }
1180                 welcomePerspectiveInfos = new AboutInfo[list.size()];
1181                 list.toArray(welcomePerspectiveInfos);
1182             }
1183         }
1184         return welcomePerspectiveInfos;
1185     }
1186
1187     /*
1188      * (non-Javadoc)
1189      *
1190      * @see org.eclipse.ui.application.WorkbenchAdvisor#getWorkbenchErrorHandler()
1191      */
1192     @Override
1193     public AbstractStatusHandler getWorkbenchErrorHandler() {
1194         if (ideWorkbenchErrorHandler == null) {
1195             ideWorkbenchErrorHandler = new IDEWorkbenchErrorHandler(
1196                     getWorkbenchConfigurer());
1197         }
1198         return ideWorkbenchErrorHandler;
1199     }
1200
1201     /* (non-Javadoc)
1202      * @see org.eclipse.ui.application.WorkbenchAdvisor#eventLoopIdle(org.eclipse.swt.widgets.Display)
1203      */
1204     @Override
1205     public void eventLoopIdle(Display display) {
1206         if (delayedEventsProcessor != null)
1207             delayedEventsProcessor.catchUp(display);
1208         super.eventLoopIdle(display);
1209     }
1210
1211 }