1 /*******************************************************************************
2 * Copyright (c) 2007, 2010 Association for Decentralized Information Management
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
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.workbench.internal;
14 import java.io.IOException;
15 import java.lang.reflect.InvocationTargetException;
17 import java.text.Collator;
18 import java.util.ArrayList;
19 import java.util.Iterator;
21 import java.util.TreeMap;
23 import org.eclipse.core.internal.resources.Workspace;
24 import org.eclipse.core.net.proxy.IProxyService;
25 import org.eclipse.core.resources.IContainer;
26 import org.eclipse.core.resources.IResource;
27 import org.eclipse.core.resources.ResourcesPlugin;
28 import org.eclipse.core.resources.WorkspaceJob;
29 import org.eclipse.core.runtime.CoreException;
30 import org.eclipse.core.runtime.FileLocator;
31 import org.eclipse.core.runtime.IAdaptable;
32 import org.eclipse.core.runtime.IBundleGroup;
33 import org.eclipse.core.runtime.IBundleGroupProvider;
34 import org.eclipse.core.runtime.ILog;
35 import org.eclipse.core.runtime.IProgressMonitor;
36 import org.eclipse.core.runtime.IStatus;
37 import org.eclipse.core.runtime.MultiStatus;
38 import org.eclipse.core.runtime.Path;
39 import org.eclipse.core.runtime.Platform;
40 import org.eclipse.core.runtime.ProgressMonitorWrapper;
41 import org.eclipse.core.runtime.Status;
42 import org.eclipse.core.runtime.SubMonitor;
43 import org.eclipse.core.runtime.jobs.Job;
44 import org.eclipse.e4.core.contexts.IEclipseContext;
45 import org.eclipse.e4.ui.internal.workbench.E4Workbench;
46 import org.eclipse.jface.dialogs.ErrorDialog;
47 import org.eclipse.jface.dialogs.IDialogSettings;
48 import org.eclipse.jface.dialogs.MessageDialog;
49 import org.eclipse.jface.dialogs.TrayDialog;
50 import org.eclipse.jface.operation.IRunnableWithProgress;
51 import org.eclipse.jface.preference.IPreferenceStore;
52 import org.eclipse.jface.resource.ImageDescriptor;
53 import org.eclipse.jface.util.Policy;
54 import org.eclipse.jface.window.Window;
55 import org.eclipse.swt.SWT;
56 import org.eclipse.swt.events.SelectionAdapter;
57 import org.eclipse.swt.events.SelectionEvent;
58 import org.eclipse.swt.widgets.Composite;
59 import org.eclipse.swt.widgets.Display;
60 import org.eclipse.swt.widgets.Event;
61 import org.eclipse.swt.widgets.Listener;
62 import org.eclipse.swt.widgets.Shell;
63 import org.eclipse.ui.IPerspectiveDescriptor;
64 import org.eclipse.ui.PlatformUI;
65 import org.eclipse.ui.application.IWorkbenchConfigurer;
66 import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
67 import org.eclipse.ui.application.WorkbenchAdvisor;
68 import org.eclipse.ui.application.WorkbenchWindowAdvisor;
69 import org.eclipse.ui.ide.IDE;
70 import org.eclipse.ui.internal.ISelectionConversionService;
71 import org.eclipse.ui.internal.Workbench;
72 import org.eclipse.ui.internal.ide.AboutInfo;
73 import org.eclipse.ui.internal.ide.IDEInternalPreferences;
74 import org.eclipse.ui.internal.ide.IDEInternalWorkbenchImages;
75 import org.eclipse.ui.internal.ide.IDESelectionConversionService;
76 import org.eclipse.ui.internal.ide.IDEWorkbenchActivityHelper;
77 import org.eclipse.ui.internal.ide.IDEWorkbenchErrorHandler;
78 import org.eclipse.ui.internal.ide.IDEWorkbenchMessages;
79 import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin;
80 import org.eclipse.ui.internal.ide.undo.WorkspaceUndoMonitor;
81 import org.eclipse.ui.internal.progress.ProgressMonitorJobsDialog;
82 import org.eclipse.ui.keys.IBindingService;
83 import org.eclipse.ui.progress.IProgressService;
84 import org.eclipse.ui.statushandlers.AbstractStatusHandler;
85 import org.osgi.framework.Bundle;
86 import org.osgi.framework.ServiceReference;
87 import org.osgi.framework.Version;
88 import org.simantics.CancelStartupException;
89 import org.simantics.PlatformException;
90 import org.simantics.Simantics;
91 import org.simantics.SimanticsPlatform;
92 import org.simantics.SimanticsPlatform.OntologyRecoveryPolicy;
93 import org.simantics.SimanticsPlatform.RecoveryPolicy;
94 import org.simantics.application.arguments.IArguments;
95 import org.simantics.application.arguments.SimanticsArguments;
96 import org.simantics.db.common.Indexing;
97 import org.simantics.db.indexing.DatabaseIndexing;
98 import org.simantics.db.procore.server.environment.RebootRequiredException;
99 import org.simantics.db.procore.server.environment.windows.Product;
100 import org.simantics.internal.TimedSessionCache;
101 import org.simantics.project.IProject;
102 import org.simantics.project.ProjectKeys;
103 import org.simantics.ui.SimanticsUI;
104 import org.simantics.ui.jobs.SessionGarbageCollectorJob;
105 import org.simantics.ui.workbench.PerspectiveBarsActivator;
106 import org.simantics.ui.workbench.PerspectiveContextActivator;
107 import org.simantics.utils.logging.TimeLogger;
108 import org.simantics.utils.threads.ThreadUtils;
109 import org.simantics.utils.ui.dialogs.ShowError;
110 import org.simantics.utils.ui.dialogs.ShowMessage;
111 import org.slf4j.Logger;
112 import org.slf4j.LoggerFactory;
116 * @author Tuukka Lehtonen
118 public class SimanticsWorkbenchAdvisor extends WorkbenchAdvisor {
120 private static final Logger LOGGER = LoggerFactory.getLogger(SimanticsWorkbenchAdvisor.class);
122 private static final boolean PROFILE_PLATFORM_STARTUP = false;
124 private static final String SHUT_DOWN_TASK = "Shutting down...";
126 private static final String SHUT_DOWN_PLATFORM_TASK = "Shutting down platform...";
128 private static final String WORKBENCH_PREFERENCE_CATEGORY_ID = "org.eclipse.ui.preferencePages.Workbench"; //$NON-NLS-1$
131 * The dialog setting key to access the known installed features since the
132 * last time the workbench was run.
134 private static final String INSTALLED_FEATURES = "installedFeatures"; //$NON-NLS-1$
137 * The arguments received by the application.
139 protected final IArguments args;
141 protected final boolean restoredPreviousSession = false;
144 * Only true while opening the initial windows during {@link #openWindows()}.
145 * Used by {@link SimanticsWorkbenchWindowAdvisor#postWindowOpen()} to
146 * recognize when to skip all one-time initialization.
148 protected boolean workbenchWindowsInitialized = false;
151 * Whether or not to save unsaved database changes before exiting the
154 protected boolean saveAtExit = false;
157 * Ordered map of versioned feature ids -> info that are new for this
158 * session; <code>null</code> if uninitialized. Key type:
159 * <code>String</code>, Value type: <code>AboutInfo</code>.
161 private Map<String, AboutInfo> newlyAddedBundleGroups;
164 * Array of <code>AboutInfo</code> for all new installed features that
165 * specify a welcome perspective.
167 private AboutInfo[] welcomePerspectiveInfos = null;
170 * Helper for managing activites in response to workspace changes.
172 private IDEWorkbenchActivityHelper activityHelper = null;
175 * Helper for managing work that is performed when the system is otherwise
178 private IDEIdleHelper idleHelper;
180 private Listener settingsChangeListener;
183 * Support class for monitoring workspace changes and periodically
184 * validating the undo history
186 private WorkspaceUndoMonitor workspaceUndoMonitor;
189 * The IDE workbench error handler.
191 private AbstractStatusHandler ideWorkbenchErrorHandler;
194 * Helper class used to process delayed events.
196 private DelayedEventsProcessor delayedEventsProcessor;
199 * Creates a new workbench advisor instance.
202 public SimanticsWorkbenchAdvisor(IArguments args, DelayedEventsProcessor processor) {
205 this.delayedEventsProcessor = processor;
207 Listener closeListener = new Listener() {
208 public void handleEvent(Event event) {
209 boolean doExit = SimanticsWorkbenchWindowAdvisor.promptOnExit(null);
212 event.type = SWT.None;
215 Display.getDefault().addListener(SWT.Close, closeListener);
218 public IArguments getArguments() {
222 public boolean workbenchInitialized() {
223 return workbenchWindowsInitialized;
226 public boolean restoredPreviousSession() {
227 return restoredPreviousSession;
230 boolean saveAtExit() {
234 void setSaveAtExit(boolean saveAtExit) {
235 this.saveAtExit = saveAtExit;
241 * @see org.eclipse.ui.application.WorkbenchAdvisor#initialize
244 public void initialize(IWorkbenchConfigurer configurer) {
245 // By default, we always save and restore the workbench state.
246 configurer.setSaveAndRestore(true);
248 checkWorkspaceDatabaseIndexes();
250 // Start tracking the active perspective to activate contexts based on it.
251 new PerspectiveContextActivator();
252 new PerspectiveBarsActivator();
254 // register workspace adapters
255 IDE.registerAdapters();
257 // register shared images
258 declareWorkbenchImages();
260 // initialize the activity helper
261 activityHelper = IDEWorkbenchActivityHelper.getInstance();
263 // initialize idle handler
264 idleHelper = new IDEIdleHelper(configurer);
266 // initialize the workspace undo monitor
267 workspaceUndoMonitor = WorkspaceUndoMonitor.getInstance();
269 // show Help button in JFace dialogs
270 TrayDialog.setDialogHelpAvailable(true);
272 Policy.setComparator(Collator.getInstance());
275 private void checkWorkspaceDatabaseIndexes() {
277 DatabaseIndexing.validateIndexes();
278 } catch (IOException e) {
279 Activator.logError("Problems encountered while checking database indexes, see exception for details.", e);
283 public WorkbenchWindowAdvisor createWorkbenchWindowAdvisorClass(SimanticsWorkbenchAdvisor advisor, IWorkbenchWindowConfigurer configurer) {
284 return new SimanticsWorkbenchWindowAdvisor(this, configurer);
288 public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) {
289 // Attach database session watchdog.
290 new SessionWatchdog().attach( Simantics.getSessionContextProvider() );
292 return createWorkbenchWindowAdvisorClass(this, configurer);
296 * For gaining direct access to super.openWindows() in implementations
297 * inheriting this one.
299 public boolean openWindowsSuper() {
300 return super.openWindows();
304 * Sadly we do not know why key bindings are lost and why this helps. But it
305 * does. Visiting the <code>Keys</code> preference page and pressing OK uses
306 * this the same call and it seems to salvage the bindings that have been in
307 * some cases destroyed by <code>BindingToModelProcessor</code>.
311 * https://techblog.ralph-schuster.eu/2013/10/13/eclipsee4-problem-with-key-bindings/comment-page-1/
312 * https://www.eclipse.org/forums/index.php/t/550175/
313 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=461037
315 * @see platform issue #6353
317 private void fixBindings() {
319 IBindingService bs = PlatformUI.getWorkbench().getAdapter(IBindingService.class);
320 bs.savePreferences(bs.getActiveScheme(), bs.getBindings());
321 } catch (IOException e) {
322 Activator.logError(getClass().getSimpleName() + ".fixBindings failed", e);
327 public boolean openWindows() {
328 boolean platformOk = startPlatform();
329 LOGGER.info("startPlatform finished");
330 TimeLogger.log("SimanticsWorkbenchAdvisor.startPlatform finished");
333 // At this point workbenchConfigurer.getSaveAndRestore()
334 // returns false iff something has gone terribly wrong
335 // before this. Currently saveAndRestore is always true.
336 boolean windowsOpened = super.openWindows();
337 TimeLogger.log("Opened windows");
339 workbenchWindowsInitialized = true;
341 // Start the database garbage collector after a short while.
342 SessionGarbageCollectorJob.getInstance().scheduleAfterQuietTime();
344 // #6353: Workaround for
351 // Make sure platform shutdown is ran if window opening fails.
353 platformShutdownRunnable.run(null);
354 } catch (InvocationTargetException e) {
355 Activator.logError(getClass().getSimpleName() + ".openWindows failed", e.getCause());
356 } catch (InterruptedException e) {
357 Activator.logError(getClass().getSimpleName() + ".openWindows failed", e);
362 protected boolean startPlatform() {
363 // Verify selected perspective
364 if (args.contains(SimanticsArguments.PERSPECTIVE)) {
365 String perspectiveId = args.get(SimanticsArguments.PERSPECTIVE);
366 IPerspectiveDescriptor perspective = PlatformUI.getWorkbench().getPerspectiveRegistry().findPerspectiveWithId(perspectiveId);
367 if (perspective == null) {
368 StringBuilder msg = new StringBuilder();
369 msg.append("Requested perspective not found: '" + perspectiveId + "'\n");
370 msg.append("Valid alternatives are:\n");
371 for (IPerspectiveDescriptor pd : PlatformUI.getWorkbench().getPerspectiveRegistry().getPerspectives()) {
372 msg.append(" " + pd.getId() + "\n");
375 ShowMessage.syncShowError("Invalid Perspective", msg.toString());
380 ILog log = Platform.getLog(Activator.getDefault().getBundle());
385 // Create Simantics Platform Helper.
387 // If Simantics is started from Eclipse IDE or with -fixerrors option,
388 // there is an attempt to fix errors.
390 // On ontology mismatch, there is an attempt to merge new ontology to the
391 // existing database. With -reinstall, the database is cleaned and
396 RecoveryPolicy workspacePolicy = Platform.inDevelopmentMode() ? RecoveryPolicy.FixError : RecoveryPolicy.ThrowError;
397 OntologyRecoveryPolicy ontologyPolicy = Platform.inDevelopmentMode() ? OntologyRecoveryPolicy.Merge : OntologyRecoveryPolicy.ThrowError;
399 if (args.contains(SimanticsArguments.RECOVERY_POLICY_FIX_ERRORS)) {
400 workspacePolicy = RecoveryPolicy.FixError;
401 ontologyPolicy = OntologyRecoveryPolicy.Merge;
404 boolean requireSynchronize = true;
406 if (args.contains(SimanticsArguments.ONTOLOGY_RECOVERY_POLICY_REINSTALL)) {
407 ontologyPolicy = OntologyRecoveryPolicy.ReinstallDatabase;
410 if (args.contains(SimanticsArguments.DO_NOT_SYNCHRONIZE_ONTOLOGIES)) {
411 requireSynchronize = false;
414 if (args.contains(SimanticsArguments.DISABLE_INDEX)) {
415 Indexing.setDefaultDependenciesIndexingEnabled(false);
418 if (args.contains(SimanticsArguments.SERVER)) {
419 String serverAddress = args.get(SimanticsArguments.SERVER);
420 throw new PlatformException("Argument not supported: " + SimanticsArguments.SERVER + " " + serverAddress);
423 String databaseDriverId = Simantics.getDefaultDatabaseDriver();
424 if (args.contains(SimanticsArguments.DATABASE_ID)) {
425 databaseDriverId = args.get(SimanticsArguments.DATABASE_ID);
426 Simantics.setDefaultDatabaseDriver(databaseDriverId);
429 IProgressMonitor mon = null;
430 if (PROFILE_PLATFORM_STARTUP)
431 mon = new TimingProgressMonitor();
432 SimanticsPlatform.INSTANCE.startUp(databaseDriverId, mon, workspacePolicy, ontologyPolicy, requireSynchronize, new JFaceUserAgent());
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");
444 } catch (CancelStartupException e) {
446 } catch (PlatformException e) {
447 boolean hasStackTrace = e.getStackTrace().length > 0;
449 while (ee.getCause() != null) {
451 hasStackTrace = ee.getStackTrace().length > 0;
454 log.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), hasStackTrace ? e : null));
456 new ShowError("Platform Initialization Failed", "Simantics Platform initialization failed:\n\n" + e.getMessage(), e, true);
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);
466 } catch (Exception e) {
467 log.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e));
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());
479 new ShowError("Platform Startup Failed", "Simantics Platform startup failed:\n\n" + e.getMessage(), e, true);
489 * @see org.eclipse.ui.application.WorkbenchAdvisor#preStartup()
492 public void preStartup() {
494 // Suspend background jobs while we startup
495 Job.getJobManager().suspend();
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);
511 * @see org.eclipse.ui.application.WorkbenchAdvisor#postStartup()
514 public void postStartup() {
517 activateProxyService();
518 ((Workbench) PlatformUI.getWorkbench()).registerService(
519 ISelectionConversionService.class,
520 new IDESelectionConversionService());
522 initializeSettingsChangeListener();
523 Display.getCurrent().addListener(SWT.Settings,
524 settingsChangeListener);
525 } finally {// Resume background jobs after we startup
526 Job.getJobManager().resume();
531 * Activate the proxy service by obtaining it.
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());
539 proxyService = bundle.getBundleContext().getService(ref);
541 if (proxyService == null) {
542 IDEWorkbenchPlugin.log("Proxy service could not be found."); //$NON-NLS-1$
547 * Initialize the listener for settings changes.
549 private void initializeSettingsChangeListener() {
550 settingsChangeListener = new Listener() {
552 boolean currentHighContrast = Display.getCurrent()
556 public void handleEvent(org.eclipse.swt.widgets.Event event) {
557 if (Display.getCurrent().getHighContrast() == currentHighContrast)
560 currentHighContrast = !currentHighContrast;
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();
580 * @see org.eclipse.ui.application.WorkbenchAdvisor#postShutdown
583 public void postShutdown() {
584 if (activityHelper != null) {
585 activityHelper.shutdown();
586 activityHelper = null;
588 if (idleHelper != null) {
589 idleHelper.shutdown();
592 if (workspaceUndoMonitor != null) {
593 workspaceUndoMonitor.shutdown();
594 workspaceUndoMonitor = null;
596 if (IDEWorkbenchPlugin.getPluginWorkspace() != null) {
597 disconnectFromWorkspace();
604 * @see org.eclipse.ui.application.WorkbenchAdvisor#preShutdown()
607 public boolean preShutdown() {
608 Display.getCurrent().removeListener(SWT.Settings,
609 settingsChangeListener);
610 return super.preShutdown();
614 * Return true if the intro plugin is present and false otherwise.
618 public boolean hasIntro() {
619 return getWorkbenchConfigurer().getWorkbench().getIntroManager()
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);
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$
640 final IContainer root = ResourcesPlugin.getWorkspace().getRoot();
641 Job job = new WorkspaceJob(IDEWorkbenchMessages.Workspace_refreshing) {
643 public IStatus runInWorkspace(IProgressMonitor monitor)
644 throws CoreException {
645 root.refreshLocal(IResource.DEPTH_INFINITE, monitor);
646 return Status.OK_STATUS;
653 private static class CancelableProgressMonitorWrapper extends ProgressMonitorWrapper {
654 private double total = 0;
655 private ProgressMonitorJobsDialog dialog;
657 CancelableProgressMonitorWrapper(IProgressMonitor monitor,
658 ProgressMonitorJobsDialog dialog) {
660 this.dialog = dialog;
665 * @see org.eclipse.core.runtime.ProgressMonitorWrapper#internalWorked(double)
667 public void internalWorked(double work) {
668 super.internalWorked(work);
670 updateProgressDetails();
675 * @see org.eclipse.core.runtime.ProgressMonitorWrapper#worked(int)
677 public void worked(int work) {
680 updateProgressDetails();
683 public void beginTask(String name, int totalWork) {
684 super.beginTask(name, totalWork);
685 subTask(IDEWorkbenchMessages.IDEWorkbenchAdvisor_preHistoryCompaction);
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);
693 if (Math.abs(total - 5.0) < 0.0001 /* history compacting finished */) {
694 subTask(IDEWorkbenchMessages.IDEWorkbenchAdvisor_postHistoryCompaction);
695 dialog.setCancelable(false);
700 private static class CancelableProgressMonitorJobsDialog extends ProgressMonitorJobsDialog {
702 public CancelableProgressMonitorJobsDialog(Shell parent) {
708 * @see org.eclipse.ui.internal.progress.ProgressMonitorJobsDialog#createDetailsButton(org.eclipse.swt.widgets.Composite)
710 protected void createButtonsForButtonBar(Composite parent) {
711 super.createButtonsForButtonBar(parent);
712 registerCancelButtonListener();
715 public void registerCancelButtonListener() {
716 cancel.addSelectionListener(new SelectionAdapter() {
717 public void widgetSelected(SelectionEvent e) {
718 subTaskLabel.setText(""); //$NON-NLS-1$
725 final IRunnableWithProgress platformShutdownRunnable = new IRunnableWithProgress() {
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.
733 public void run(IProgressMonitor monitor) {
734 SubMonitor progress = SubMonitor.convert(monitor, SHUT_DOWN_PLATFORM_TASK, 100);
737 progress.subTask("Platform");
738 SimanticsPlatform.INSTANCE.shutdown(progress.newChild(50));
739 } catch (PlatformException e) {
740 Activator.logError("Problems encountered while shutting down Simantics platform, see exception for details.", e);
743 progress.subTask("Remaining database connections");
744 SimanticsUI.closeSessions();
746 TimedSessionCache.close();
749 progress.subTask("Thread pools");
750 ThreadUtils.shutdown();
753 progress.subTask("Clear index status");
755 // Everything ok, clear index dirty state.
756 DatabaseIndexing.clearAllDirty();
757 } catch (IOException e) {
758 Activator.logError("Problems encountered while refreshing database index states, see exception for details.", e);
762 progress.setWorkRemaining(0);
764 if (monitor != null) {
772 * Disconnect from the workspace and close ProCore sessions.
774 private void disconnectFromWorkspace() {
775 // save the workspace
776 final MultiStatus status = new MultiStatus(
777 IDEWorkbenchPlugin.IDE_WORKBENCH, 1,
778 IDEWorkbenchMessages.ProblemSavingWorkbench, null);
780 final ProgressMonitorJobsDialog p = new CancelableProgressMonitorJobsDialog(
783 final boolean applyPolicy = ResourcesPlugin.getWorkspace()
784 .getDescription().isApplyFileStatePolicy();
786 final IRunnableWithProgress workspaceShutdownRunnable = new IRunnableWithProgress() {
788 public void run(IProgressMonitor monitor) {
790 status.merge(((Workspace) ResourcesPlugin.getWorkspace()).save(true, true, monitor));
791 } catch (CoreException e) {
792 status.merge(e.getStatus());
797 IRunnableWithProgress shutdownRunnable = new IRunnableWithProgress() {
799 public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
801 monitor = new CancelableProgressMonitorWrapper(
804 SubMonitor progress = SubMonitor.convert(monitor, SHUT_DOWN_TASK, 2);
806 workspaceShutdownRunnable.run(progress.newChild(1, SubMonitor.SUPPRESS_NONE));
807 platformShutdownRunnable.run(progress.newChild(1, SubMonitor.SUPPRESS_NONE));
815 new ProgressMonitorJobsDialog(null).run(true, false, shutdownRunnable);
816 } catch (InvocationTargetException e) {
817 status.merge(new Status(IStatus.ERROR,
818 IDEWorkbenchPlugin.IDE_WORKBENCH, 1,
819 IDEWorkbenchMessages.InternalError, e.getTargetException()));
820 } catch (InterruptedException e) {
821 status.merge(new Status(IStatus.ERROR,
822 IDEWorkbenchPlugin.IDE_WORKBENCH, 1,
823 IDEWorkbenchMessages.InternalError, e));
825 ErrorDialog.openError(null,
826 IDEWorkbenchMessages.ProblemsSavingWorkspace, null, status,
827 IStatus.ERROR | IStatus.WARNING);
828 if (!status.isOK()) {
829 IDEWorkbenchPlugin.log(
830 IDEWorkbenchMessages.ProblemsSavingWorkspace, status);
837 * @see org.eclipse.ui.application.WorkbenchAdvisor#getDefaultPageInput
840 public IAdaptable getDefaultPageInput() {
841 return ResourcesPlugin.getWorkspace().getRoot();
847 * @see org.eclipse.ui.application.WorkbenchAdvisor
850 public String getInitialWindowPerspectiveId() {
851 int index = PlatformUI.getWorkbench().getWorkbenchWindowCount() - 1;
853 String perspectiveId = null;
854 AboutInfo[] welcomeInfos = getWelcomePerspectiveInfos();
855 if (index >= 0 && welcomeInfos != null && index < welcomeInfos.length) {
856 perspectiveId = welcomeInfos[index].getWelcomePerspectiveId();
859 if (perspectiveId == null && args.contains(SimanticsArguments.PERSPECTIVE)) {
860 String id = args.get(SimanticsArguments.PERSPECTIVE);
861 IPerspectiveDescriptor perspective = PlatformUI.getWorkbench().getPerspectiveRegistry().findPerspectiveWithId(id);
862 if (perspective != null)
866 if (perspectiveId == null) {
867 IProject project = SimanticsUI.peekProject();
869 perspectiveId = project.getHint(ProjectKeys.DEFAULT_PERSPECTIVE);
872 //System.out.println("Initial perspective: " + perspectiveId);
874 return perspectiveId;
878 * Returns the map of versioned feature ids -> info object for all installed
879 * features. The format of the versioned feature id (the key of the map) is
880 * featureId + ":" + versionId.
882 * @return map of versioned feature ids -> info object (key type:
883 * <code>String</code>, value type: <code>AboutInfo</code>)
886 private Map<String, AboutInfo> computeBundleGroupMap() {
887 // use tree map to get predicable order
888 Map<String, AboutInfo> ids = new TreeMap<String, AboutInfo>();
890 IBundleGroupProvider[] providers = Platform.getBundleGroupProviders();
891 for (int i = 0; i < providers.length; ++i) {
892 IBundleGroup[] groups = providers[i].getBundleGroups();
893 for (int j = 0; j < groups.length; ++j) {
894 IBundleGroup group = groups[j];
895 AboutInfo info = new AboutInfo(group);
897 String version = info.getVersionId();
898 version = version == null ? "0.0.0" //$NON-NLS-1$
899 : new Version(version).toString();
900 String versionedFeature = group.getIdentifier() + ":" + version; //$NON-NLS-1$
902 ids.put(versionedFeature, info);
910 * Returns the ordered map of versioned feature ids -> AboutInfo that are
911 * new for this session.
913 * @return ordered map of versioned feature ids (key type:
914 * <code>String</code>) -> infos (value type:
915 * <code>AboutInfo</code>).
917 public Map<String, AboutInfo> getNewlyAddedBundleGroups() {
918 if (newlyAddedBundleGroups == null) {
919 newlyAddedBundleGroups = createNewBundleGroupsMap();
921 return newlyAddedBundleGroups;
925 * Updates the old features setting and returns a map of new features.
927 private Map<String, AboutInfo> createNewBundleGroupsMap() {
928 // retrieve list of installed bundle groups from last session
929 IDialogSettings settings = IDEWorkbenchPlugin.getDefault()
930 .getDialogSettings();
931 String[] previousFeaturesArray = settings.getArray(INSTALLED_FEATURES);
933 // get a map of currently installed bundle groups and store it for next
935 Map<String, AboutInfo> bundleGroups = computeBundleGroupMap();
936 String[] currentFeaturesArray = new String[bundleGroups.size()];
937 bundleGroups.keySet().toArray(currentFeaturesArray);
938 settings.put(INSTALLED_FEATURES, currentFeaturesArray);
940 // remove the previously known from the current set
941 if (previousFeaturesArray != null) {
942 for (int i = 0; i < previousFeaturesArray.length; ++i) {
943 bundleGroups.remove(previousFeaturesArray[i]);
951 * Declares all IDE-specific workbench images. This includes both "shared"
952 * images (named in {@link IDE.SharedImages}) and internal images (named in
953 * {@link org.eclipse.ui.internal.ide.IDEInternalWorkbenchImages}).
955 * @see IWorkbenchConfigurer#declareImage
957 private void declareWorkbenchImages() {
959 final String ICONS_PATH = "$nl$/icons/full/";//$NON-NLS-1$
960 final String PATH_ELOCALTOOL = ICONS_PATH + "elcl16/"; // Enabled //$NON-NLS-1$
964 final String PATH_DLOCALTOOL = ICONS_PATH + "dlcl16/"; // Disabled //$NON-NLS-1$
968 final String PATH_ETOOL = ICONS_PATH + "etool16/"; // Enabled toolbar //$NON-NLS-1$
971 final String PATH_DTOOL = ICONS_PATH + "dtool16/"; // Disabled toolbar //$NON-NLS-1$
974 final String PATH_OBJECT = ICONS_PATH + "obj16/"; // Model object //$NON-NLS-1$
977 final String PATH_WIZBAN = ICONS_PATH + "wizban/"; // Wizard //$NON-NLS-1$
981 Bundle ideBundle = Platform.getBundle(IDEWorkbenchPlugin.IDE_WORKBENCH);
983 declareWorkbenchImage(ideBundle,
984 IDEInternalWorkbenchImages.IMG_ETOOL_BUILD_EXEC, PATH_ETOOL
985 + "build_exec.gif", false); //$NON-NLS-1$
986 declareWorkbenchImage(ideBundle,
987 IDEInternalWorkbenchImages.IMG_ETOOL_BUILD_EXEC_HOVER,
988 PATH_ETOOL + "build_exec.gif", false); //$NON-NLS-1$
989 declareWorkbenchImage(ideBundle,
990 IDEInternalWorkbenchImages.IMG_ETOOL_BUILD_EXEC_DISABLED,
991 PATH_DTOOL + "build_exec.gif", false); //$NON-NLS-1$
993 declareWorkbenchImage(ideBundle,
994 IDEInternalWorkbenchImages.IMG_ETOOL_SEARCH_SRC, PATH_ETOOL
995 + "search_src.gif", false); //$NON-NLS-1$
996 declareWorkbenchImage(ideBundle,
997 IDEInternalWorkbenchImages.IMG_ETOOL_SEARCH_SRC_HOVER,
998 PATH_ETOOL + "search_src.gif", false); //$NON-NLS-1$
999 declareWorkbenchImage(ideBundle,
1000 IDEInternalWorkbenchImages.IMG_ETOOL_SEARCH_SRC_DISABLED,
1001 PATH_DTOOL + "search_src.gif", false); //$NON-NLS-1$
1003 declareWorkbenchImage(ideBundle,
1004 IDEInternalWorkbenchImages.IMG_ETOOL_NEXT_NAV, PATH_ETOOL
1005 + "next_nav.gif", false); //$NON-NLS-1$
1007 declareWorkbenchImage(ideBundle,
1008 IDEInternalWorkbenchImages.IMG_ETOOL_PREVIOUS_NAV, PATH_ETOOL
1009 + "prev_nav.gif", false); //$NON-NLS-1$
1011 declareWorkbenchImage(ideBundle,
1012 IDEInternalWorkbenchImages.IMG_WIZBAN_NEWPRJ_WIZ, PATH_WIZBAN
1013 + "newprj_wiz.png", false); //$NON-NLS-1$
1014 declareWorkbenchImage(ideBundle,
1015 IDEInternalWorkbenchImages.IMG_WIZBAN_NEWFOLDER_WIZ,
1016 PATH_WIZBAN + "newfolder_wiz.png", false); //$NON-NLS-1$
1017 declareWorkbenchImage(ideBundle,
1018 IDEInternalWorkbenchImages.IMG_WIZBAN_NEWFILE_WIZ, PATH_WIZBAN
1019 + "newfile_wiz.png", false); //$NON-NLS-1$
1021 declareWorkbenchImage(ideBundle,
1022 IDEInternalWorkbenchImages.IMG_WIZBAN_IMPORTDIR_WIZ,
1023 PATH_WIZBAN + "importdir_wiz.png", false); //$NON-NLS-1$
1024 declareWorkbenchImage(ideBundle,
1025 IDEInternalWorkbenchImages.IMG_WIZBAN_IMPORTZIP_WIZ,
1026 PATH_WIZBAN + "importzip_wiz.png", false); //$NON-NLS-1$
1028 declareWorkbenchImage(ideBundle,
1029 IDEInternalWorkbenchImages.IMG_WIZBAN_EXPORTDIR_WIZ,
1030 PATH_WIZBAN + "exportdir_wiz.png", false); //$NON-NLS-1$
1031 declareWorkbenchImage(ideBundle,
1032 IDEInternalWorkbenchImages.IMG_WIZBAN_EXPORTZIP_WIZ,
1033 PATH_WIZBAN + "exportzip_wiz.png", false); //$NON-NLS-1$
1035 declareWorkbenchImage(ideBundle,
1036 IDEInternalWorkbenchImages.IMG_WIZBAN_RESOURCEWORKINGSET_WIZ,
1037 PATH_WIZBAN + "workset_wiz.png", false); //$NON-NLS-1$
1039 declareWorkbenchImage(ideBundle,
1040 IDEInternalWorkbenchImages.IMG_DLGBAN_SAVEAS_DLG, PATH_WIZBAN
1041 + "saveas_wiz.png", false); //$NON-NLS-1$
1043 declareWorkbenchImage(ideBundle,
1044 IDEInternalWorkbenchImages.IMG_DLGBAN_QUICKFIX_DLG, PATH_WIZBAN
1045 + "quick_fix.png", false); //$NON-NLS-1$
1047 declareWorkbenchImage(ideBundle, IDE.SharedImages.IMG_OBJ_PROJECT,
1048 PATH_OBJECT + "prj_obj.gif", true); //$NON-NLS-1$
1049 declareWorkbenchImage(ideBundle,
1050 IDE.SharedImages.IMG_OBJ_PROJECT_CLOSED, PATH_OBJECT
1051 + "cprj_obj.gif", true); //$NON-NLS-1$
1052 declareWorkbenchImage(ideBundle, IDE.SharedImages.IMG_OPEN_MARKER,
1053 PATH_ELOCALTOOL + "gotoobj_tsk.gif", true); //$NON-NLS-1$
1055 declareWorkbenchImage(ideBundle,
1056 IDEInternalWorkbenchImages.IMG_ELCL_QUICK_FIX_ENABLED,
1057 PATH_ELOCALTOOL + "smartmode_co.gif", true); //$NON-NLS-1$
1059 declareWorkbenchImage(ideBundle,
1060 IDEInternalWorkbenchImages.IMG_DLCL_QUICK_FIX_DISABLED,
1061 PATH_DLOCALTOOL + "smartmode_co.gif", true); //$NON-NLS-1$
1064 // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_HPRIO_TSK,
1065 // PATH_OBJECT+"hprio_tsk.gif");
1066 // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_MPRIO_TSK,
1067 // PATH_OBJECT+"mprio_tsk.gif");
1068 // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_LPRIO_TSK,
1069 // PATH_OBJECT+"lprio_tsk.gif");
1071 declareWorkbenchImage(ideBundle, IDE.SharedImages.IMG_OBJS_TASK_TSK,
1072 PATH_OBJECT + "taskmrk_tsk.gif", true); //$NON-NLS-1$
1073 declareWorkbenchImage(ideBundle, IDE.SharedImages.IMG_OBJS_BKMRK_TSK,
1074 PATH_OBJECT + "bkmrk_tsk.gif", true); //$NON-NLS-1$
1076 declareWorkbenchImage(ideBundle,
1077 IDEInternalWorkbenchImages.IMG_OBJS_COMPLETE_TSK, PATH_OBJECT
1078 + "complete_tsk.gif", true); //$NON-NLS-1$
1079 declareWorkbenchImage(ideBundle,
1080 IDEInternalWorkbenchImages.IMG_OBJS_INCOMPLETE_TSK, PATH_OBJECT
1081 + "incomplete_tsk.gif", true); //$NON-NLS-1$
1082 declareWorkbenchImage(ideBundle,
1083 IDEInternalWorkbenchImages.IMG_OBJS_WELCOME_ITEM, PATH_OBJECT
1084 + "welcome_item.gif", true); //$NON-NLS-1$
1085 declareWorkbenchImage(ideBundle,
1086 IDEInternalWorkbenchImages.IMG_OBJS_WELCOME_BANNER, PATH_OBJECT
1087 + "welcome_banner.gif", true); //$NON-NLS-1$
1088 declareWorkbenchImage(ideBundle,
1089 IDEInternalWorkbenchImages.IMG_OBJS_ERROR_PATH, PATH_OBJECT
1090 + "error_tsk.gif", true); //$NON-NLS-1$
1091 declareWorkbenchImage(ideBundle,
1092 IDEInternalWorkbenchImages.IMG_OBJS_WARNING_PATH, PATH_OBJECT
1093 + "warn_tsk.gif", true); //$NON-NLS-1$
1094 declareWorkbenchImage(ideBundle,
1095 IDEInternalWorkbenchImages.IMG_OBJS_INFO_PATH, PATH_OBJECT
1096 + "info_tsk.gif", true); //$NON-NLS-1$
1098 declareWorkbenchImage(ideBundle,
1099 IDEInternalWorkbenchImages.IMG_LCL_FLAT_LAYOUT, PATH_ELOCALTOOL
1100 + "flatLayout.gif", true); //$NON-NLS-1$
1101 declareWorkbenchImage(ideBundle,
1102 IDEInternalWorkbenchImages.IMG_LCL_HIERARCHICAL_LAYOUT,
1103 PATH_ELOCALTOOL + "hierarchicalLayout.gif", true); //$NON-NLS-1$
1104 declareWorkbenchImage(ideBundle,
1105 IDEInternalWorkbenchImages.IMG_ETOOL_PROBLEM_CATEGORY,
1106 PATH_ETOOL + "problem_category.gif", true); //$NON-NLS-1$
1108 declareWorkbenchImage(ideBundle,
1109 IDEInternalWorkbenchImages.IMG_LCL_LINKTO_HELP, PATH_ELOCALTOOL
1110 + "linkto_help.gif", false); //$NON-NLS-1$
1113 // synchronization indicator objects
1114 // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_WBET_STAT,
1115 // PATH_OVERLAY+"wbet_stat.gif");
1116 // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_SBET_STAT,
1117 // PATH_OVERLAY+"sbet_stat.gif");
1118 // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_CONFLICT_STAT,
1119 // PATH_OVERLAY+"conflict_stat.gif");
1121 // content locality indicator objects
1122 // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_NOTLOCAL_STAT,
1123 // PATH_STAT+"notlocal_stat.gif");
1124 // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_LOCAL_STAT,
1125 // PATH_STAT+"local_stat.gif");
1126 // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_FILLLOCAL_STAT,
1127 // PATH_STAT+"filllocal_stat.gif");
1131 * Declares an IDE-specific workbench image.
1133 * @param symbolicName
1134 * the symbolic name of the image
1136 * the path of the image file; this path is relative to the base
1137 * of the IDE plug-in
1139 * <code>true</code> if this is a shared image, and
1140 * <code>false</code> if this is not a shared image
1141 * @see IWorkbenchConfigurer#declareImage
1143 private void declareWorkbenchImage(Bundle ideBundle, String symbolicName,
1144 String path, boolean shared) {
1145 URL url = FileLocator.find(ideBundle, new Path(path), null);
1146 ImageDescriptor desc = ImageDescriptor.createFromURL(url);
1147 getWorkbenchConfigurer().declareImage(symbolicName, desc, shared);
1153 * @see org.eclipse.ui.application.WorkbenchAdvisor#getMainPreferencePageId
1156 public String getMainPreferencePageId() {
1157 // indicate that we want the Workench preference page to be prominent
1158 return WORKBENCH_PREFERENCE_CATEGORY_ID;
1162 * @return the workspace location string, or <code>null</code> if the
1163 * location is not being shown
1165 public String getWorkspaceLocation() {
1166 // read command line, which has priority
1167 IEclipseContext context = getWorkbenchConfigurer().getWorkbench().getService(IEclipseContext.class);
1168 String location = context != null ? (String) context.get(E4Workbench.FORCED_SHOW_LOCATION) : null;
1169 if (location != null) {
1172 // read the preference
1173 if (IDEWorkbenchPlugin.getDefault().getPreferenceStore().getBoolean(IDEInternalPreferences.SHOW_LOCATION)) {
1174 return Platform.getLocation().toOSString();
1180 * @return the welcome perspective infos, or <code>null</code> if none or
1181 * if they should be ignored due to the new intro being present
1183 public AboutInfo[] getWelcomePerspectiveInfos() {
1184 if (welcomePerspectiveInfos == null) {
1185 // support old welcome perspectives if intro plugin is not present
1187 Map<String, AboutInfo> m = getNewlyAddedBundleGroups();
1188 ArrayList<AboutInfo> list = new ArrayList<AboutInfo>(m.size());
1189 for (Iterator<AboutInfo> i = m.values().iterator(); i.hasNext();) {
1190 AboutInfo info = i.next();
1191 if (info != null && info.getWelcomePerspectiveId() != null
1192 && info.getWelcomePageURL() != null) {
1196 welcomePerspectiveInfos = new AboutInfo[list.size()];
1197 list.toArray(welcomePerspectiveInfos);
1200 return welcomePerspectiveInfos;
1206 * @see org.eclipse.ui.application.WorkbenchAdvisor#getWorkbenchErrorHandler()
1209 public AbstractStatusHandler getWorkbenchErrorHandler() {
1210 if (ideWorkbenchErrorHandler == null) {
1211 ideWorkbenchErrorHandler = new IDEWorkbenchErrorHandler(
1212 getWorkbenchConfigurer());
1214 return ideWorkbenchErrorHandler;
1218 * @see org.eclipse.ui.application.WorkbenchAdvisor#eventLoopIdle(org.eclipse.swt.widgets.Display)
1221 public void eventLoopIdle(Display display) {
1222 if (delayedEventsProcessor != null)
1223 delayedEventsProcessor.catchUp(display);
1224 super.eventLoopIdle(display);