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.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.internal.TimedSessionCache;
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.utils.logging.TimeLogger;
109 import org.simantics.utils.threads.ExecutorWorker;
110 import org.simantics.utils.threads.ThreadUtils;
111 import org.simantics.utils.ui.dialogs.ShowError;
112 import org.simantics.utils.ui.dialogs.ShowMessage;
113 import org.slf4j.Logger;
114 import org.slf4j.LoggerFactory;
118 * @author Tuukka Lehtonen
120 public class SimanticsWorkbenchAdvisor extends WorkbenchAdvisor {
122 private static final Logger LOGGER = LoggerFactory.getLogger(SimanticsWorkbenchAdvisor.class);
124 private static final boolean PROFILE_PLATFORM_STARTUP = false;
126 private static final String SHUT_DOWN_TASK = "Shutting down...";
128 private static final String SHUT_DOWN_PLATFORM_TASK = "Shutting down platform...";
130 private static final String WORKBENCH_PREFERENCE_CATEGORY_ID = "org.eclipse.ui.preferencePages.Workbench"; //$NON-NLS-1$
133 * The dialog setting key to access the known installed features since the
134 * last time the workbench was run.
136 private static final String INSTALLED_FEATURES = "installedFeatures"; //$NON-NLS-1$
139 * The arguments received by the application.
141 protected final IArguments args;
143 protected final boolean restoredPreviousSession = false;
146 * Only true while opening the initial windows during {@link #openWindows()}.
147 * Used by {@link SimanticsWorkbenchWindowAdvisor#postWindowOpen()} to
148 * recognize when to skip all one-time initialization.
150 protected boolean workbenchWindowsInitialized = false;
153 * Whether or not to save unsaved database changes before exiting the
156 protected boolean saveAtExit = false;
159 * Ordered map of versioned feature ids -> info that are new for this
160 * session; <code>null</code> if uninitialized. Key type:
161 * <code>String</code>, Value type: <code>AboutInfo</code>.
163 private Map<String, AboutInfo> newlyAddedBundleGroups;
166 * Array of <code>AboutInfo</code> for all new installed features that
167 * specify a welcome perspective.
169 private AboutInfo[] welcomePerspectiveInfos = null;
172 * Helper for managing activites in response to workspace changes.
174 private IDEWorkbenchActivityHelper activityHelper = null;
177 * Helper for managing work that is performed when the system is otherwise
180 private IDEIdleHelper idleHelper;
182 private Listener settingsChangeListener;
185 * Support class for monitoring workspace changes and periodically
186 * validating the undo history
188 private WorkspaceUndoMonitor workspaceUndoMonitor;
191 * The IDE workbench error handler.
193 private AbstractStatusHandler ideWorkbenchErrorHandler;
196 * Helper class used to process delayed events.
198 private DelayedEventsProcessor delayedEventsProcessor;
201 * Creates a new workbench advisor instance.
204 public SimanticsWorkbenchAdvisor(IArguments args, DelayedEventsProcessor processor) {
207 this.delayedEventsProcessor = processor;
209 Listener closeListener = new Listener() {
210 public void handleEvent(Event event) {
211 boolean doExit = SimanticsWorkbenchWindowAdvisor.promptOnExit(null);
214 event.type = SWT.None;
217 Display.getDefault().addListener(SWT.Close, closeListener);
220 public IArguments getArguments() {
224 public boolean workbenchInitialized() {
225 return workbenchWindowsInitialized;
228 public boolean restoredPreviousSession() {
229 return restoredPreviousSession;
232 boolean saveAtExit() {
236 void setSaveAtExit(boolean saveAtExit) {
237 this.saveAtExit = saveAtExit;
243 * @see org.eclipse.ui.application.WorkbenchAdvisor#initialize
246 public void initialize(IWorkbenchConfigurer configurer) {
247 // By default, we always save and restore the workbench state.
248 configurer.setSaveAndRestore(true);
250 checkWorkspaceDatabaseIndexes();
252 // Start tracking the active perspective to activate contexts based on it.
253 new PerspectiveContextActivator();
254 new PerspectiveBarsActivator();
256 // register workspace adapters
257 IDE.registerAdapters();
259 // register shared images
260 declareWorkbenchImages();
262 // initialize the activity helper
263 activityHelper = IDEWorkbenchActivityHelper.getInstance();
265 // initialize idle handler
266 idleHelper = new IDEIdleHelper(configurer);
268 // initialize the workspace undo monitor
269 workspaceUndoMonitor = WorkspaceUndoMonitor.getInstance();
271 // show Help button in JFace dialogs
272 TrayDialog.setDialogHelpAvailable(true);
274 Policy.setComparator(Collator.getInstance());
277 private void checkWorkspaceDatabaseIndexes() {
279 DatabaseIndexing.validateIndexes();
280 } catch (IOException e) {
281 Activator.logError("Problems encountered while checking database indexes, see exception for details.", e);
285 public WorkbenchWindowAdvisor createWorkbenchWindowAdvisorClass(SimanticsWorkbenchAdvisor advisor, IWorkbenchWindowConfigurer configurer) {
286 return new SimanticsWorkbenchWindowAdvisor(this, configurer);
290 public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) {
291 // Attach database session watchdog.
292 new SessionWatchdog().attach( Simantics.getSessionContextProvider() );
294 return createWorkbenchWindowAdvisorClass(this, configurer);
298 * For gaining direct access to super.openWindows() in implementations
299 * inheriting this one.
301 public boolean openWindowsSuper() {
302 return super.openWindows();
306 * Sadly we do not know why key bindings are lost and why this helps. But it
307 * does. Visiting the <code>Keys</code> preference page and pressing OK uses
308 * this the same call and it seems to salvage the bindings that have been in
309 * some cases destroyed by <code>BindingToModelProcessor</code>.
313 * https://techblog.ralph-schuster.eu/2013/10/13/eclipsee4-problem-with-key-bindings/comment-page-1/
314 * https://www.eclipse.org/forums/index.php/t/550175/
315 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=461037
317 * @see platform issue #6353
319 private void fixBindings() {
321 IBindingService bs = PlatformUI.getWorkbench().getAdapter(IBindingService.class);
322 bs.savePreferences(bs.getActiveScheme(), bs.getBindings());
323 } catch (IOException e) {
324 Activator.logError(getClass().getSimpleName() + ".fixBindings failed", e);
329 public boolean openWindows() {
330 boolean platformOk = startPlatform();
331 LOGGER.info("startPlatform finished");
332 TimeLogger.log("SimanticsWorkbenchAdvisor.startPlatform finished");
335 // At this point workbenchConfigurer.getSaveAndRestore()
336 // returns false iff something has gone terribly wrong
337 // before this. Currently saveAndRestore is always true.
338 boolean windowsOpened = super.openWindows();
339 TimeLogger.log("Opened windows");
341 workbenchWindowsInitialized = true;
343 // Start the database garbage collector after a short while.
344 SessionGarbageCollectorJob.getInstance().scheduleAfterQuietTime();
346 // #6353: Workaround for
353 // Make sure platform shutdown is ran if window opening fails.
355 platformShutdownRunnable.run(null);
356 } catch (InvocationTargetException e) {
357 Activator.logError(getClass().getSimpleName() + ".openWindows failed", e.getCause());
358 } catch (InterruptedException e) {
359 Activator.logError(getClass().getSimpleName() + ".openWindows failed", e);
364 protected boolean startPlatform() {
365 // Verify selected perspective
366 if (args.contains(SimanticsArguments.PERSPECTIVE)) {
367 String perspectiveId = args.get(SimanticsArguments.PERSPECTIVE);
368 IPerspectiveDescriptor perspective = PlatformUI.getWorkbench().getPerspectiveRegistry().findPerspectiveWithId(perspectiveId);
369 if (perspective == null) {
370 StringBuilder msg = new StringBuilder();
371 msg.append("Requested perspective not found: '" + perspectiveId + "'\n");
372 msg.append("Valid alternatives are:\n");
373 for (IPerspectiveDescriptor pd : PlatformUI.getWorkbench().getPerspectiveRegistry().getPerspectives()) {
374 msg.append(" " + pd.getId() + "\n");
377 ShowMessage.syncShowError("Invalid Perspective", msg.toString());
382 ILog log = Platform.getLog(Activator.getDefault().getBundle());
387 // Create Simantics Platform Helper.
389 // If Simantics is started from Eclipse IDE or with -fixerrors option,
390 // there is an attempt to fix errors.
392 // On ontology mismatch, there is an attempt to merge new ontology to the
393 // existing database. With -reinstall, the database is cleaned and
398 RecoveryPolicy workspacePolicy = Platform.inDevelopmentMode() ? RecoveryPolicy.FixError : RecoveryPolicy.ThrowError;
399 OntologyRecoveryPolicy ontologyPolicy = Platform.inDevelopmentMode() ? OntologyRecoveryPolicy.Merge : OntologyRecoveryPolicy.ThrowError;
401 if (args.contains(SimanticsArguments.RECOVERY_POLICY_FIX_ERRORS)) {
402 workspacePolicy = RecoveryPolicy.FixError;
403 ontologyPolicy = OntologyRecoveryPolicy.Merge;
406 boolean requireSynchronize = true;
408 if (args.contains(SimanticsArguments.ONTOLOGY_RECOVERY_POLICY_REINSTALL)) {
409 ontologyPolicy = OntologyRecoveryPolicy.ReinstallDatabase;
412 if (args.contains(SimanticsArguments.DO_NOT_SYNCHRONIZE_ONTOLOGIES)) {
413 requireSynchronize = false;
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));
471 Throwable cause = e.getCause();
472 if (cause instanceof RebootRequiredException) {
473 RebootRequiredException rre = (RebootRequiredException) cause;
474 StringBuilder msg = new StringBuilder();
475 msg.append("The application must be restarted after installing the following products:\n");
476 for (Product product : rre.products)
477 msg.append("\t" + product + "\n");
478 msg.append("\nThe application will now close.");
479 MessageDialog.openInformation(null, "Restart Required", msg.toString());
481 new ShowError("Platform Startup Failed", "Simantics Platform startup failed:\n\n" + e.getMessage(), e, true);
491 * @see org.eclipse.ui.application.WorkbenchAdvisor#preStartup()
494 public void preStartup() {
496 // Suspend background jobs while we startup
497 Job.getJobManager().suspend();
499 // Register the build actions
500 IProgressService service = PlatformUI.getWorkbench()
501 .getProgressService();
502 ImageDescriptor newImage = IDEInternalWorkbenchImages
503 .getImageDescriptor(IDEInternalWorkbenchImages.IMG_ETOOL_BUILD_EXEC);
504 service.registerIconForFamily(newImage,
505 ResourcesPlugin.FAMILY_MANUAL_BUILD);
506 service.registerIconForFamily(newImage,
507 ResourcesPlugin.FAMILY_AUTO_BUILD);
513 * @see org.eclipse.ui.application.WorkbenchAdvisor#postStartup()
516 public void postStartup() {
519 activateProxyService();
520 ((Workbench) PlatformUI.getWorkbench()).registerService(
521 ISelectionConversionService.class,
522 new IDESelectionConversionService());
524 initializeSettingsChangeListener();
525 Display.getCurrent().addListener(SWT.Settings,
526 settingsChangeListener);
527 } finally {// Resume background jobs after we startup
528 Job.getJobManager().resume();
533 * Activate the proxy service by obtaining it.
535 private void activateProxyService() {
536 Bundle bundle = Platform.getBundle("org.eclipse.ui.ide"); //$NON-NLS-1$
537 Object proxyService = null;
538 if (bundle != null) {
539 ServiceReference<?> ref = bundle.getBundleContext().getServiceReference(IProxyService.class.getName());
541 proxyService = bundle.getBundleContext().getService(ref);
543 if (proxyService == null) {
544 IDEWorkbenchPlugin.log("Proxy service could not be found."); //$NON-NLS-1$
549 * Initialize the listener for settings changes.
551 private void initializeSettingsChangeListener() {
552 settingsChangeListener = new Listener() {
554 boolean currentHighContrast = Display.getCurrent()
558 public void handleEvent(org.eclipse.swt.widgets.Event event) {
559 if (Display.getCurrent().getHighContrast() == currentHighContrast)
562 currentHighContrast = !currentHighContrast;
564 // make sure they really want to do this
565 if (new MessageDialog(null,
566 IDEWorkbenchMessages.SystemSettingsChange_title, null,
567 IDEWorkbenchMessages.SystemSettingsChange_message,
568 MessageDialog.QUESTION, new String[] {
569 IDEWorkbenchMessages.SystemSettingsChange_yes,
570 IDEWorkbenchMessages.SystemSettingsChange_no },
571 1).open() == Window.OK) {
572 PlatformUI.getWorkbench().restart();
582 * @see org.eclipse.ui.application.WorkbenchAdvisor#postShutdown
585 public void postShutdown() {
586 if (activityHelper != null) {
587 activityHelper.shutdown();
588 activityHelper = null;
590 if (idleHelper != null) {
591 idleHelper.shutdown();
594 if (workspaceUndoMonitor != null) {
595 workspaceUndoMonitor.shutdown();
596 workspaceUndoMonitor = null;
598 if (IDEWorkbenchPlugin.getPluginWorkspace() != null) {
599 disconnectFromWorkspace();
606 * @see org.eclipse.ui.application.WorkbenchAdvisor#preShutdown()
609 public boolean preShutdown() {
610 Display.getCurrent().removeListener(SWT.Settings,
611 settingsChangeListener);
612 return super.preShutdown();
616 * Return true if the intro plugin is present and false otherwise.
620 public boolean hasIntro() {
621 return getWorkbenchConfigurer().getWorkbench().getIntroManager()
625 private void refreshFromLocal() {
626 String[] commandLineArgs = Platform.getCommandLineArgs();
627 IPreferenceStore store = IDEWorkbenchPlugin.getDefault()
628 .getPreferenceStore();
629 boolean refresh = store
630 .getBoolean(IDEInternalPreferences.REFRESH_WORKSPACE_ON_STARTUP);
635 // Do not refresh if it was already done by core on startup.
636 for (int i = 0; i < commandLineArgs.length; i++) {
637 if (commandLineArgs[i].equalsIgnoreCase("-refresh")) { //$NON-NLS-1$
642 final IContainer root = ResourcesPlugin.getWorkspace().getRoot();
643 Job job = new WorkspaceJob(IDEWorkbenchMessages.Workspace_refreshing) {
645 public IStatus runInWorkspace(IProgressMonitor monitor)
646 throws CoreException {
647 root.refreshLocal(IResource.DEPTH_INFINITE, monitor);
648 return Status.OK_STATUS;
655 private static class CancelableProgressMonitorWrapper extends ProgressMonitorWrapper {
656 private double total = 0;
657 private ProgressMonitorJobsDialog dialog;
659 CancelableProgressMonitorWrapper(IProgressMonitor monitor,
660 ProgressMonitorJobsDialog dialog) {
662 this.dialog = dialog;
667 * @see org.eclipse.core.runtime.ProgressMonitorWrapper#internalWorked(double)
669 public void internalWorked(double work) {
670 super.internalWorked(work);
672 updateProgressDetails();
677 * @see org.eclipse.core.runtime.ProgressMonitorWrapper#worked(int)
679 public void worked(int work) {
682 updateProgressDetails();
685 public void beginTask(String name, int totalWork) {
686 super.beginTask(name, totalWork);
687 subTask(IDEWorkbenchMessages.IDEWorkbenchAdvisor_preHistoryCompaction);
690 private void updateProgressDetails() {
691 if (!isCanceled() && Math.abs(total - 4.0) < 0.0001 /* right before history compacting */) {
692 subTask(IDEWorkbenchMessages.IDEWorkbenchAdvisor_cancelHistoryPruning);
693 dialog.setCancelable(true);
695 if (Math.abs(total - 5.0) < 0.0001 /* history compacting finished */) {
696 subTask(IDEWorkbenchMessages.IDEWorkbenchAdvisor_postHistoryCompaction);
697 dialog.setCancelable(false);
702 private static class CancelableProgressMonitorJobsDialog extends ProgressMonitorJobsDialog {
704 public CancelableProgressMonitorJobsDialog(Shell parent) {
710 * @see org.eclipse.ui.internal.progress.ProgressMonitorJobsDialog#createDetailsButton(org.eclipse.swt.widgets.Composite)
712 protected void createButtonsForButtonBar(Composite parent) {
713 super.createButtonsForButtonBar(parent);
714 registerCancelButtonListener();
717 public void registerCancelButtonListener() {
718 cancel.addSelectionListener(new SelectionAdapter() {
719 public void widgetSelected(SelectionEvent e) {
720 subTaskLabel.setText(""); //$NON-NLS-1$
727 final IRunnableWithProgress platformShutdownRunnable = new IRunnableWithProgress() {
730 * the progress monitor to use for reporting progress to the
731 * user, or <code>null</code> indicating that no progress
732 * should be reported and the operation cannot be cancelled.
735 public void run(IProgressMonitor monitor) {
736 SubMonitor progress = SubMonitor.convert(monitor, SHUT_DOWN_PLATFORM_TASK, 100);
739 progress.subTask("Platform");
740 SimanticsPlatform.INSTANCE.shutdown(progress.newChild(50));
741 } catch (PlatformException e) {
742 Activator.logError("Problems encountered while shutting down Simantics platform, see exception for details.", e);
745 progress.subTask("Remaining database connections");
746 SimanticsUI.closeSessions();
748 TimedSessionCache.close();
751 progress.subTask("Thread pools");
752 ThreadUtils.shutdown();
753 ExecutorWorker.shutdown();
756 progress.subTask("Clear index status");
758 // Everything ok, clear index dirty state.
759 DatabaseIndexing.clearAllDirty();
760 } catch (IOException e) {
761 Activator.logError("Problems encountered while refreshing database index states, see exception for details.", e);
765 progress.setWorkRemaining(0);
767 if (monitor != null) {
775 * Disconnect from the workspace and close ProCore sessions.
777 private void disconnectFromWorkspace() {
778 // save the workspace
779 final MultiStatus status = new MultiStatus(
780 IDEWorkbenchPlugin.IDE_WORKBENCH, 1,
781 IDEWorkbenchMessages.ProblemSavingWorkbench, null);
783 final ProgressMonitorJobsDialog p = new CancelableProgressMonitorJobsDialog(
786 final boolean applyPolicy = ResourcesPlugin.getWorkspace()
787 .getDescription().isApplyFileStatePolicy();
789 final IRunnableWithProgress workspaceShutdownRunnable = new IRunnableWithProgress() {
791 public void run(IProgressMonitor monitor) {
793 status.merge(((Workspace) ResourcesPlugin.getWorkspace()).save(true, true, monitor));
794 } catch (CoreException e) {
795 status.merge(e.getStatus());
800 IRunnableWithProgress shutdownRunnable = new IRunnableWithProgress() {
802 public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
804 monitor = new CancelableProgressMonitorWrapper(
807 SubMonitor progress = SubMonitor.convert(monitor, SHUT_DOWN_TASK, 2);
809 workspaceShutdownRunnable.run(progress.newChild(1, SubMonitor.SUPPRESS_NONE));
810 platformShutdownRunnable.run(progress.newChild(1, SubMonitor.SUPPRESS_NONE));
818 new ProgressMonitorJobsDialog(null).run(true, false, shutdownRunnable);
819 } catch (InvocationTargetException e) {
820 status.merge(new Status(IStatus.ERROR,
821 IDEWorkbenchPlugin.IDE_WORKBENCH, 1,
822 IDEWorkbenchMessages.InternalError, e.getTargetException()));
823 } catch (InterruptedException e) {
824 status.merge(new Status(IStatus.ERROR,
825 IDEWorkbenchPlugin.IDE_WORKBENCH, 1,
826 IDEWorkbenchMessages.InternalError, e));
828 ErrorDialog.openError(null,
829 IDEWorkbenchMessages.ProblemsSavingWorkspace, null, status,
830 IStatus.ERROR | IStatus.WARNING);
831 if (!status.isOK()) {
832 IDEWorkbenchPlugin.log(
833 IDEWorkbenchMessages.ProblemsSavingWorkspace, status);
840 * @see org.eclipse.ui.application.WorkbenchAdvisor#getDefaultPageInput
843 public IAdaptable getDefaultPageInput() {
844 return ResourcesPlugin.getWorkspace().getRoot();
850 * @see org.eclipse.ui.application.WorkbenchAdvisor
853 public String getInitialWindowPerspectiveId() {
854 int index = PlatformUI.getWorkbench().getWorkbenchWindowCount() - 1;
856 String perspectiveId = null;
857 AboutInfo[] welcomeInfos = getWelcomePerspectiveInfos();
858 if (index >= 0 && welcomeInfos != null && index < welcomeInfos.length) {
859 perspectiveId = welcomeInfos[index].getWelcomePerspectiveId();
862 if (perspectiveId == null && args.contains(SimanticsArguments.PERSPECTIVE)) {
863 String id = args.get(SimanticsArguments.PERSPECTIVE);
864 IPerspectiveDescriptor perspective = PlatformUI.getWorkbench().getPerspectiveRegistry().findPerspectiveWithId(id);
865 if (perspective != null)
869 if (perspectiveId == null) {
870 IProject project = Simantics.peekProject();
872 perspectiveId = project.getHint(ProjectKeys.DEFAULT_PERSPECTIVE);
875 //System.out.println("Initial perspective: " + perspectiveId);
877 return perspectiveId;
881 * Returns the map of versioned feature ids -> info object for all installed
882 * features. The format of the versioned feature id (the key of the map) is
883 * featureId + ":" + versionId.
885 * @return map of versioned feature ids -> info object (key type:
886 * <code>String</code>, value type: <code>AboutInfo</code>)
889 private Map<String, AboutInfo> computeBundleGroupMap() {
890 // use tree map to get predicable order
891 Map<String, AboutInfo> ids = new TreeMap<String, AboutInfo>();
893 IBundleGroupProvider[] providers = Platform.getBundleGroupProviders();
894 for (int i = 0; i < providers.length; ++i) {
895 IBundleGroup[] groups = providers[i].getBundleGroups();
896 for (int j = 0; j < groups.length; ++j) {
897 IBundleGroup group = groups[j];
898 AboutInfo info = new AboutInfo(group);
900 String version = info.getVersionId();
901 version = version == null ? "0.0.0" //$NON-NLS-1$
902 : new Version(version).toString();
903 String versionedFeature = group.getIdentifier() + ":" + version; //$NON-NLS-1$
905 ids.put(versionedFeature, info);
913 * Returns the ordered map of versioned feature ids -> AboutInfo that are
914 * new for this session.
916 * @return ordered map of versioned feature ids (key type:
917 * <code>String</code>) -> infos (value type:
918 * <code>AboutInfo</code>).
920 public Map<String, AboutInfo> getNewlyAddedBundleGroups() {
921 if (newlyAddedBundleGroups == null) {
922 newlyAddedBundleGroups = createNewBundleGroupsMap();
924 return newlyAddedBundleGroups;
928 * Updates the old features setting and returns a map of new features.
930 private Map<String, AboutInfo> createNewBundleGroupsMap() {
931 // retrieve list of installed bundle groups from last session
932 IDialogSettings settings = IDEWorkbenchPlugin.getDefault()
933 .getDialogSettings();
934 String[] previousFeaturesArray = settings.getArray(INSTALLED_FEATURES);
936 // get a map of currently installed bundle groups and store it for next
938 Map<String, AboutInfo> bundleGroups = computeBundleGroupMap();
939 String[] currentFeaturesArray = new String[bundleGroups.size()];
940 bundleGroups.keySet().toArray(currentFeaturesArray);
941 settings.put(INSTALLED_FEATURES, currentFeaturesArray);
943 // remove the previously known from the current set
944 if (previousFeaturesArray != null) {
945 for (int i = 0; i < previousFeaturesArray.length; ++i) {
946 bundleGroups.remove(previousFeaturesArray[i]);
954 * Declares all IDE-specific workbench images. This includes both "shared"
955 * images (named in {@link IDE.SharedImages}) and internal images (named in
956 * {@link org.eclipse.ui.internal.ide.IDEInternalWorkbenchImages}).
958 * @see IWorkbenchConfigurer#declareImage
960 private void declareWorkbenchImages() {
962 final String ICONS_PATH = "$nl$/icons/full/";//$NON-NLS-1$
963 final String PATH_ELOCALTOOL = ICONS_PATH + "elcl16/"; // Enabled //$NON-NLS-1$
967 final String PATH_DLOCALTOOL = ICONS_PATH + "dlcl16/"; // Disabled //$NON-NLS-1$
971 final String PATH_ETOOL = ICONS_PATH + "etool16/"; // Enabled toolbar //$NON-NLS-1$
974 final String PATH_DTOOL = ICONS_PATH + "dtool16/"; // Disabled toolbar //$NON-NLS-1$
977 final String PATH_OBJECT = ICONS_PATH + "obj16/"; // Model object //$NON-NLS-1$
980 final String PATH_WIZBAN = ICONS_PATH + "wizban/"; // Wizard //$NON-NLS-1$
984 Bundle ideBundle = Platform.getBundle(IDEWorkbenchPlugin.IDE_WORKBENCH);
986 declareWorkbenchImage(ideBundle,
987 IDEInternalWorkbenchImages.IMG_ETOOL_BUILD_EXEC, PATH_ETOOL
988 + "build_exec.gif", false); //$NON-NLS-1$
989 declareWorkbenchImage(ideBundle,
990 IDEInternalWorkbenchImages.IMG_ETOOL_BUILD_EXEC_HOVER,
991 PATH_ETOOL + "build_exec.gif", false); //$NON-NLS-1$
992 declareWorkbenchImage(ideBundle,
993 IDEInternalWorkbenchImages.IMG_ETOOL_BUILD_EXEC_DISABLED,
994 PATH_DTOOL + "build_exec.gif", false); //$NON-NLS-1$
996 declareWorkbenchImage(ideBundle,
997 IDEInternalWorkbenchImages.IMG_ETOOL_SEARCH_SRC, PATH_ETOOL
998 + "search_src.gif", false); //$NON-NLS-1$
999 declareWorkbenchImage(ideBundle,
1000 IDEInternalWorkbenchImages.IMG_ETOOL_SEARCH_SRC_HOVER,
1001 PATH_ETOOL + "search_src.gif", false); //$NON-NLS-1$
1002 declareWorkbenchImage(ideBundle,
1003 IDEInternalWorkbenchImages.IMG_ETOOL_SEARCH_SRC_DISABLED,
1004 PATH_DTOOL + "search_src.gif", false); //$NON-NLS-1$
1006 declareWorkbenchImage(ideBundle,
1007 IDEInternalWorkbenchImages.IMG_ETOOL_NEXT_NAV, PATH_ETOOL
1008 + "next_nav.gif", false); //$NON-NLS-1$
1010 declareWorkbenchImage(ideBundle,
1011 IDEInternalWorkbenchImages.IMG_ETOOL_PREVIOUS_NAV, PATH_ETOOL
1012 + "prev_nav.gif", false); //$NON-NLS-1$
1014 declareWorkbenchImage(ideBundle,
1015 IDEInternalWorkbenchImages.IMG_WIZBAN_NEWPRJ_WIZ, PATH_WIZBAN
1016 + "newprj_wiz.png", false); //$NON-NLS-1$
1017 declareWorkbenchImage(ideBundle,
1018 IDEInternalWorkbenchImages.IMG_WIZBAN_NEWFOLDER_WIZ,
1019 PATH_WIZBAN + "newfolder_wiz.png", false); //$NON-NLS-1$
1020 declareWorkbenchImage(ideBundle,
1021 IDEInternalWorkbenchImages.IMG_WIZBAN_NEWFILE_WIZ, PATH_WIZBAN
1022 + "newfile_wiz.png", false); //$NON-NLS-1$
1024 declareWorkbenchImage(ideBundle,
1025 IDEInternalWorkbenchImages.IMG_WIZBAN_IMPORTDIR_WIZ,
1026 PATH_WIZBAN + "importdir_wiz.png", false); //$NON-NLS-1$
1027 declareWorkbenchImage(ideBundle,
1028 IDEInternalWorkbenchImages.IMG_WIZBAN_IMPORTZIP_WIZ,
1029 PATH_WIZBAN + "importzip_wiz.png", false); //$NON-NLS-1$
1031 declareWorkbenchImage(ideBundle,
1032 IDEInternalWorkbenchImages.IMG_WIZBAN_EXPORTDIR_WIZ,
1033 PATH_WIZBAN + "exportdir_wiz.png", false); //$NON-NLS-1$
1034 declareWorkbenchImage(ideBundle,
1035 IDEInternalWorkbenchImages.IMG_WIZBAN_EXPORTZIP_WIZ,
1036 PATH_WIZBAN + "exportzip_wiz.png", false); //$NON-NLS-1$
1038 declareWorkbenchImage(ideBundle,
1039 IDEInternalWorkbenchImages.IMG_WIZBAN_RESOURCEWORKINGSET_WIZ,
1040 PATH_WIZBAN + "workset_wiz.png", false); //$NON-NLS-1$
1042 declareWorkbenchImage(ideBundle,
1043 IDEInternalWorkbenchImages.IMG_DLGBAN_SAVEAS_DLG, PATH_WIZBAN
1044 + "saveas_wiz.png", false); //$NON-NLS-1$
1046 declareWorkbenchImage(ideBundle,
1047 IDEInternalWorkbenchImages.IMG_DLGBAN_QUICKFIX_DLG, PATH_WIZBAN
1048 + "quick_fix.png", false); //$NON-NLS-1$
1050 declareWorkbenchImage(ideBundle, IDE.SharedImages.IMG_OBJ_PROJECT,
1051 PATH_OBJECT + "prj_obj.gif", true); //$NON-NLS-1$
1052 declareWorkbenchImage(ideBundle,
1053 IDE.SharedImages.IMG_OBJ_PROJECT_CLOSED, PATH_OBJECT
1054 + "cprj_obj.gif", true); //$NON-NLS-1$
1055 declareWorkbenchImage(ideBundle, IDE.SharedImages.IMG_OPEN_MARKER,
1056 PATH_ELOCALTOOL + "gotoobj_tsk.gif", true); //$NON-NLS-1$
1058 declareWorkbenchImage(ideBundle,
1059 IDEInternalWorkbenchImages.IMG_ELCL_QUICK_FIX_ENABLED,
1060 PATH_ELOCALTOOL + "smartmode_co.gif", true); //$NON-NLS-1$
1062 declareWorkbenchImage(ideBundle,
1063 IDEInternalWorkbenchImages.IMG_DLCL_QUICK_FIX_DISABLED,
1064 PATH_DLOCALTOOL + "smartmode_co.gif", true); //$NON-NLS-1$
1067 // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_HPRIO_TSK,
1068 // PATH_OBJECT+"hprio_tsk.gif");
1069 // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_MPRIO_TSK,
1070 // PATH_OBJECT+"mprio_tsk.gif");
1071 // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_LPRIO_TSK,
1072 // PATH_OBJECT+"lprio_tsk.gif");
1074 declareWorkbenchImage(ideBundle, IDE.SharedImages.IMG_OBJS_TASK_TSK,
1075 PATH_OBJECT + "taskmrk_tsk.gif", true); //$NON-NLS-1$
1076 declareWorkbenchImage(ideBundle, IDE.SharedImages.IMG_OBJS_BKMRK_TSK,
1077 PATH_OBJECT + "bkmrk_tsk.gif", true); //$NON-NLS-1$
1079 declareWorkbenchImage(ideBundle,
1080 IDEInternalWorkbenchImages.IMG_OBJS_COMPLETE_TSK, PATH_OBJECT
1081 + "complete_tsk.gif", true); //$NON-NLS-1$
1082 declareWorkbenchImage(ideBundle,
1083 IDEInternalWorkbenchImages.IMG_OBJS_INCOMPLETE_TSK, PATH_OBJECT
1084 + "incomplete_tsk.gif", true); //$NON-NLS-1$
1085 declareWorkbenchImage(ideBundle,
1086 IDEInternalWorkbenchImages.IMG_OBJS_WELCOME_ITEM, PATH_OBJECT
1087 + "welcome_item.gif", true); //$NON-NLS-1$
1088 declareWorkbenchImage(ideBundle,
1089 IDEInternalWorkbenchImages.IMG_OBJS_WELCOME_BANNER, PATH_OBJECT
1090 + "welcome_banner.gif", true); //$NON-NLS-1$
1091 declareWorkbenchImage(ideBundle,
1092 IDEInternalWorkbenchImages.IMG_OBJS_ERROR_PATH, PATH_OBJECT
1093 + "error_tsk.gif", true); //$NON-NLS-1$
1094 declareWorkbenchImage(ideBundle,
1095 IDEInternalWorkbenchImages.IMG_OBJS_WARNING_PATH, PATH_OBJECT
1096 + "warn_tsk.gif", true); //$NON-NLS-1$
1097 declareWorkbenchImage(ideBundle,
1098 IDEInternalWorkbenchImages.IMG_OBJS_INFO_PATH, PATH_OBJECT
1099 + "info_tsk.gif", true); //$NON-NLS-1$
1101 declareWorkbenchImage(ideBundle,
1102 IDEInternalWorkbenchImages.IMG_LCL_FLAT_LAYOUT, PATH_ELOCALTOOL
1103 + "flatLayout.gif", true); //$NON-NLS-1$
1104 declareWorkbenchImage(ideBundle,
1105 IDEInternalWorkbenchImages.IMG_LCL_HIERARCHICAL_LAYOUT,
1106 PATH_ELOCALTOOL + "hierarchicalLayout.gif", true); //$NON-NLS-1$
1107 declareWorkbenchImage(ideBundle,
1108 IDEInternalWorkbenchImages.IMG_ETOOL_PROBLEM_CATEGORY,
1109 PATH_ETOOL + "problem_category.gif", true); //$NON-NLS-1$
1111 declareWorkbenchImage(ideBundle,
1112 IDEInternalWorkbenchImages.IMG_LCL_LINKTO_HELP, PATH_ELOCALTOOL
1113 + "linkto_help.gif", false); //$NON-NLS-1$
1116 // synchronization indicator objects
1117 // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_WBET_STAT,
1118 // PATH_OVERLAY+"wbet_stat.gif");
1119 // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_SBET_STAT,
1120 // PATH_OVERLAY+"sbet_stat.gif");
1121 // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_CONFLICT_STAT,
1122 // PATH_OVERLAY+"conflict_stat.gif");
1124 // content locality indicator objects
1125 // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_NOTLOCAL_STAT,
1126 // PATH_STAT+"notlocal_stat.gif");
1127 // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_LOCAL_STAT,
1128 // PATH_STAT+"local_stat.gif");
1129 // declareRegistryImage(IDEInternalWorkbenchImages.IMG_OBJS_FILLLOCAL_STAT,
1130 // PATH_STAT+"filllocal_stat.gif");
1134 * Declares an IDE-specific workbench image.
1136 * @param symbolicName
1137 * the symbolic name of the image
1139 * the path of the image file; this path is relative to the base
1140 * of the IDE plug-in
1142 * <code>true</code> if this is a shared image, and
1143 * <code>false</code> if this is not a shared image
1144 * @see IWorkbenchConfigurer#declareImage
1146 private void declareWorkbenchImage(Bundle ideBundle, String symbolicName,
1147 String path, boolean shared) {
1148 URL url = FileLocator.find(ideBundle, new Path(path), null);
1149 ImageDescriptor desc = ImageDescriptor.createFromURL(url);
1150 getWorkbenchConfigurer().declareImage(symbolicName, desc, shared);
1156 * @see org.eclipse.ui.application.WorkbenchAdvisor#getMainPreferencePageId
1159 public String getMainPreferencePageId() {
1160 // indicate that we want the Workench preference page to be prominent
1161 return WORKBENCH_PREFERENCE_CATEGORY_ID;
1165 * @return the workspace location string, or <code>null</code> if the
1166 * location is not being shown
1168 public String getWorkspaceLocation() {
1169 // read command line, which has priority
1170 IEclipseContext context = getWorkbenchConfigurer().getWorkbench().getService(IEclipseContext.class);
1171 String location = context != null ? (String) context.get(E4Workbench.FORCED_SHOW_LOCATION) : null;
1172 if (location != null) {
1175 // read the preference
1176 if (IDEWorkbenchPlugin.getDefault().getPreferenceStore().getBoolean(IDEInternalPreferences.SHOW_LOCATION)) {
1177 return Platform.getLocation().toOSString();
1183 * @return the welcome perspective infos, or <code>null</code> if none or
1184 * if they should be ignored due to the new intro being present
1186 public AboutInfo[] getWelcomePerspectiveInfos() {
1187 if (welcomePerspectiveInfos == null) {
1188 // support old welcome perspectives if intro plugin is not present
1190 Map<String, AboutInfo> m = getNewlyAddedBundleGroups();
1191 ArrayList<AboutInfo> list = new ArrayList<AboutInfo>(m.size());
1192 for (Iterator<AboutInfo> i = m.values().iterator(); i.hasNext();) {
1193 AboutInfo info = i.next();
1194 if (info != null && info.getWelcomePerspectiveId() != null
1195 && info.getWelcomePageURL() != null) {
1199 welcomePerspectiveInfos = new AboutInfo[list.size()];
1200 list.toArray(welcomePerspectiveInfos);
1203 return welcomePerspectiveInfos;
1209 * @see org.eclipse.ui.application.WorkbenchAdvisor#getWorkbenchErrorHandler()
1212 public AbstractStatusHandler getWorkbenchErrorHandler() {
1213 if (ideWorkbenchErrorHandler == null) {
1214 ideWorkbenchErrorHandler = new IDEWorkbenchErrorHandler(
1215 getWorkbenchConfigurer());
1217 return ideWorkbenchErrorHandler;
1221 * @see org.eclipse.ui.application.WorkbenchAdvisor#eventLoopIdle(org.eclipse.swt.widgets.Display)
1224 public void eventLoopIdle(Display display) {
1225 if (delayedEventsProcessor != null)
1226 delayedEventsProcessor.catchUp(display);
1227 super.eventLoopIdle(display);