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;
15 import java.io.FileInputStream;
16 import java.io.FileOutputStream;
17 import java.io.IOException;
18 import java.io.OutputStream;
19 import java.net.MalformedURLException;
22 import java.util.Properties;
24 import org.eclipse.core.runtime.IConfigurationElement;
25 import org.eclipse.core.runtime.IExecutableExtension;
26 import org.eclipse.core.runtime.IStatus;
27 import org.eclipse.core.runtime.Platform;
28 import org.eclipse.core.runtime.Status;
29 import org.eclipse.equinox.app.IApplication;
30 import org.eclipse.equinox.app.IApplicationContext;
31 import org.eclipse.jface.dialogs.Dialog;
32 import org.eclipse.jface.dialogs.MessageDialog;
33 import org.eclipse.osgi.service.datalocation.Location;
34 import org.eclipse.osgi.util.NLS;
35 import org.eclipse.swt.SWT;
36 import org.eclipse.swt.widgets.Composite;
37 import org.eclipse.swt.widgets.Control;
38 import org.eclipse.swt.widgets.Display;
39 import org.eclipse.swt.widgets.MessageBox;
40 import org.eclipse.swt.widgets.Shell;
41 import org.eclipse.ui.IWorkbench;
42 import org.eclipse.ui.PlatformUI;
43 import org.eclipse.ui.application.WorkbenchAdvisor;
44 import org.eclipse.ui.internal.WorkbenchPlugin;
45 import org.eclipse.ui.internal.ide.ChooseWorkspaceData;
46 import org.eclipse.ui.internal.ide.ChooseWorkspaceDialog;
47 import org.eclipse.ui.internal.ide.IDEWorkbenchMessages;
48 import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin;
49 import org.eclipse.ui.internal.ide.StatusUtil;
50 import org.simantics.application.arguments.ApplicationUtils;
51 import org.simantics.application.arguments.Arguments;
52 import org.simantics.application.arguments.IArgumentFactory;
53 import org.simantics.application.arguments.IArguments;
54 import org.simantics.application.arguments.SimanticsArguments;
55 import org.simantics.db.management.ISessionContextProvider;
56 import org.simantics.db.management.ISessionContextProviderSource;
57 import org.simantics.db.management.SessionContextProvider;
58 import org.simantics.db.management.SingleSessionContextProviderSource;
59 import org.simantics.ui.SimanticsUI;
60 import org.simantics.utils.ui.BundleUtils;
64 * The "main program" for the Eclipse IDE.
68 public class SimanticsWorkbenchApplication implements IApplication, IExecutableExtension {
71 * The name of the folder containing metadata information for the workspace.
73 public static final String METADATA_FOLDER = ".metadata"; //$NON-NLS-1$
75 private static final String VERSION_FILENAME = "version.ini"; //$NON-NLS-1$
77 private static final String WORKSPACE_VERSION_KEY = "org.eclipse.core.runtime"; //$NON-NLS-1$
79 private static final String WORKSPACE_VERSION_VALUE = "1"; //$NON-NLS-1$
81 private static final String PROP_EXIT_CODE = "eclipse.exitcode"; //$NON-NLS-1$
84 * A special return code that will be recognized by the launcher and used to
85 * restart the workbench.
87 private static final Integer EXIT_RELAUNCH = new Integer(24);
90 * A special return code that will be recognized by the PDE launcher and used to
91 * show an error dialog if the workspace is locked.
93 private static final Integer EXIT_WORKSPACE_LOCKED = new Integer(15);
96 * Creates a new IDE application.
98 public SimanticsWorkbenchApplication() {
99 // There is nothing to do for WorkbenchApplication
102 public WorkbenchAdvisor createWorkbenchAdvisor(IArguments args, DelayedEventsProcessor processor) {
103 return new SimanticsWorkbenchAdvisor(args, processor);
107 * @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext context)
110 public Object start(IApplicationContext appContext) throws Exception {
111 ApplicationUtils.loadSystemProperties(BundleUtils.find(Activator.PLUGIN_ID, "system.properties"));
112 IArguments args = parseArguments((String[]) appContext.getArguments().get(IApplicationContext.APPLICATION_ARGS));
114 Display display = createDisplay();
115 // processor must be created before we start event loop
116 DelayedEventsProcessor processor = new DelayedEventsProcessor(display);
119 Object argCheck = verifyArguments(args);
120 if (argCheck != null)
123 // look and see if there's a splash shell we can parent off of
124 Shell shell = WorkbenchPlugin.getSplashShell(display);
126 // should should set the icon and message for this shell to be the
127 // same as the chooser dialog - this will be the guy that lives in
128 // the task bar and without these calls you'd have the default icon
130 shell.setText(ChooseWorkspaceDialog.getWindowTitle());
131 shell.setImages(Dialog.getDefaultImages());
134 Object instanceLocationCheck = checkInstanceLocation(shell, appContext.getArguments(), args);
135 if (instanceLocationCheck != null) {
136 WorkbenchPlugin.unsetSplashShell(display);
137 Platform.endSplash();
138 return instanceLocationCheck;
141 final ISessionContextProvider provider = new SessionContextProvider(null);
142 final ISessionContextProviderSource contextProviderSource = new SingleSessionContextProviderSource(provider);
143 //final ISessionContextProviderSource contextProviderSource = new WorkbenchWindowSessionContextProviderSource(PlatformUI.getWorkbench());
144 SimanticsUI.setSessionContextProviderSource(contextProviderSource);
145 org.simantics.db.layer0.internal.SimanticsInternal.setSessionContextProviderSource(contextProviderSource);
146 org.simantics.Simantics.setSessionContextProviderSource(contextProviderSource);
148 // create the workbench with this advisor and run it until it exits
149 // N.B. createWorkbench remembers the advisor, and also registers
150 // the workbench globally so that all UI plug-ins can find it using
151 // PlatformUI.getWorkbench() or AbstractUIPlugin.getWorkbench()
152 int returnCode = PlatformUI.createAndRunWorkbench(display,
153 createWorkbenchAdvisor(args, processor));
155 // the workbench doesn't support relaunch yet (bug 61809) so
156 // for now restart is used, and exit data properties are checked
157 // here to substitute in the relaunch return code if needed
158 if (returnCode != PlatformUI.RETURN_RESTART) {
162 // if the exit code property has been set to the relaunch code, then
163 // return that code now, otherwise this is a normal restart
164 return EXIT_RELAUNCH.equals(Integer.getInteger(PROP_EXIT_CODE)) ? EXIT_RELAUNCH
167 if (display != null) {
170 Location instanceLoc = Platform.getInstanceLocation();
171 if (instanceLoc != null)
172 instanceLoc.release();
176 /*************************************************************************/
178 private IArguments parseArguments(String[] args) {
179 IArgumentFactory<?>[] accepted = {
180 SimanticsArguments.RECOVERY_POLICY_FIX_ERRORS,
181 SimanticsArguments.ONTOLOGY_RECOVERY_POLICY_REINSTALL,
182 SimanticsArguments.DEFAULT_WORKSPACE_LOCATION,
183 SimanticsArguments.WORKSPACE_CHOOSER,
184 SimanticsArguments.WORKSPACE_NO_REMEMBER,
185 SimanticsArguments.PERSPECTIVE,
186 SimanticsArguments.SERVER,
187 SimanticsArguments.NEW_MODEL,
188 SimanticsArguments.EXPERIMENT,
189 SimanticsArguments.DISABLE_INDEX,
190 SimanticsArguments.DATABASE_ID,
192 IArguments result = Arguments.parse(args, accepted);
196 private Object verifyArguments(IArguments args) {
197 StringBuilder report = new StringBuilder();
199 // if (args.contains(SimanticsArguments.NEW_PROJECT)) {
200 // if (args.contains(SimanticsArguments.PROJECT)) {
201 // exclusiveArguments(report, SimanticsArguments.PROJECT, SimanticsArguments.NEW_PROJECT);
203 // // Must have a server to checkout from when creating a new
204 // // project right from the beginning.
205 // if (!args.contains(SimanticsArguments.SERVER)) {
206 // missingArgument(report, SimanticsArguments.SERVER);
208 // } else if (args.contains(SimanticsArguments.PROJECT)) {
209 // // To load a project, a server must be defined to checkout from
210 // if (!args.contains(SimanticsArguments.SERVER)) {
211 // missingArgument(report, SimanticsArguments.SERVER);
215 // NEW_MODEL and MODEL arguments are optional
216 // EXPERIMENT argument is optional
218 String result = report.toString();
219 boolean valid = result.length() == 0;
222 String msg = NLS.bind(Messages.Application_1, result);
223 MessageDialog.openInformation(null, Messages.Application_2, msg);
225 return valid ? null : EXIT_OK;
228 // private void exclusiveArguments(StringBuilder sb, IArgumentFactory<?> arg1, IArgumentFactory<?> arg2) {
229 // sb.append(NLS.bind(Messages.Application_3, arg1.getArgument(), arg2.getArgument()));
233 // private void missingArgument(StringBuilder sb, IArgumentFactory<?> arg) {
234 // sb.append(NLS.bind(Messages.Application_0, arg.getArgument()));
238 /*************************************************************************/
241 * Creates the display used by the application.
243 * @return the display used by the application
245 protected Display createDisplay() {
246 return PlatformUI.createDisplay();
250 * @see org.eclipse.core.runtime.IExecutableExtension#setInitializationData(org.eclipse.core.runtime.IConfigurationElement, java.lang.String, java.lang.Object)
253 public void setInitializationData(IConfigurationElement config,
254 String propertyName, Object data) {
255 // There is nothing to do for ProConfApplication
259 * Return true if a valid workspace path has been set and false otherwise.
260 * Prompt for and set the path if possible and required.
261 * @param applicationArguments
263 * @return true if a valid instance location has been set and false
266 private Object checkInstanceLocation(Shell shell, Map<?,?> applicationArguments, IArguments args) {
267 // -data @none was specified but an ide requires workspace
268 Location instanceLoc = Platform.getInstanceLocation();
269 if (instanceLoc == null) {
273 IDEWorkbenchMessages.IDEApplication_workspaceMandatoryTitle,
274 IDEWorkbenchMessages.IDEApplication_workspaceMandatoryMessage);
278 // -data "/valid/path", workspace already set
279 // This information is stored in configuration/.settings/org.eclipse.ui.ide.prefs
280 if (instanceLoc.isSet()) {
281 // make sure the meta data version is compatible (or the user has
282 // chosen to overwrite it).
283 if (!checkValidWorkspace(shell, instanceLoc.getURL())) {
287 // at this point its valid, so try to lock it and update the
288 // metadata version information if successful
290 if (instanceLoc.lock()) {
291 writeWorkspaceVersion();
295 // we failed to create the directory.
296 // Two possibilities:
297 // 1. directory is already in use
298 // 2. directory could not be created
299 File workspaceDirectory = new File(instanceLoc.getURL().getFile());
300 if (workspaceDirectory.exists()) {
301 if (isDevLaunchMode(applicationArguments)) {
302 return EXIT_WORKSPACE_LOCKED;
304 MessageDialog.openError(
306 IDEWorkbenchMessages.IDEApplication_workspaceCannotLockTitle,
307 IDEWorkbenchMessages.IDEApplication_workspaceCannotLockMessage);
309 MessageDialog.openError(
311 IDEWorkbenchMessages.IDEApplication_workspaceCannotBeSetTitle,
312 IDEWorkbenchMessages.IDEApplication_workspaceCannotBeSetMessage);
314 } catch (IOException e) {
315 IDEWorkbenchPlugin.log("Could not obtain lock for workspace location", //$NON-NLS-1$
320 IDEWorkbenchMessages.InternalError,
326 // -data @noDefault or -data not specified, prompt and set
327 ChooseWorkspaceData launchData = null;
328 if (args.contains(SimanticsArguments.DEFAULT_WORKSPACE_LOCATION)) {
329 launchData = new ChooseWorkspaceData(args.get(SimanticsArguments.DEFAULT_WORKSPACE_LOCATION));
331 launchData = new ChooseWorkspaceData(instanceLoc.getDefault());
334 boolean force = args.contains(SimanticsArguments.WORKSPACE_CHOOSER);
335 boolean suppressAskAgain = args.contains(SimanticsArguments.WORKSPACE_NO_REMEMBER);
338 URL workspaceUrl = promptForWorkspace(shell, launchData, force, suppressAskAgain);
339 if (workspaceUrl == null) {
343 // if there is an error with the first selection, then force the
344 // dialog to open to give the user a chance to correct
348 // the operation will fail if the url is not a valid
349 // instance data area, so other checking is unneeded
350 if (instanceLoc.setURL(workspaceUrl, true)) {
351 launchData.writePersistedData();
352 writeWorkspaceVersion();
355 } catch (IllegalStateException e) {
359 IDEWorkbenchMessages.IDEApplication_workspaceCannotBeSetTitle,
360 IDEWorkbenchMessages.IDEApplication_workspaceCannotBeSetMessage);
364 // by this point it has been determined that the workspace is
365 // already in use -- force the user to choose again
366 MessageDialog.openError(shell, IDEWorkbenchMessages.IDEApplication_workspaceInUseTitle,
367 IDEWorkbenchMessages.IDEApplication_workspaceInUseMessage);
371 private static boolean isDevLaunchMode(Map<?,?> args) {
372 // see org.eclipse.pde.internal.core.PluginPathFinder.isDevLaunchMode()
373 if (Boolean.getBoolean("eclipse.pde.launch")) //$NON-NLS-1$
375 return args.containsKey("-pdelaunch"); //$NON-NLS-1$
378 private static class ChooseSimanticsWorkspaceDialog extends ChooseWorkspaceDialog {
380 public ChooseSimanticsWorkspaceDialog(Shell parentShell, ChooseWorkspaceData launchData, boolean suppressAskAgain, boolean centerOnMonitor) {
381 super(parentShell, launchData, suppressAskAgain, centerOnMonitor);
385 protected void configureShell(Shell shell) {
386 super.configureShell(shell);
387 // Use product name in shell title instead of generic "Eclipse Launcher"
388 shell.setText(getWindowTitle());
393 * Open a workspace selection dialog on the argument shell, populating the
394 * argument data with the user's selection. Perform first level validation
395 * on the selection by comparing the version information. This method does
396 * not examine the runtime state (e.g., is the workspace already locked?).
401 * setting to true makes the dialog open regardless of the
403 * @return An URL storing the selected workspace or null if the user has
404 * canceled the launch operation.
406 private URL promptForWorkspace(Shell shell, ChooseWorkspaceData launchData,
407 boolean force, boolean suppressAskAgain) {
410 // okay to use the shell now - this is the splash shell
411 new ChooseSimanticsWorkspaceDialog(shell, launchData, suppressAskAgain, true).prompt(force);
413 String instancePath = launchData.getSelection();
414 if (instancePath == null) {
418 // the dialog is not forced on the first iteration, but is on every
419 // subsequent one -- if there was an error then the user needs to be
423 // 70576: don't accept empty input
424 if (instancePath.length() <= 0) {
428 IDEWorkbenchMessages.IDEApplication_workspaceEmptyTitle,
429 IDEWorkbenchMessages.IDEApplication_workspaceEmptyMessage);
433 // create the workspace if it does not already exist
434 File workspace = new File(instancePath);
435 if (!workspace.exists()) {
440 // Don't use File.toURL() since it adds a leading slash that Platform does not
441 // handle properly. See bug 54081 for more details.
442 String path = workspace.getAbsolutePath().replace(
443 File.separatorChar, '/');
444 url = new URL("file", null, path); //$NON-NLS-1$
445 } catch (MalformedURLException e) {
449 IDEWorkbenchMessages.IDEApplication_workspaceInvalidTitle,
450 IDEWorkbenchMessages.IDEApplication_workspaceInvalidMessage);
453 } while (!checkValidWorkspace(shell, url));
459 * Return true if the argument directory is ok to use as a workspace and
460 * false otherwise. A version check will be performed, and a confirmation
461 * box may be displayed on the argument shell if an older version is
464 * @return true if the argument URL is ok to use as a workspace and false
467 private boolean checkValidWorkspace(Shell shell, URL url) {
468 // a null url is not a valid workspace
473 String version = readWorkspaceVersion(url);
475 // if the version could not be read, then there is not any existing
476 // workspace data to trample, e.g., perhaps its a new directory that
477 // is just starting to be used as a workspace
478 if (version == null) {
482 final int ide_version = Integer.parseInt(WORKSPACE_VERSION_VALUE);
483 int workspace_version = Integer.parseInt(version);
485 // equality test is required since any version difference (newer
486 // or older) may result in data being trampled
487 if (workspace_version == ide_version) {
491 // At this point workspace has been detected to be from a version
492 // other than the current ide version -- find out if the user wants
497 if (workspace_version < ide_version) {
498 // Workspace < IDE. Update must be possible without issues,
499 // so only inform user about it.
500 severity = MessageDialog.INFORMATION;
501 title = IDEWorkbenchMessages.IDEApplication_versionTitle_olderWorkspace;
502 message = NLS.bind(IDEWorkbenchMessages.IDEApplication_versionMessage_olderWorkspace, url.getFile());
504 // Workspace > IDE. It must have been opened with a newer IDE version.
505 // Downgrade might be problematic, so warn user about it.
506 severity = MessageDialog.WARNING;
507 title = IDEWorkbenchMessages.IDEApplication_versionTitle_newerWorkspace;
508 message = NLS.bind(IDEWorkbenchMessages.IDEApplication_versionMessage_newerWorkspace, url.getFile());
511 MessageBox mbox = new MessageBox(shell, SWT.OK | SWT.CANCEL
512 | SWT.ICON_WARNING | SWT.APPLICATION_MODAL);
514 mbox.setMessage(message);
515 return mbox.open() == SWT.OK;
519 * Look at the argument URL for the workspace's version information. Return
520 * that version if found and null otherwise.
522 private static String readWorkspaceVersion(URL workspace) {
523 File versionFile = getVersionFile(workspace, false);
524 if (versionFile == null || !versionFile.exists()) {
529 // Although the version file is not spec'ed to be a Java properties
530 // file, it happens to follow the same format currently, so using
531 // Properties to read it is convenient.
532 Properties props = new Properties();
533 FileInputStream is = new FileInputStream(versionFile);
540 return props.getProperty(WORKSPACE_VERSION_KEY);
541 } catch (IOException e) {
542 IDEWorkbenchPlugin.log("Could not read version file", new Status( //$NON-NLS-1$
543 IStatus.ERROR, IDEWorkbenchPlugin.IDE_WORKBENCH,
545 e.getMessage() == null ? "" : e.getMessage(), //$NON-NLS-1$,
552 * Write the version of the metadata into a known file overwriting any
553 * existing file contents. Writing the version file isn't really crucial,
554 * so the function is silent about failure
556 private static void writeWorkspaceVersion() {
557 Location instanceLoc = Platform.getInstanceLocation();
558 if (instanceLoc == null || instanceLoc.isReadOnly()) {
562 File versionFile = getVersionFile(instanceLoc.getURL(), true);
563 if (versionFile == null) {
567 OutputStream output = null;
569 String versionLine = WORKSPACE_VERSION_KEY + '='
570 + WORKSPACE_VERSION_VALUE;
572 output = new FileOutputStream(versionFile);
573 output.write(versionLine.getBytes("UTF-8")); //$NON-NLS-1$
574 } catch (IOException e) {
575 IDEWorkbenchPlugin.log("Could not write version file", //$NON-NLS-1$
576 StatusUtil.newStatus(IStatus.ERROR, e.getMessage(), e));
579 if (output != null) {
582 } catch (IOException e) {
589 * The version file is stored in the metadata area of the workspace. This
590 * method returns an URL to the file or null if the directory or file does
591 * not exist (and the create parameter is false).
594 * If the directory and file does not exist this parameter
595 * controls whether it will be created.
596 * @return An url to the file or null if the version file does not exist or
597 * could not be created.
599 private static File getVersionFile(URL workspaceUrl, boolean create) {
600 if (workspaceUrl == null) {
605 // make sure the directory exists
606 File metaDir = new File(workspaceUrl.getPath(), METADATA_FOLDER);
607 if (!metaDir.exists() && (!create || !metaDir.mkdir())) {
611 // make sure the file exists
612 File versionFile = new File(metaDir, VERSION_FILENAME);
613 if (!versionFile.exists()
614 && (!create || !versionFile.createNewFile())) {
619 } catch (IOException e) {
620 // cannot log because instance area has not been set
626 * @see org.eclipse.equinox.app.IApplication#stop()
630 final IWorkbench workbench = PlatformUI.getWorkbench();
631 if (workbench == null)
633 final Display display = workbench.getDisplay();
634 display.syncExec(new Runnable() {
637 if (!display.isDisposed())