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.eclipse.ui.statushandlers.StatusAdapter;
86 import org.osgi.framework.Bundle;
87 import org.osgi.framework.BundleContext;
88 import org.osgi.framework.ServiceReference;
89 import org.osgi.framework.Version;
90 import org.simantics.CancelStartupException;
91 import org.simantics.PlatformException;
92 import org.simantics.Simantics;
93 import org.simantics.SimanticsPlatform;
94 import org.simantics.SimanticsPlatform.OntologyRecoveryPolicy;
95 import org.simantics.SimanticsPlatform.RecoveryPolicy;
96 import org.simantics.TimingProgressMonitor;
97 import org.simantics.UnhandledExceptionService;
98 import org.simantics.application.arguments.IArguments;
99 import org.simantics.application.arguments.SimanticsArguments;
100 import org.simantics.db.common.Indexing;
101 import org.simantics.db.indexing.DatabaseIndexing;
102 import org.simantics.project.IProject;
103 import org.simantics.project.ProjectKeys;
104 import org.simantics.ui.SimanticsUI;
105 import org.simantics.ui.jobs.SessionGarbageCollectorJob;
106 import org.simantics.ui.workbench.PerspectiveBarsActivator;
107 import org.simantics.ui.workbench.PerspectiveContextActivator;
108 import org.simantics.ui.workbench.WorkbenchShutdownService;
109 import org.simantics.utils.logging.TimeLogger;
110 import org.simantics.utils.ui.dialogs.ShowError;
111 import org.simantics.utils.ui.dialogs.ShowMessage;
112 import org.slf4j.Logger;
113 import org.slf4j.LoggerFactory;
117 * @author Tuukka Lehtonen
119 public class SimanticsWorkbenchAdvisor extends WorkbenchAdvisor {
121 private static final Logger LOGGER = LoggerFactory.getLogger(SimanticsWorkbenchAdvisor.class);
123 private static final boolean PROFILE_PLATFORM_STARTUP = false;
125 private static final String SHUT_DOWN_TASK = "Shutting down...";
127 private static final String SHUT_DOWN_PLATFORM_TASK = "Shutting down platform...";
129 private static final String WORKBENCH_PREFERENCE_CATEGORY_ID = "org.eclipse.ui.preferencePages.Workbench"; //$NON-NLS-1$
132 * The dialog setting key to access the known installed features since the
133 * last time the workbench was run.
135 private static final String INSTALLED_FEATURES = "installedFeatures"; //$NON-NLS-1$
138 * The arguments received by the application.
140 protected final IArguments args;
142 protected final boolean restoredPreviousSession = false;
145 * Only true while opening the initial windows during {@link #openWindows()}.
146 * Used by {@link SimanticsWorkbenchWindowAdvisor#postWindowOpen()} to
147 * recognize when to skip all one-time initialization.
149 protected boolean workbenchWindowsInitialized = false;
152 * Whether or not to save unsaved database changes before exiting the
155 protected boolean saveAtExit = false;
158 * Ordered map of versioned feature ids -> info that are new for this
159 * session; <code>null</code> if uninitialized. Key type:
160 * <code>String</code>, Value type: <code>AboutInfo</code>.
162 private Map<String, AboutInfo> newlyAddedBundleGroups;
165 * Array of <code>AboutInfo</code> for all new installed features that
166 * specify a welcome perspective.
168 private AboutInfo[] welcomePerspectiveInfos = null;
171 * Helper for managing activites in response to workspace changes.
173 private IDEWorkbenchActivityHelper activityHelper = null;
176 * Helper for managing work that is performed when the system is otherwise
179 private IDEIdleHelper idleHelper;
181 private Listener settingsChangeListener;
184 * Support class for monitoring workspace changes and periodically
185 * validating the undo history
187 private WorkspaceUndoMonitor workspaceUndoMonitor;
190 * The IDE workbench error handler.
192 private AbstractStatusHandler ideWorkbenchErrorHandler;
195 * Helper class used to process delayed events.
197 private DelayedEventsProcessor delayedEventsProcessor;
200 * Creates a new workbench advisor instance.
203 public SimanticsWorkbenchAdvisor(IArguments args, DelayedEventsProcessor processor) {
206 this.delayedEventsProcessor = processor;
208 Listener closeListener = new Listener() {
209 public void handleEvent(Event event) {
210 boolean doExit = SimanticsWorkbenchWindowAdvisor.promptOnExit(null);
213 event.type = SWT.None;
216 Display.getDefault().addListener(SWT.Close, closeListener);
219 public IArguments getArguments() {
223 public boolean workbenchInitialized() {
224 return workbenchWindowsInitialized;
227 public boolean restoredPreviousSession() {
228 return restoredPreviousSession;
231 boolean saveAtExit() {
235 void setSaveAtExit(boolean saveAtExit) {
236 this.saveAtExit = saveAtExit;
242 * @see org.eclipse.ui.application.WorkbenchAdvisor#initialize
245 public void initialize(IWorkbenchConfigurer configurer) {
246 // By default, we always save and restore the workbench state.
247 configurer.setSaveAndRestore(true);
249 checkWorkspaceDatabaseIndexes();
251 // Start tracking the active perspective to activate contexts based on it.
252 new PerspectiveContextActivator();
253 new PerspectiveBarsActivator();
255 // register workspace adapters
256 IDE.registerAdapters();
258 // register shared images
259 declareWorkbenchImages();
261 // initialize the activity helper
262 activityHelper = IDEWorkbenchActivityHelper.getInstance();
264 // initialize idle handler
265 idleHelper = new IDEIdleHelper(configurer);
267 // initialize the workspace undo monitor
268 workspaceUndoMonitor = WorkspaceUndoMonitor.getInstance();
270 // show Help button in JFace dialogs
271 TrayDialog.setDialogHelpAvailable(true);
273 Policy.setComparator(Collator.getInstance());
276 private void checkWorkspaceDatabaseIndexes() {
278 DatabaseIndexing.validateIndexes();
279 } catch (IOException e) {
280 Activator.logError("Problems encountered while checking database indexes, see exception for details.", e);
284 public WorkbenchWindowAdvisor createWorkbenchWindowAdvisorClass(SimanticsWorkbenchAdvisor advisor, IWorkbenchWindowConfigurer configurer) {
285 return new SimanticsWorkbenchWindowAdvisor(this, configurer);
289 public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) {
290 // Attach database session watchdog.
291 new SessionWatchdog().attach( Simantics.getSessionContextProvider() );
293 return createWorkbenchWindowAdvisorClass(this, configurer);
297 * For gaining direct access to super.openWindows() in implementations
298 * inheriting this one.
300 public boolean openWindowsSuper() {
301 return super.openWindows();
305 * Sadly we do not know why key bindings are lost and why this helps. But it
306 * does. Visiting the <code>Keys</code> preference page and pressing OK uses
307 * this the same call and it seems to salvage the bindings that have been in
308 * some cases destroyed by <code>BindingToModelProcessor</code>.
312 * https://techblog.ralph-schuster.eu/2013/10/13/eclipsee4-problem-with-key-bindings/comment-page-1/
313 * https://www.eclipse.org/forums/index.php/t/550175/
314 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=461037
316 * @see platform issue #6353
318 private void fixBindings() {
320 IBindingService bs = PlatformUI.getWorkbench().getAdapter(IBindingService.class);
321 bs.savePreferences(bs.getActiveScheme(), bs.getBindings());
322 } catch (IOException e) {
323 Activator.logError(getClass().getSimpleName() + ".fixBindings failed", e);
328 public boolean openWindows() {
329 boolean platformOk = startPlatform();
330 LOGGER.info("startPlatform finished");
331 TimeLogger.log("SimanticsWorkbenchAdvisor.startPlatform finished");
334 // At this point workbenchConfigurer.getSaveAndRestore()
335 // returns false iff something has gone terribly wrong
336 // before this. Currently saveAndRestore is always true.
337 boolean windowsOpened = super.openWindows();
338 TimeLogger.log("Opened windows");
340 workbenchWindowsInitialized = true;
342 // Start the database garbage collector after a short while.
343 SessionGarbageCollectorJob.getInstance().scheduleAfterQuietTime();
345 // #6353: Workaround for
352 // Make sure platform shutdown is ran if window opening fails.
354 platformShutdownRunnable.run(null);
355 } catch (InvocationTargetException e) {
356 Activator.logError(getClass().getSimpleName() + ".openWindows failed", e.getCause());
357 } catch (InterruptedException e) {
358 Activator.logError(getClass().getSimpleName() + ".openWindows failed", e);
363 protected boolean startPlatform() {
364 // Verify selected perspective
365 if (args.contains(SimanticsArguments.PERSPECTIVE)) {
366 String perspectiveId = args.get(SimanticsArguments.PERSPECTIVE);
367 IPerspectiveDescriptor perspective = PlatformUI.getWorkbench().getPerspectiveRegistry().findPerspectiveWithId(perspectiveId);
368 if (perspective == null) {
369 StringBuilder msg = new StringBuilder();
370 msg.append("Requested perspective not found: '" + perspectiveId + "'\n");
371 msg.append("Valid alternatives are:\n");
372 for (IPerspectiveDescriptor pd : PlatformUI.getWorkbench().getPerspectiveRegistry().getPerspectives()) {
373 msg.append(" " + pd.getId() + "\n");
376 ShowMessage.syncShowError("Invalid Perspective", msg.toString());
381 ILog log = Platform.getLog(Activator.getDefault().getBundle());
386 // Create Simantics Platform Helper.
388 // If Simantics is started from Eclipse IDE or with -fixerrors option,
389 // there is an attempt to fix errors.
391 // On ontology mismatch, there is an attempt to merge new ontology to the
392 // existing database. With -reinstall, the database is cleaned and
397 RecoveryPolicy workspacePolicy = Platform.inDevelopmentMode() ? RecoveryPolicy.FixError : RecoveryPolicy.ThrowError;
398 OntologyRecoveryPolicy ontologyPolicy = Platform.inDevelopmentMode() ? OntologyRecoveryPolicy.Merge : OntologyRecoveryPolicy.ThrowError;
400 if (args.contains(SimanticsArguments.RECOVERY_POLICY_FIX_ERRORS)) {
401 workspacePolicy = RecoveryPolicy.FixError;
402 ontologyPolicy = OntologyRecoveryPolicy.Merge;
405 boolean requireSynchronize = true;
407 if (args.contains(SimanticsArguments.ONTOLOGY_RECOVERY_POLICY_REINSTALL)) {
408 ontologyPolicy = OntologyRecoveryPolicy.ReinstallDatabase;
411 if (args.contains(SimanticsArguments.DO_NOT_SYNCHRONIZE_ONTOLOGIES)) {
412 requireSynchronize = false;
413 ontologyPolicy = OntologyRecoveryPolicy.Bypass;
416 if (args.contains(SimanticsArguments.DISABLE_INDEX)) {
417 Indexing.setDefaultDependenciesIndexingEnabled(false);
420 if (args.contains(SimanticsArguments.SERVER)) {
421 String serverAddress = args.get(SimanticsArguments.SERVER);
422 throw new PlatformException("Argument not supported: " + SimanticsArguments.SERVER + " " + serverAddress);
425 String databaseDriverId = Simantics.getDefaultDatabaseDriver();
426 if (args.contains(SimanticsArguments.DATABASE_ID)) {
427 databaseDriverId = args.get(SimanticsArguments.DATABASE_ID);
428 Simantics.setDefaultDatabaseDriver(databaseDriverId);
431 IProgressMonitor mon = null;
432 if (PROFILE_PLATFORM_STARTUP)
433 mon = new TimingProgressMonitor();
434 SimanticsPlatform.INSTANCE.startUp(databaseDriverId, mon, workspacePolicy, ontologyPolicy, requireSynchronize, new JFaceUserAgent());
436 // Make sure that the default perspective comes from the project if
437 // the project has set ProjectKeys#DEFAULT_PERSPECTIVE.
438 // This might go wrong if project features interact with
439 // PerspectiveRegistry while configuring themselves, since that will
440 // cause an invocation to #getInitialWindowPerspectiveId() while
441 // the project has not yet been properly initialized.
442 getWorkbenchConfigurer().getWorkbench().getPerspectiveRegistry().setDefaultPerspective(getInitialWindowPerspectiveId());
443 TimeLogger.log("Completed setting default perspective");
446 } catch (CancelStartupException e) {
448 } catch (PlatformException e) {
449 boolean hasStackTrace = e.getStackTrace().length > 0;
451 while (ee.getCause() != null) {
453 hasStackTrace = ee.getStackTrace().length > 0;
456 log.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), hasStackTrace ? e : null));
458 new ShowError("Platform Initialization Failed", "Simantics Platform initialization failed:\n\n" + e.getMessage(), e, true);
460 StringBuilder sb = new StringBuilder(256);
461 sb.append(e.getMessage());
462 for (Throwable c=e.getCause(); null != c && null != c.getMessage(); c=c.getCause())
463 sb.append("\ncause: ").append(c.getMessage());
464 new ShowError("Startup Failed", sb.toString(), (Exception) null, true);
468 } catch (Exception e) {
469 log.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e));
470 new ShowError("Platform Startup Failed", "Simantics Platform startup failed:\n\n" + e.getMessage(), e, true);
479 * @see org.eclipse.ui.application.WorkbenchAdvisor#preStartup()
482 public void preStartup() {
484 // Suspend background jobs while we startup
485 Job.getJobManager().suspend();
487 // Register the build actions
488 IProgressService service = PlatformUI.getWorkbench()
489 .getProgressService();
490 ImageDescriptor newImage = IDEInternalWorkbenchImages
491 .getImageDescriptor(IDEInternalWorkbenchImages.IMG_ETOOL_BUILD_EXEC);
492 service.registerIconForFamily(newImage,
493 ResourcesPlugin.FAMILY_MANUAL_BUILD);
494 service.registerIconForFamily(newImage,
495 ResourcesPlugin.FAMILY_AUTO_BUILD);
501 * @see org.eclipse.ui.application.WorkbenchAdvisor#postStartup()
504 public void postStartup() {
507 activateProxyService();
508 ((Workbench) PlatformUI.getWorkbench()).registerService(
509 ISelectionConversionService.class,
510 new IDESelectionConversionService());
512 initializeSettingsChangeListener();
513 Display.getCurrent().addListener(SWT.Settings,
514 settingsChangeListener);
515 } finally {// Resume background jobs after we startup
516 Job.getJobManager().resume();
521 * Activate the proxy service by obtaining it.
523 private void activateProxyService() {
524 Bundle bundle = Platform.getBundle("org.eclipse.ui.ide"); //$NON-NLS-1$
525 Object proxyService = null;
526 if (bundle != null) {
527 ServiceReference<?> ref = bundle.getBundleContext().getServiceReference(IProxyService.class.getName());
529 proxyService = bundle.getBundleContext().getService(ref);
531 if (proxyService == null) {
532 IDEWorkbenchPlugin.log("Proxy service could not be found."); //$NON-NLS-1$
537 * Initialize the listener for settings changes.
539 private void initializeSettingsChangeListener() {
540 settingsChangeListener = new Listener() {
542 boolean currentHighContrast = Display.getCurrent()
546 public void handleEvent(org.eclipse.swt.widgets.Event event) {
547 if (Display.getCurrent().getHighContrast() == currentHighContrast)
550 currentHighContrast = !currentHighContrast;
552 // make sure they really want to do this
553 if (new MessageDialog(null,
554 IDEWorkbenchMessages.SystemSettingsChange_title, null,
555 IDEWorkbenchMessages.SystemSettingsChange_message,
556 MessageDialog.QUESTION, new String[] {
557 IDEWorkbenchMessages.SystemSettingsChange_yes,
558 IDEWorkbenchMessages.SystemSettingsChange_no },
559 1).open() == Window.OK) {
560 PlatformUI.getWorkbench().restart();
570 * @see org.eclipse.ui.application.WorkbenchAdvisor#postShutdown
573 public void postShutdown() {
574 if (activityHelper != null) {
575 activityHelper.shutdown();
576 activityHelper = null;
578 if (idleHelper != null) {
579 idleHelper.shutdown();
582 if (workspaceUndoMonitor != null) {
583 workspaceUndoMonitor.shutdown();
584 workspaceUndoMonitor = null;
586 if (IDEWorkbenchPlugin.getPluginWorkspace() != null) {
587 disconnectFromWorkspace();
594 * @see org.eclipse.ui.application.WorkbenchAdvisor#preShutdown()
597 public boolean preShutdown() {
598 Display.getCurrent().removeListener(SWT.Settings,
599 settingsChangeListener);
600 return super.preShutdown();
604 * Return true if the intro plugin is present and false otherwise.
608 public boolean hasIntro() {
609 return getWorkbenchConfigurer().getWorkbench().getIntroManager()
613 private void refreshFromLocal() {
614 String[] commandLineArgs = Platform.getCommandLineArgs();
615 IPreferenceStore store = IDEWorkbenchPlugin.getDefault()
616 .getPreferenceStore();
617 boolean refresh = store
618 .getBoolean(IDEInternalPreferences.REFRESH_WORKSPACE_ON_STARTUP);
623 // Do not refresh if it was already done by core on startup.
624 for (int i = 0; i < commandLineArgs.length; i++) {
625 if (commandLineArgs[i].equalsIgnoreCase("-refresh")) { //$NON-NLS-1$
630 final IContainer root = ResourcesPlugin.getWorkspace().getRoot();
631 Job job = new WorkspaceJob(IDEWorkbenchMessages.Workspace_refreshing) {
633 public IStatus runInWorkspace(IProgressMonitor monitor)
634 throws CoreException {
635 root.refreshLocal(IResource.DEPTH_INFINITE, monitor);
636 return Status.OK_STATUS;
643 private static class CancelableProgressMonitorWrapper extends ProgressMonitorWrapper {
644 private double total = 0;
645 private ProgressMonitorJobsDialog dialog;
647 CancelableProgressMonitorWrapper(IProgressMonitor monitor,
648 ProgressMonitorJobsDialog dialog) {
650 this.dialog = dialog;
655 * @see org.eclipse.core.runtime.ProgressMonitorWrapper#internalWorked(double)
657 public void internalWorked(double work) {
658 super.internalWorked(work);
660 updateProgressDetails();
665 * @see org.eclipse.core.runtime.ProgressMonitorWrapper#worked(int)
667 public void worked(int work) {
670 updateProgressDetails();
673 public void beginTask(String name, int totalWork) {
674 super.beginTask(name, totalWork);
675 subTask(IDEWorkbenchMessages.IDEWorkbenchAdvisor_preHistoryCompaction);
678 private void updateProgressDetails() {
679 if (!isCanceled() && Math.abs(total - 4.0) < 0.0001 /* right before history compacting */) {
680 subTask(IDEWorkbenchMessages.IDEWorkbenchAdvisor_cancelHistoryPruning);
681 dialog.setCancelable(true);
683 if (Math.abs(total - 5.0) < 0.0001 /* history compacting finished */) {
684 subTask(IDEWorkbenchMessages.IDEWorkbenchAdvisor_postHistoryCompaction);
685 dialog.setCancelable(false);
690 private static class CancelableProgressMonitorJobsDialog extends ProgressMonitorJobsDialog {
692 public CancelableProgressMonitorJobsDialog(Shell parent) {
698 * @see org.eclipse.ui.internal.progress.ProgressMonitorJobsDialog#createDetailsButton(org.eclipse.swt.widgets.Composite)
700 protected void createButtonsForButtonBar(Composite parent) {
701 super.createButtonsForButtonBar(parent);
702 registerCancelButtonListener();
705 public void registerCancelButtonListener() {
706 cancel.addSelectionListener(new SelectionAdapter() {
707 public void widgetSelected(SelectionEvent e) {
708 subTaskLabel.setText(""); //$NON-NLS-1$
715 final IRunnableWithProgress platformShutdownRunnable = new IRunnableWithProgress() {
718 * the progress monitor to use for reporting progress to the
719 * user, or <code>null</code> indicating that no progress
720 * should be reported and the operation cannot be cancelled.
723 public void run(IProgressMonitor monitor) {
724 SubMonitor progress = SubMonitor.convert(monitor, SHUT_DOWN_PLATFORM_TASK, 100);
727 progress.subTask("Platform");
728 SimanticsPlatform.INSTANCE.shutdown(progress.newChild(100));
729 } catch (PlatformException e) {
730 Activator.logError("Problems encountered while shutting down Simantics platform, see exception for details.", e);
733 progress.subTask("Remaining database connections");
734 SimanticsUI.closeSessions();
736 progress.setWorkRemaining(0);
738 if (monitor != null) {
746 * Disconnect from the workspace and close ProCore sessions.
748 private void disconnectFromWorkspace() {
749 // save the workspace
750 final MultiStatus status = new MultiStatus(
751 IDEWorkbenchPlugin.IDE_WORKBENCH, 1,
752 IDEWorkbenchMessages.ProblemSavingWorkbench, null);
754 final ProgressMonitorJobsDialog p = new CancelableProgressMonitorJobsDialog(
757 final boolean applyPolicy = ResourcesPlugin.getWorkspace()
758 .getDescription().isApplyFileStatePolicy();
760 final IRunnableWithProgress workspaceShutdownRunnable = new IRunnableWithProgress() {
762 public void run(IProgressMonitor monitor) {
764 status.merge(((Workspace) ResourcesPlugin.getWorkspace()).save(true, true, monitor));
765 } catch (CoreException e) {
766 status.merge(e.getStatus());
771 IRunnableWithProgress shutdownRunnable = new IRunnableWithProgress() {
773 public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
775 monitor = new CancelableProgressMonitorWrapper(
778 SubMonitor progress = SubMonitor.convert(monitor, SHUT_DOWN_TASK, 2);
780 workspaceShutdownRunnable.run(progress.newChild(1, SubMonitor.SUPPRESS_NONE));
781 platformShutdownRunnable.run(progress.newChild(1, SubMonitor.SUPPRESS_NONE));
789 new ProgressMonitorJobsDialog(null).run(true, false, shutdownRunnable);
790 } catch (InvocationTargetException e) {
791 status.merge(new Status(IStatus.ERROR,
792 IDEWorkbenchPlugin.IDE_WORKBENCH, 1,
793 IDEWorkbenchMessages.InternalError, e.getTargetException()));
794 } catch (InterruptedException e) {
795 status.merge(new Status(IStatus.ERROR,
796 IDEWorkbenchPlugin.IDE_WORKBENCH, 1,
797 IDEWorkbenchMessages.InternalError, e));
799 ErrorDialog.openError(null,
800 IDEWorkbenchMessages.ProblemsSavingWorkspace, null, status,
801 IStatus.ERROR | IStatus.WARNING);
802 if (!status.isOK()) {
803 IDEWorkbenchPlugin.log(
804 IDEWorkbenchMessages.ProblemsSavingWorkspace, status);
811 * @see org.eclipse.ui.application.WorkbenchAdvisor#getDefaultPageInput
814 public IAdaptable getDefaultPageInput() {
815 return ResourcesPlugin.getWorkspace().getRoot();
821 * @see org.eclipse.ui.application.WorkbenchAdvisor
824 public String getInitialWindowPerspectiveId() {
825 int index = PlatformUI.getWorkbench().getWorkbenchWindowCount() - 1;
827 String perspectiveId = null;
828 AboutInfo[] welcomeInfos = getWelcomePerspectiveInfos();
829 if (index >= 0 && welcomeInfos != null && index < welcomeInfos.length) {
830 perspectiveId = welcomeInfos[index].getWelcomePerspectiveId();
833 if (perspectiveId == null && args.contains(SimanticsArguments.PERSPECTIVE)) {
834 String id = args.get(SimanticsArguments.PERSPECTIVE);
835 IPerspectiveDescriptor perspective = PlatformUI.getWorkbench().getPerspectiveRegistry().findPerspectiveWithId(id);
836 if (perspective != null)
840 if (perspectiveId == null) {
841 IProject project = Simantics.peekProject();
843 perspectiveId = project.getHint(ProjectKeys.DEFAULT_PERSPECTIVE);
846 //System.out.println("Initial perspective: " + perspectiveId);
848 return perspectiveId;
852 * Returns the map of versioned feature ids -> info object for all installed
853 * features. The format of the versioned feature id (the key of the map) is
854 * featureId + ":" + versionId.
856 * @return map of versioned feature ids -> info object (key type:
857 * <code>String</code>, value type: <code>AboutInfo</code>)
860 private Map<String, AboutInfo> computeBundleGroupMap() {
861 // use tree map to get predicable order
862 Map<String, AboutInfo> ids = new TreeMap<String, AboutInfo>();
864 IBundleGroupProvider[] providers = Platform.getBundleGroupProviders();
865 for (int i = 0; i < providers.length; ++i) {
866 IBundleGroup[] groups = providers[i].getBundleGroups();
867 for (int j = 0; j < groups.length; ++j) {
868 IBundleGroup group = groups[j];
869 AboutInfo info = new AboutInfo(group);
871 String version = info.getVersionId();
872 version = version == null ? "0.0.0" //$NON-NLS-1$
873 : new Version(version).toString();
874 String versionedFeature = group.getIdentifier() + ":" + version; //$NON-NLS-1$
876 ids.put(versionedFeature, info);
884 * Returns the ordered map of versioned feature ids -> AboutInfo that are
885 * new for this session.
887 * @return ordered map of versioned feature ids (key type:
888 * <code>String</code>) -> infos (value type:
889 * <code>AboutInfo</code>).
891 public Map<String, AboutInfo> getNewlyAddedBundleGroups() {
892 if (newlyAddedBundleGroups == null) {
893 newlyAddedBundleGroups = createNewBundleGroupsMap();
895 return newlyAddedBundleGroups;
899 * Updates the old features setting and returns a map of new features.
901 private Map<String, AboutInfo> createNewBundleGroupsMap() {
902 // retrieve list of installed bundle groups from last session
903 IDialogSettings settings = IDEWorkbenchPlugin.getDefault()
904 .getDialogSettings();
905 String[] previousFeaturesArray = settings.getArray(INSTALLED_FEATURES);
907 // get a map of currently installed bundle groups and store it for next
909 Map<String, AboutInfo> bundleGroups = computeBundleGroupMap();
910 String[] currentFeaturesArray = new String[bundleGroups.size()];
911 bundleGroups.keySet().toArray(currentFeaturesArray);
912 settings.put(INSTALLED_FEATURES, currentFeaturesArray);
914 // remove the previously known from the current set
915 if (previousFeaturesArray != null) {
916 for (int i = 0; i < previousFeaturesArray.length; ++i) {
917 bundleGroups.remove(previousFeaturesArray[i]);
925 * Declares all IDE-specific workbench images. This includes both "shared"
926 * images (named in {@link IDE.SharedImages}) and internal images (named in
927 * {@link org.eclipse.ui.internal.ide.IDEInternalWorkbenchImages}).
929 * @see IWorkbenchConfigurer#declareImage
931 private void declareWorkbenchImages() {
933 final String ICONS_PATH = "$nl$/icons/full/";//$NON-NLS-1$
934 final String PATH_ELOCALTOOL = ICONS_PATH + "elcl16/"; // Enabled //$NON-NLS-1$
938 final String PATH_DLOCALTOOL = ICONS_PATH + "dlcl16/"; // Disabled //$NON-NLS-1$
942 final String PATH_ETOOL = ICONS_PATH + "etool16/"; // Enabled toolbar //$NON-NLS-1$
945 final String PATH_DTOOL = ICONS_PATH + "dtool16/"; // Disabled toolbar //$NON-NLS-1$
948 final String PATH_OBJECT = ICONS_PATH + "obj16/"; // Model object //$NON-NLS-1$
951 final String PATH_WIZBAN = ICONS_PATH + "wizban/"; // Wizard //$NON-NLS-1$
955 Bundle ideBundle = Platform.getBundle(IDEWorkbenchPlugin.IDE_WORKBENCH);
957 declareWorkbenchImage(ideBundle,
958 IDEInternalWorkbenchImages.IMG_ETOOL_BUILD_EXEC, PATH_ETOOL
959 + "build_exec.gif", false); //$NON-NLS-1$
960 declareWorkbenchImage(ideBundle,
961 IDEInternalWorkbenchImages.IMG_ETOOL_BUILD_EXEC_HOVER,
962 PATH_ETOOL + "build_exec.gif", false); //$NON-NLS-1$
963 declareWorkbenchImage(ideBundle,
964 IDEInternalWorkbenchImages.IMG_ETOOL_BUILD_EXEC_DISABLED,
965 PATH_DTOOL + "build_exec.gif", false); //$NON-NLS-1$
967 declareWorkbenchImage(ideBundle,
968 IDEInternalWorkbenchImages.IMG_ETOOL_SEARCH_SRC, PATH_ETOOL
969 + "search_src.gif", false); //$NON-NLS-1$
970 declareWorkbenchImage(ideBundle,
971 IDEInternalWorkbenchImages.IMG_ETOOL_SEARCH_SRC_HOVER,
972 PATH_ETOOL + "search_src.gif", false); //$NON-NLS-1$
973 declareWorkbenchImage(ideBundle,
974 IDEInternalWorkbenchImages.IMG_ETOOL_SEARCH_SRC_DISABLED,
975 PATH_DTOOL + "search_src.gif", false); //$NON-NLS-1$
977 declareWorkbenchImage(ideBundle,
978 IDEInternalWorkbenchImages.IMG_ETOOL_NEXT_NAV, PATH_ETOOL
979 + "next_nav.gif", false); //$NON-NLS-1$
981 declareWorkbenchImage(ideBundle,
982 IDEInternalWorkbenchImages.IMG_ETOOL_PREVIOUS_NAV, PATH_ETOOL
983 + "prev_nav.gif", false); //$NON-NLS-1$
985 declareWorkbenchImage(ideBundle,
986 IDEInternalWorkbenchImages.IMG_WIZBAN_NEWPRJ_WIZ, PATH_WIZBAN
987 + "newprj_wiz.png", false); //$NON-NLS-1$
988 declareWorkbenchImage(ideBundle,
989 IDEInternalWorkbenchImages.IMG_WIZBAN_NEWFOLDER_WIZ,
990 PATH_WIZBAN + "newfolder_wiz.png", false); //$NON-NLS-1$
991 declareWorkbenchImage(ideBundle,
992 IDEInternalWorkbenchImages.IMG_WIZBAN_NEWFILE_WIZ, PATH_WIZBAN
993 + "newfile_wiz.png", false); //$NON-NLS-1$
995 declareWorkbenchImage(ideBundle,
996 IDEInternalWorkbenchImages.IMG_WIZBAN_IMPORTDIR_WIZ,
997 PATH_WIZBAN + "importdir_wiz.png", false); //$NON-NLS-1$
998 declareWorkbenchImage(ideBundle,
999 IDEInternalWorkbenchImages.IMG_WIZBAN_IMPORTZIP_WIZ,
1000 PATH_WIZBAN + "importzip_wiz.png", false); //$NON-NLS-1$
1002 declareWorkbenchImage(ideBundle,
1003 IDEInternalWorkbenchImages.IMG_WIZBAN_EXPORTDIR_WIZ,
1004 PATH_WIZBAN + "exportdir_wiz.png", false); //$NON-NLS-1$
1005 declareWorkbenchImage(ideBundle,
1006 IDEInternalWorkbenchImages.IMG_WIZBAN_EXPORTZIP_WIZ,
1007 PATH_WIZBAN + "exportzip_wiz.png", false); //$NON-NLS-1$
1009 declareWorkbenchImage(ideBundle,
1010 IDEInternalWorkbenchImages.IMG_WIZBAN_RESOURCEWORKINGSET_WIZ,
1011 PATH_WIZBAN + "workset_wiz.png", false); //$NON-NLS-1$
1013 declareWorkbenchImage(ideBundle,
1014 IDEInternalWorkbenchImages.IMG_DLGBAN_SAVEAS_DLG, PATH_WIZBAN
1015 + "saveas_wiz.png", false); //$NON-NLS-1$
1017 declareWorkbenchImage(ideBundle,
1018 IDEInternalWorkbenchImages.IMG_DLGBAN_QUICKFIX_DLG, PATH_WIZBAN
1019 + "quick_fix.png", false); //$NON-NLS-1$
1021 declareWorkbenchImage(ideBundle, IDE.SharedImages.IMG_OBJ_PROJECT,
1022 PATH_OBJECT + "prj_obj.gif", true); //$NON-NLS-1$
1023 declareWorkbenchImage(ideBundle,
1024 IDE.SharedImages.IMG_OBJ_PROJECT_CLOSED, PATH_OBJECT
1025 + "cprj_obj.gif", true); //$NON-NLS-1$
1026 declareWorkbenchImage(ideBundle, IDE.SharedImages.IMG_OPEN_MARKER,
1027 PATH_ELOCALTOOL + "gotoobj_tsk.gif", true); //$NON-NLS-1$
1029 declareWorkbenchImage(ideBundle,
1030 IDEInternalWorkbenchImages.IMG_ELCL_QUICK_FIX_ENABLED,
1031 PATH_ELOCALTOOL + "smartmode_co.gif", true); //$NON-NLS-1$
1033 declareWorkbenchImage(ideBundle,
1034 IDEInternalWorkbenchImages.IMG_DLCL_QUICK_FIX_DISABLED,
1035 PATH_DLOCALTOOL + "smartmode_co.gif", true); //$NON-NLS-1$
1038 // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_HPRIO_TSK,
1039 // PATH_OBJECT+"hprio_tsk.gif");
1040 // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_MPRIO_TSK,
1041 // PATH_OBJECT+"mprio_tsk.gif");
1042 // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_LPRIO_TSK,
1043 // PATH_OBJECT+"lprio_tsk.gif");
1045 declareWorkbenchImage(ideBundle, IDE.SharedImages.IMG_OBJS_TASK_TSK,
1046 PATH_OBJECT + "taskmrk_tsk.gif", true); //$NON-NLS-1$
1047 declareWorkbenchImage(ideBundle, IDE.SharedImages.IMG_OBJS_BKMRK_TSK,
1048 PATH_OBJECT + "bkmrk_tsk.gif", true); //$NON-NLS-1$
1050 declareWorkbenchImage(ideBundle,
1051 IDEInternalWorkbenchImages.IMG_OBJS_COMPLETE_TSK, PATH_OBJECT
1052 + "complete_tsk.gif", true); //$NON-NLS-1$
1053 declareWorkbenchImage(ideBundle,
1054 IDEInternalWorkbenchImages.IMG_OBJS_INCOMPLETE_TSK, PATH_OBJECT
1055 + "incomplete_tsk.gif", true); //$NON-NLS-1$
1056 declareWorkbenchImage(ideBundle,
1057 IDEInternalWorkbenchImages.IMG_OBJS_WELCOME_ITEM, PATH_OBJECT
1058 + "welcome_item.gif", true); //$NON-NLS-1$
1059 declareWorkbenchImage(ideBundle,
1060 IDEInternalWorkbenchImages.IMG_OBJS_WELCOME_BANNER, PATH_OBJECT
1061 + "welcome_banner.gif", true); //$NON-NLS-1$
1062 declareWorkbenchImage(ideBundle,
1063 IDEInternalWorkbenchImages.IMG_OBJS_ERROR_PATH, PATH_OBJECT
1064 + "error_tsk.gif", true); //$NON-NLS-1$
1065 declareWorkbenchImage(ideBundle,
1066 IDEInternalWorkbenchImages.IMG_OBJS_WARNING_PATH, PATH_OBJECT
1067 + "warn_tsk.gif", true); //$NON-NLS-1$
1068 declareWorkbenchImage(ideBundle,
1069 IDEInternalWorkbenchImages.IMG_OBJS_INFO_PATH, PATH_OBJECT
1070 + "info_tsk.gif", true); //$NON-NLS-1$
1072 declareWorkbenchImage(ideBundle,
1073 IDEInternalWorkbenchImages.IMG_LCL_FLAT_LAYOUT, PATH_ELOCALTOOL
1074 + "flatLayout.gif", true); //$NON-NLS-1$
1075 declareWorkbenchImage(ideBundle,
1076 IDEInternalWorkbenchImages.IMG_LCL_HIERARCHICAL_LAYOUT,
1077 PATH_ELOCALTOOL + "hierarchicalLayout.gif", true); //$NON-NLS-1$
1078 declareWorkbenchImage(ideBundle,
1079 IDEInternalWorkbenchImages.IMG_ETOOL_PROBLEM_CATEGORY,
1080 PATH_ETOOL + "problem_category.gif", true); //$NON-NLS-1$
1082 declareWorkbenchImage(ideBundle,
1083 IDEInternalWorkbenchImages.IMG_LCL_LINKTO_HELP, PATH_ELOCALTOOL
1084 + "linkto_help.gif", false); //$NON-NLS-1$
1087 // synchronization indicator objects
1088 // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_WBET_STAT,
1089 // PATH_OVERLAY+"wbet_stat.gif");
1090 // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_SBET_STAT,
1091 // PATH_OVERLAY+"sbet_stat.gif");
1092 // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_CONFLICT_STAT,
1093 // PATH_OVERLAY+"conflict_stat.gif");
1095 // content locality indicator objects
1096 // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_NOTLOCAL_STAT,
1097 // PATH_STAT+"notlocal_stat.gif");
1098 // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_LOCAL_STAT,
1099 // PATH_STAT+"local_stat.gif");
1100 // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_FILLLOCAL_STAT,
1101 // PATH_STAT+"filllocal_stat.gif");
1105 * Declares an IDE-specific workbench image.
1107 * @param symbolicName
1108 * the symbolic name of the image
1110 * the path of the image file; this path is relative to the base
1111 * of the IDE plug-in
1113 * <code>true</code> if this is a shared image, and
1114 * <code>false</code> if this is not a shared image
1115 * @see IWorkbenchConfigurer#declareImage
1117 private void declareWorkbenchImage(Bundle ideBundle, String symbolicName,
1118 String path, boolean shared) {
1119 URL url = FileLocator.find(ideBundle, new Path(path), null);
1120 ImageDescriptor desc = ImageDescriptor.createFromURL(url);
1121 getWorkbenchConfigurer().declareImage(symbolicName, desc, shared);
1127 * @see org.eclipse.ui.application.WorkbenchAdvisor#getMainPreferencePageId
1130 public String getMainPreferencePageId() {
1131 // indicate that we want the Workench preference page to be prominent
1132 return WORKBENCH_PREFERENCE_CATEGORY_ID;
1136 * @return the workspace location string, or <code>null</code> if the
1137 * location is not being shown
1139 public String getWorkspaceLocation() {
1140 // read command line, which has priority
1141 IEclipseContext context = getWorkbenchConfigurer().getWorkbench().getService(IEclipseContext.class);
1142 String location = context != null ? (String) context.get(E4Workbench.FORCED_SHOW_LOCATION) : null;
1143 if (location != null) {
1146 // read the preference
1147 if (IDEWorkbenchPlugin.getDefault().getPreferenceStore().getBoolean(IDEInternalPreferences.SHOW_LOCATION)) {
1148 return Platform.getLocation().toOSString();
1154 * @return the welcome perspective infos, or <code>null</code> if none or
1155 * if they should be ignored due to the new intro being present
1157 public AboutInfo[] getWelcomePerspectiveInfos() {
1158 if (welcomePerspectiveInfos == null) {
1159 // support old welcome perspectives if intro plugin is not present
1161 Map<String, AboutInfo> m = getNewlyAddedBundleGroups();
1162 ArrayList<AboutInfo> list = new ArrayList<AboutInfo>(m.size());
1163 for (Iterator<AboutInfo> i = m.values().iterator(); i.hasNext();) {
1164 AboutInfo info = i.next();
1165 if (info != null && info.getWelcomePerspectiveId() != null
1166 && info.getWelcomePageURL() != null) {
1170 welcomePerspectiveInfos = new AboutInfo[list.size()];
1171 list.toArray(welcomePerspectiveInfos);
1174 return welcomePerspectiveInfos;
1180 * @see org.eclipse.ui.application.WorkbenchAdvisor#getWorkbenchErrorHandler()
1183 private AbstractStatusHandler workbenchErrorHandler = new AbstractStatusHandler() {
1186 public void handle(StatusAdapter statusAdapter, int style) {
1187 if (ideWorkbenchErrorHandler == null) {
1188 ideWorkbenchErrorHandler = new IDEWorkbenchErrorHandler(
1189 getWorkbenchConfigurer());
1191 ideWorkbenchErrorHandler.handle(statusAdapter, style);
1193 BundleContext context = Activator.getDefault().getBundle().getBundleContext();
1194 ServiceReference<?> ref = context.getServiceReference(UnhandledExceptionService.class.getName());
1195 UnhandledExceptionService unhandled = (UnhandledExceptionService)context.getService(ref);
1196 Throwable t = statusAdapter.getStatus().getException();
1198 unhandled.handle(t);
1204 public AbstractStatusHandler getWorkbenchErrorHandler() {
1205 return workbenchErrorHandler;
1209 * @see org.eclipse.ui.application.WorkbenchAdvisor#eventLoopIdle(org.eclipse.swt.widgets.Display)
1212 public void eventLoopIdle(Display display) {
1213 if (delayedEventsProcessor != null)
1214 delayedEventsProcessor.catchUp(display);
1215 super.eventLoopIdle(display);