Monday, May 21, 2007

How to learn if the Workbench is going to be restarted upon closing

Sometimes you need to intercept the Workbench shutdown event and check whether the workbench is being shut down or just restarted. Depending on that you may want to do something with your backend.
Unfortunately there is no public API for that - everything what we have is the IWorkbench#isClosing() method, which does not tell us if it's gonna be a restart or shutdown. However, in the internal implementation of IWorkbench (org.eclipse.ui.internal.Workbench) there is a private int field named "returnCode", which is set to PlatformUI.RETURN_RESTART value if somebody calls the restart() method.
Using reflection you can get the value of this field:

* The method uses the private field of the internal IWorkbench implementation,
* since there is no public API to check whether the Workbench is being restarted.
* @return true, if the workbench is restarting
* @author Ilya Shinkarenko
private boolean isWorkbenchRestarting() {
int returnValue = 0;
IWorkbench workbench = PlatformUI.getWorkbench();
try {
Field field = workbench.getClass().getDeclaredField("returnCode");
Object value = field.get(workbench);
//the value is always Integer
returnValue = ((Integer)value).intValue();
catch (Exception e) {
//report the exception

return returnValue == PlatformUI.RETURN_RESTART;


Eugene Kuleshov said...

Yak! Can't you just register a listener for workbench shutdown event?

Ilya Shinkarenko said...

Eugene: of course you register a WorkbenchListener. But the problem is that in the event handler you can't tell whether it's gonna be restart or shutdown.

public interface IWorkbenchListener {
public boolean preShutdown(IWorkbench workbench, boolean forced);
public void postShutdown(IWorkbench workbench);