Pages

Thursday, 3 June 2010

Run editor in event loop

We have only seen dialogs in a modal mode but recently I came across a requirement where we had to open an editor from a UI thread and then hold the Job until that editor was either closed or a button 'continue' was pressed upon it.


The challenge here was halting/suspending the job until some user action has been received. So here is the trick that I applied towards this problem -

  • Get the active workbench window -
 IWorkbenchWindow dw = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
  •  Get the active page -
IWorkbenchPage page = dw.getActivePage();        
  • Open the editor -
IEditorPart part = IDE.openEditor(page, editorInput, true);
  • Use the following method to keep the job suspended until the editorpart was disposed -
runEventLoop(page, part.getEditorInput(), monitor);

private void runEventLoop(IWorkbenchPage page, IEditorInput editorInput, ProgressMonitor monitor) {
        Display display = Display.getCurrent();
        if(page != null && editorInput != null)
        {
            while (page.findEditor(editorInput) != null)
            {
                IEditorPart part = page.findEditor(editorInput);
                if(!monitor.isCanceled())
                {
                    if(!display.readAndDispatch())
                    {
                        display.sleep();
                    }
                }
                else
                {
                    if(part.getSite() != null && part.getSite().getPage() != null)
                    {
                        part.getSite().getPage().closeEditor(part, false);
                    }
                }
            }
            display.update();
        }
    }

So, as long as the editor part is received on page.findEditor(editorInput) line the display would sleep and hence our job will sit dummy. As soon as the editor part is not found, the while loop will exit updating the display in the process.

0 comments:

Post a Comment