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.Display;
37 import org.eclipse.swt.widgets.MessageBox;
38 import org.eclipse.swt.widgets.Shell;
39 import org.eclipse.ui.IWorkbench;
40 import org.eclipse.ui.PlatformUI;
41 import org.eclipse.ui.application.WorkbenchAdvisor;
42 import org.eclipse.ui.internal.WorkbenchPlugin;
43 import org.eclipse.ui.internal.ide.ChooseWorkspaceData;
44 import org.eclipse.ui.internal.ide.ChooseWorkspaceDialog;
45 import org.eclipse.ui.internal.ide.IDEWorkbenchMessages;
46 import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin;
47 import org.eclipse.ui.internal.ide.StatusUtil;
48 import org.simantics.application.arguments.ApplicationUtils;
49 import org.simantics.application.arguments.Arguments;
50 import org.simantics.application.arguments.IArgumentFactory;
51 import org.simantics.application.arguments.IArguments;
52 import org.simantics.application.arguments.SimanticsArguments;
53 import org.simantics.db.management.ISessionContextProvider;
54 import org.simantics.db.management.ISessionContextProviderSource;
55 import org.simantics.db.management.SessionContextProvider;
56 import org.simantics.db.management.SingleSessionContextProviderSource;
57 import org.simantics.ui.SimanticsUI;
58 import org.simantics.utils.ui.BundleUtils;
62 * The "main program" for the Eclipse IDE.
66 public class SimanticsWorkbenchApplication implements IApplication, IExecutableExtension {
69 * The name of the folder containing metadata information for the workspace.
71 public static final String METADATA_FOLDER = ".metadata"; //$NON-NLS-1$
73 private static final String VERSION_FILENAME = "version.ini"; //$NON-NLS-1$
75 private static final String WORKSPACE_VERSION_KEY = "org.eclipse.core.runtime"; //$NON-NLS-1$
77 private static final String WORKSPACE_VERSION_VALUE = "1"; //$NON-NLS-1$
79 private static final String PROP_EXIT_CODE = "eclipse.exitcode"; //$NON-NLS-1$
82 * A special return code that will be recognized by the launcher and used to
83 * restart the workbench.
85 private static final Integer EXIT_RELAUNCH = new Integer(24);
88 * A special return code that will be recognized by the PDE launcher and used to
89 * show an error dialog if the workspace is locked.
91 private static final Integer EXIT_WORKSPACE_LOCKED = new Integer(15);
94 * Creates a new IDE application.
96 public SimanticsWorkbenchApplication() {
97 // There is nothing to do for WorkbenchApplication
100 public WorkbenchAdvisor createWorkbenchAdvisor(IArguments args, DelayedEventsProcessor processor) {
101 return new SimanticsWorkbenchAdvisor(args, processor);
105 * @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext context)
108 public Object start(IApplicationContext appContext) throws Exception {
109 ApplicationUtils.loadSystemProperties(BundleUtils.find(Activator.PLUGIN_ID, "system.properties"));
110 IArguments args = parseArguments((String[]) appContext.getArguments().get(IApplicationContext.APPLICATION_ARGS));
112 Display display = createDisplay();
113 // processor must be created before we start event loop
114 DelayedEventsProcessor processor = new DelayedEventsProcessor(display);
117 Object argCheck = verifyArguments(args);
118 if (argCheck != null)
121 // look and see if there's a splash shell we can parent off of
122 Shell shell = WorkbenchPlugin.getSplashShell(display);
124 // should should set the icon and message for this shell to be the
125 // same as the chooser dialog - this will be the guy that lives in
126 // the task bar and without these calls you'd have the default icon
128 shell.setText(ChooseWorkspaceDialog.getWindowTitle());
129 shell.setImages(Dialog.getDefaultImages());
132 Object instanceLocationCheck = checkInstanceLocation(shell, appContext.getArguments(), args);
133 if (instanceLocationCheck != null) {
134 WorkbenchPlugin.unsetSplashShell(display);
135 Platform.endSplash();
136 return instanceLocationCheck;
139 final ISessionContextProvider provider = new SessionContextProvider(null);
140 final ISessionContextProviderSource contextProviderSource = new SingleSessionContextProviderSource(provider);
141 //final ISessionContextProviderSource contextProviderSource = new WorkbenchWindowSessionContextProviderSource(PlatformUI.getWorkbench());
142 SimanticsUI.setSessionContextProviderSource(contextProviderSource);
143 org.simantics.db.layer0.internal.SimanticsInternal.setSessionContextProviderSource(contextProviderSource);
144 org.simantics.Simantics.setSessionContextProviderSource(contextProviderSource);
146 // create the workbench with this advisor and run it until it exits
147 // N.B. createWorkbench remembers the advisor, and also registers
148 // the workbench globally so that all UI plug-ins can find it using
149 // PlatformUI.getWorkbench() or AbstractUIPlugin.getWorkbench()
150 int returnCode = PlatformUI.createAndRunWorkbench(display,
151 createWorkbenchAdvisor(args, processor));
153 // the workbench doesn't support relaunch yet (bug 61809) so
154 // for now restart is used, and exit data properties are checked
155 // here to substitute in the relaunch return code if needed
156 if (returnCode != PlatformUI.RETURN_RESTART) {
160 // if the exit code property has been set to the relaunch code, then
161 // return that code now, otherwise this is a normal restart
162 return EXIT_RELAUNCH.equals(Integer.getInteger(PROP_EXIT_CODE)) ? EXIT_RELAUNCH
165 if (display != null) {
168 Location instanceLoc = Platform.getInstanceLocation();
169 if (instanceLoc != null)
170 instanceLoc.release();
174 /*************************************************************************/
176 private IArguments parseArguments(String[] args) {
177 IArgumentFactory<?>[] accepted = {
178 SimanticsArguments.RECOVERY_POLICY_FIX_ERRORS,
179 SimanticsArguments.ONTOLOGY_RECOVERY_POLICY_REINSTALL,
180 SimanticsArguments.DEFAULT_WORKSPACE_LOCATION,
181 SimanticsArguments.WORKSPACE_CHOOSER,
182 SimanticsArguments.WORKSPACE_NO_REMEMBER,
183 SimanticsArguments.PERSPECTIVE,
184 SimanticsArguments.SERVER,
185 SimanticsArguments.NEW_MODEL,
186 SimanticsArguments.EXPERIMENT,
187 SimanticsArguments.DISABLE_INDEX,
188 SimanticsArguments.DATABASE_ID,
190 IArguments result = Arguments.parse(args, accepted);
194 private Object verifyArguments(IArguments args) {
195 StringBuilder report = new StringBuilder();
197 // if (args.contains(SimanticsArguments.NEW_PROJECT)) {
198 // if (args.contains(SimanticsArguments.PROJECT)) {
199 // exclusiveArguments(report, SimanticsArguments.PROJECT, SimanticsArguments.NEW_PROJECT);
201 // // Must have a server to checkout from when creating a new
202 // // project right from the beginning.
203 // if (!args.contains(SimanticsArguments.SERVER)) {
204 // missingArgument(report, SimanticsArguments.SERVER);
206 // } else if (args.contains(SimanticsArguments.PROJECT)) {
207 // // To load a project, a server must be defined to checkout from
208 // if (!args.contains(SimanticsArguments.SERVER)) {
209 // missingArgument(report, SimanticsArguments.SERVER);
213 // NEW_MODEL and MODEL arguments are optional
214 // EXPERIMENT argument is optional
216 String result = report.toString();
217 boolean valid = result.length() == 0;
220 String msg = NLS.bind(Messages.Application_1, result);
221 MessageDialog.openInformation(null, Messages.Application_2, msg);
223 return valid ? null : EXIT_OK;
226 // private void exclusiveArguments(StringBuilder sb, IArgumentFactory<?> arg1, IArgumentFactory<?> arg2) {
227 // sb.append(NLS.bind(Messages.Application_3, arg1.getArgument(), arg2.getArgument()));
231 // private void missingArgument(StringBuilder sb, IArgumentFactory<?> arg) {
232 // sb.append(NLS.bind(Messages.Application_0, arg.getArgument()));
236 /*************************************************************************/
239 * Creates the display used by the application.
241 * @return the display used by the application
243 protected Display createDisplay() {
244 return PlatformUI.createDisplay();
248 * @see org.eclipse.core.runtime.IExecutableExtension#setInitializationData(org.eclipse.core.runtime.IConfigurationElement, java.lang.String, java.lang.Object)
251 public void setInitializationData(IConfigurationElement config,
252 String propertyName, Object data) {
253 // There is nothing to do for ProConfApplication
257 * Return true if a valid workspace path has been set and false otherwise.
258 * Prompt for and set the path if possible and required.
259 * @param applicationArguments
261 * @return true if a valid instance location has been set and false
264 private Object checkInstanceLocation(Shell shell, Map<?,?> applicationArguments, IArguments args) {
265 // -data @none was specified but an ide requires workspace
266 Location instanceLoc = Platform.getInstanceLocation();
267 if (instanceLoc == null) {
271 IDEWorkbenchMessages.IDEApplication_workspaceMandatoryTitle,
272 IDEWorkbenchMessages.IDEApplication_workspaceMandatoryMessage);
276 // -data "/valid/path", workspace already set
277 // This information is stored in configuration/.settings/org.eclipse.ui.ide.prefs
278 if (instanceLoc.isSet()) {
279 // make sure the meta data version is compatible (or the user has
280 // chosen to overwrite it).
281 if (!checkValidWorkspace(shell, instanceLoc.getURL())) {
285 // at this point its valid, so try to lock it and update the
286 // metadata version information if successful
288 if (instanceLoc.lock()) {
289 writeWorkspaceVersion();
293 // we failed to create the directory.
294 // Two possibilities:
295 // 1. directory is already in use
296 // 2. directory could not be created
297 File workspaceDirectory = new File(instanceLoc.getURL().getFile());
298 if (workspaceDirectory.exists()) {
299 if (isDevLaunchMode(applicationArguments)) {
300 return EXIT_WORKSPACE_LOCKED;
302 MessageDialog.openError(
304 IDEWorkbenchMessages.IDEApplication_workspaceCannotLockTitle,
305 IDEWorkbenchMessages.IDEApplication_workspaceCannotLockMessage);
307 MessageDialog.openError(
309 IDEWorkbenchMessages.IDEApplication_workspaceCannotBeSetTitle,
310 IDEWorkbenchMessages.IDEApplication_workspaceCannotBeSetMessage);
312 } catch (IOException e) {
313 IDEWorkbenchPlugin.log("Could not obtain lock for workspace location", //$NON-NLS-1$
318 IDEWorkbenchMessages.InternalError,
324 // -data @noDefault or -data not specified, prompt and set
325 ChooseWorkspaceData launchData = null;
326 if (args.contains(SimanticsArguments.DEFAULT_WORKSPACE_LOCATION)) {
327 launchData = new ChooseWorkspaceData(args.get(SimanticsArguments.DEFAULT_WORKSPACE_LOCATION));
329 launchData = new ChooseWorkspaceData(instanceLoc.getDefault());
332 boolean force = args.contains(SimanticsArguments.WORKSPACE_CHOOSER);
333 boolean suppressAskAgain = args.contains(SimanticsArguments.WORKSPACE_NO_REMEMBER);
336 URL workspaceUrl = promptForWorkspace(shell, launchData, force, suppressAskAgain);
337 if (workspaceUrl == null) {
341 // if there is an error with the first selection, then force the
342 // dialog to open to give the user a chance to correct
346 // the operation will fail if the url is not a valid
347 // instance data area, so other checking is unneeded
348 if (instanceLoc.setURL(workspaceUrl, true)) {
349 launchData.writePersistedData();
350 writeWorkspaceVersion();
353 } catch (IllegalStateException e) {
357 IDEWorkbenchMessages.IDEApplication_workspaceCannotBeSetTitle,
358 IDEWorkbenchMessages.IDEApplication_workspaceCannotBeSetMessage);
362 // by this point it has been determined that the workspace is
363 // already in use -- force the user to choose again
364 MessageDialog.openError(shell, IDEWorkbenchMessages.IDEApplication_workspaceInUseTitle,
365 IDEWorkbenchMessages.IDEApplication_workspaceInUseMessage);
369 private static boolean isDevLaunchMode(Map<?,?> args) {
370 // see org.eclipse.pde.internal.core.PluginPathFinder.isDevLaunchMode()
371 if (Boolean.getBoolean("eclipse.pde.launch")) //$NON-NLS-1$
373 return args.containsKey("-pdelaunch"); //$NON-NLS-1$
377 * Open a workspace selection dialog on the argument shell, populating the
378 * argument data with the user's selection. Perform first level validation
379 * on the selection by comparing the version information. This method does
380 * not examine the runtime state (e.g., is the workspace already locked?).
385 * setting to true makes the dialog open regardless of the
387 * @return An URL storing the selected workspace or null if the user has
388 * canceled the launch operation.
390 private URL promptForWorkspace(Shell shell, ChooseWorkspaceData launchData,
391 boolean force, boolean suppressAskAgain) {
394 // okay to use the shell now - this is the splash shell
395 new ChooseWorkspaceDialog(shell, launchData, suppressAskAgain, true).prompt(force);
396 String instancePath = launchData.getSelection();
397 if (instancePath == null) {
401 // the dialog is not forced on the first iteration, but is on every
402 // subsequent one -- if there was an error then the user needs to be
406 // 70576: don't accept empty input
407 if (instancePath.length() <= 0) {
411 IDEWorkbenchMessages.IDEApplication_workspaceEmptyTitle,
412 IDEWorkbenchMessages.IDEApplication_workspaceEmptyMessage);
416 // create the workspace if it does not already exist
417 File workspace = new File(instancePath);
418 if (!workspace.exists()) {
423 // Don't use File.toURL() since it adds a leading slash that Platform does not
424 // handle properly. See bug 54081 for more details.
425 String path = workspace.getAbsolutePath().replace(
426 File.separatorChar, '/');
427 url = new URL("file", null, path); //$NON-NLS-1$
428 } catch (MalformedURLException e) {
432 IDEWorkbenchMessages.IDEApplication_workspaceInvalidTitle,
433 IDEWorkbenchMessages.IDEApplication_workspaceInvalidMessage);
436 } while (!checkValidWorkspace(shell, url));
442 * Return true if the argument directory is ok to use as a workspace and
443 * false otherwise. A version check will be performed, and a confirmation
444 * box may be displayed on the argument shell if an older version is
447 * @return true if the argument URL is ok to use as a workspace and false
450 private boolean checkValidWorkspace(Shell shell, URL url) {
451 // a null url is not a valid workspace
456 String version = readWorkspaceVersion(url);
458 // if the version could not be read, then there is not any existing
459 // workspace data to trample, e.g., perhaps its a new directory that
460 // is just starting to be used as a workspace
461 if (version == null) {
465 final int ide_version = Integer.parseInt(WORKSPACE_VERSION_VALUE);
466 int workspace_version = Integer.parseInt(version);
468 // equality test is required since any version difference (newer
469 // or older) may result in data being trampled
470 if (workspace_version == ide_version) {
474 // At this point workspace has been detected to be from a version
475 // other than the current ide version -- find out if the user wants
480 if (workspace_version < ide_version) {
481 // Workspace < IDE. Update must be possible without issues,
482 // so only inform user about it.
483 severity = MessageDialog.INFORMATION;
484 title = IDEWorkbenchMessages.IDEApplication_versionTitle_olderWorkspace;
485 message = NLS.bind(IDEWorkbenchMessages.IDEApplication_versionMessage_olderWorkspace, url.getFile());
487 // Workspace > IDE. It must have been opened with a newer IDE version.
488 // Downgrade might be problematic, so warn user about it.
489 severity = MessageDialog.WARNING;
490 title = IDEWorkbenchMessages.IDEApplication_versionTitle_newerWorkspace;
491 message = NLS.bind(IDEWorkbenchMessages.IDEApplication_versionMessage_newerWorkspace, url.getFile());
494 MessageBox mbox = new MessageBox(shell, SWT.OK | SWT.CANCEL
495 | SWT.ICON_WARNING | SWT.APPLICATION_MODAL);
497 mbox.setMessage(message);
498 return mbox.open() == SWT.OK;
502 * Look at the argument URL for the workspace's version information. Return
503 * that version if found and null otherwise.
505 private static String readWorkspaceVersion(URL workspace) {
506 File versionFile = getVersionFile(workspace, false);
507 if (versionFile == null || !versionFile.exists()) {
512 // Although the version file is not spec'ed to be a Java properties
513 // file, it happens to follow the same format currently, so using
514 // Properties to read it is convenient.
515 Properties props = new Properties();
516 FileInputStream is = new FileInputStream(versionFile);
523 return props.getProperty(WORKSPACE_VERSION_KEY);
524 } catch (IOException e) {
525 IDEWorkbenchPlugin.log("Could not read version file", new Status( //$NON-NLS-1$
526 IStatus.ERROR, IDEWorkbenchPlugin.IDE_WORKBENCH,
528 e.getMessage() == null ? "" : e.getMessage(), //$NON-NLS-1$,
535 * Write the version of the metadata into a known file overwriting any
536 * existing file contents. Writing the version file isn't really crucial,
537 * so the function is silent about failure
539 private static void writeWorkspaceVersion() {
540 Location instanceLoc = Platform.getInstanceLocation();
541 if (instanceLoc == null || instanceLoc.isReadOnly()) {
545 File versionFile = getVersionFile(instanceLoc.getURL(), true);
546 if (versionFile == null) {
550 OutputStream output = null;
552 String versionLine = WORKSPACE_VERSION_KEY + '='
553 + WORKSPACE_VERSION_VALUE;
555 output = new FileOutputStream(versionFile);
556 output.write(versionLine.getBytes("UTF-8")); //$NON-NLS-1$
557 } catch (IOException e) {
558 IDEWorkbenchPlugin.log("Could not write version file", //$NON-NLS-1$
559 StatusUtil.newStatus(IStatus.ERROR, e.getMessage(), e));
562 if (output != null) {
565 } catch (IOException e) {
572 * The version file is stored in the metadata area of the workspace. This
573 * method returns an URL to the file or null if the directory or file does
574 * not exist (and the create parameter is false).
577 * If the directory and file does not exist this parameter
578 * controls whether it will be created.
579 * @return An url to the file or null if the version file does not exist or
580 * could not be created.
582 private static File getVersionFile(URL workspaceUrl, boolean create) {
583 if (workspaceUrl == null) {
588 // make sure the directory exists
589 File metaDir = new File(workspaceUrl.getPath(), METADATA_FOLDER);
590 if (!metaDir.exists() && (!create || !metaDir.mkdir())) {
594 // make sure the file exists
595 File versionFile = new File(metaDir, VERSION_FILENAME);
596 if (!versionFile.exists()
597 && (!create || !versionFile.createNewFile())) {
602 } catch (IOException e) {
603 // cannot log because instance area has not been set
609 * @see org.eclipse.equinox.app.IApplication#stop()
613 final IWorkbench workbench = PlatformUI.getWorkbench();
614 if (workbench == null)
616 final Display display = workbench.getDisplay();
617 display.syncExec(new Runnable() {
620 if (!display.isDisposed())