List of usage examples for org.eclipse.jface.operation ModalContext run
public static void run(IRunnableWithProgress operation, boolean fork, IProgressMonitor monitor, Display display) throws InvocationTargetException, InterruptedException
From source file:net.heartsome.cat.common.ui.wizard.TSWizardDialog.java
License:Open Source License
/** * This implementation of IRunnableContext#run(boolean, boolean, * IRunnableWithProgress) blocks until the runnable has been run, regardless * of the value of <code>fork</code>. It is recommended that * <code>fork</code> is set to true in most cases. If <code>fork</code> * is set to <code>false</code>, the runnable will run in the UI thread * and it is the runnable's responsibility to call * <code>Display.readAndDispatch()</code> to ensure UI responsiveness. * //from w w w. ja va2s . c o m * UI state is saved prior to executing the long-running operation and is * restored after the long-running operation completes executing. Any * attempt to change the UI state of the wizard in the long-running * operation will be nullified when original UI state is restored. * */ public void run(boolean fork, boolean cancelable, IRunnableWithProgress runnable) throws InvocationTargetException, InterruptedException { // The operation can only be canceled if it is executed in a separate // thread. // Otherwise the UI is blocked anyway. Object state = null; if (activeRunningOperations == 0) { state = aboutToStart(fork && cancelable); } activeRunningOperations++; try { if (!fork) { lockedUI = true; } ModalContext.run(runnable, fork, getProgressMonitor(), getShell().getDisplay()); lockedUI = false; } finally { // explicitly invoke done() on our progress monitor so that its // label does not spill over to the next invocation, see bug 271530 if (getProgressMonitor() != null) { getProgressMonitor().done(); } // Stop if this is the last one if (state != null) { timeWhenLastJobFinished = System.currentTimeMillis(); stopped(state); } activeRunningOperations--; } }
From source file:net.sf.eclipsensis.installoptions.actions.PreviewAction.java
License:Open Source License
private void doPreview(final INIFile iniFile, final File file) { final Shell shell = mEditor.getSite().getShell(); BusyIndicator.showWhile(shell.getDisplay(), new Runnable() { public void run() { final ProgressMonitorDialog pmd = new ProgressMonitorDialog(shell) { @Override/* ww w . j a v a 2 s .c om*/ protected void configureShell(Shell shell) { super.configureShell(shell); Rectangle rect = shell.getDisplay().getBounds(); shell.setLocation(rect.x + rect.width + 1, rect.y + rect.height + 1); } @Override protected Rectangle getConstrainedShellBounds(Rectangle preferredSize) { Rectangle rect = shell.getDisplay().getBounds(); return new Rectangle(rect.x + rect.width + 1, rect.y + rect.height + 1, preferredSize.width, preferredSize.height); } }; pmd.open(); try { ModalContext.run(new IRunnableWithProgress() { private File createPreviewFile(File previewFile, INIFile inifile, final NSISLanguage lang) throws IOException { File previewFile2 = previewFile; INIFile inifile2 = inifile; if (previewFile2 == null) { previewFile2 = File.createTempFile("preview", ".ini"); //$NON-NLS-1$ //$NON-NLS-2$ previewFile2.deleteOnExit(); } inifile2 = inifile2.copy(); InstallOptionsDialog dialog = InstallOptionsDialog.loadINIFile(inifile2); DialogSize dialogSize; if (getId().equals(PREVIEW_MUI_ID)) { dialogSize = DialogSizeManager.getDialogSize(cMUIDialogSizeName); } else { dialogSize = DialogSizeManager.getDialogSize(cClassicDialogSizeName); } if (dialogSize == null) { dialogSize = DialogSizeManager.getDefaultDialogSize(); } dialog.setDialogSize(dialogSize); Font font = FontUtility.getFont(lang); for (Iterator<InstallOptionsWidget> iter = dialog.getChildren().iterator(); iter .hasNext();) { InstallOptionsWidget widget = iter.next(); if (widget instanceof InstallOptionsPicture) { final InstallOptionsPicture picture = (InstallOptionsPicture) widget; final Dimension dim = widget.toGraphical(widget.getPosition(), font).getSize(); final Map<Dimension, File> cache; switch (picture.getSWTImageType()) { case SWT.IMAGE_BMP: cache = cBitmapCache; break; case SWT.IMAGE_ICO: cache = cIconCache; break; default: continue; } final File[] imageFile = new File[] { cache.get(dim) }; if (!IOUtility.isValidFile(imageFile[0])) { shell.getDisplay().syncExec(new Runnable() { public void run() { Image widgetImage = picture.getImage(); ImageData data = widgetImage.getImageData(); data.width = dim.width; data.height = dim.height; data.type = picture.getSWTImageType(); Image bitmap = new Image(shell.getDisplay(), data); GC gc = new GC(bitmap); gc.setBackground(shell.getDisplay() .getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); gc.setForeground( shell.getDisplay().getSystemColor(SWT.COLOR_BLACK)); gc.fillRectangle(0, 0, dim.width, dim.height); Rectangle rect = widgetImage.getBounds(); int x, y, width, height; if (rect.width > dim.width) { x = 0; width = dim.width; } else { x = (dim.width - rect.width) / 2; width = rect.width; } if (rect.height > dim.height) { y = 0; height = dim.height; } else { y = (dim.height - rect.height) / 2; height = rect.height; } gc.drawImage(widgetImage, 0, 0, rect.width, rect.height, x, y, width, height); gc.setLineStyle(SWT.LINE_CUSTOM); gc.setLineDash(DashedLineBorder.DASHES); gc.drawRectangle(0, 0, dim.width - 1, dim.height - 1); gc.dispose(); ImageLoader loader = new ImageLoader(); loader.data = new ImageData[] { bitmap.getImageData() }; try { imageFile[0] = File.createTempFile("preview", //$NON-NLS-1$ picture.getFileExtension()); imageFile[0].deleteOnExit(); loader.save(imageFile[0].getAbsolutePath(), picture.getSWTImageType()); cache.put(dim, imageFile[0]); } catch (IOException e) { imageFile[0] = null; InstallOptionsPlugin.getDefault().log(e); cache.remove(dim); } } }); } if (imageFile[0] != null) { picture.setPropertyValue(InstallOptionsModel.PROPERTY_TEXT, imageFile[0].getAbsolutePath()); } } } inifile2 = dialog.updateINIFile(); IOUtility.writeContentToFile(previewFile2, inifile2.toString().getBytes()); return previewFile2; } public void run(IProgressMonitor monitor) { try { monitor.beginTask( InstallOptionsPlugin.getResourceString("previewing.script.task.name"), //$NON-NLS-1$ IProgressMonitor.UNKNOWN); String pref = InstallOptionsPlugin.getDefault().getPreferenceStore() .getString(IInstallOptionsConstants.PREFERENCE_PREVIEW_LANG); NSISLanguage lang; if (pref.equals("")) { //$NON-NLS-1$ lang = NSISLanguageManager.getInstance().getDefaultLanguage(); } else { lang = NSISLanguageManager.getInstance().getLanguage(pref); if (lang == null) { lang = NSISLanguageManager.getInstance().getDefaultLanguage(); InstallOptionsPlugin.getDefault().getPreferenceStore() .setValue(IInstallOptionsConstants.PREFERENCE_PREVIEW_LANG, ""); //$NON-NLS-1$ } } PreviewCacheKey key = new PreviewCacheKey(file, lang); File previewFile = cPreviewCache.get(key); if (previewFile == null || file.lastModified() > previewFile.lastModified()) { previewFile = createPreviewFile(previewFile, iniFile, lang); cPreviewCache.put(key, previewFile); } Map<String, String> symbols = mSettings.getSymbols(); symbols.put("PREVIEW_INI", previewFile.getAbsolutePath()); //$NON-NLS-1$ symbols.put("PREVIEW_LANG", lang.getName()); //$NON-NLS-1$ Locale locale = NSISLanguageManager.getInstance() .getLocaleForLangId(lang.getLangId()); if (getId().equals(PREVIEW_MUI_ID)) { symbols.put("PREVIEW_TITLE", //$NON-NLS-1$ InstallOptionsPlugin.getResourceString(locale, "preview.setup.title")); //$NON-NLS-1$ symbols.put("PREVIEW_SUBTITLE", InstallOptionsPlugin.getResourceString(locale, //$NON-NLS-1$ "preview.setup.subtitle")); //$NON-NLS-1$ } else { symbols.put("PREVIEW_BRANDING", InstallOptionsPlugin.getResourceString(locale, //$NON-NLS-1$ "preview.setup.branding")); //$NON-NLS-1$ } symbols.put("PREVIEW_NAME", //$NON-NLS-1$ InstallOptionsPlugin.getResourceString(locale, "preview.setup.name")); //$NON-NLS-1$ if (EclipseNSISPlugin.getDefault().isWinVista() && NSISPreferences.getInstance() .getNSISVersion().compareTo(INSISVersions.VERSION_2_21) >= 0) { symbols.put("WINDOWS_VISTA", ""); //$NON-NLS-1$ //$NON-NLS-2$ } mSettings.setSymbols(symbols); final File previewScript = getPreviewScript(); long timestamp = System.currentTimeMillis(); MakeNSISResults results = null; results = MakeNSISRunner.compile(previewScript, mSettings, cDummyConsole, new INSISConsoleLineProcessor() { public NSISConsoleLine processText(String text) { return NSISConsoleLine.info(text); } public void reset() { } }); if (results != null) { if (results.getReturnCode() != 0) { List<NSISScriptProblem> errors = results.getProblems(); final String error; if (!Common.isEmptyCollection(errors)) { Iterator<NSISScriptProblem> iter = errors.iterator(); StringBuffer buf = new StringBuffer(iter.next().getText()); while (iter.hasNext()) { buf.append(INSISConstants.LINE_SEPARATOR) .append(iter.next().getText()); } error = buf.toString(); } else { error = InstallOptionsPlugin.getResourceString("preview.compile.error"); //$NON-NLS-1$ } shell.getDisplay().asyncExec(new Runnable() { public void run() { Common.openError(shell, error, InstallOptionsPlugin.getShellImage()); } }); } else { final File outfile = new File(results.getOutputFileName()); if (IOUtility.isValidFile(outfile) && outfile.lastModified() > timestamp) { MakeNSISRunner.testInstaller(outfile.getAbsolutePath(), null, true); } } } } catch (final Exception e) { InstallOptionsPlugin.getDefault().log(e); shell.getDisplay().asyncExec(new Runnable() { public void run() { Common.openError(shell, e.getMessage(), InstallOptionsPlugin.getShellImage()); } }); } finally { monitor.done(); } } }, true, pmd.getProgressMonitor(), shell.getDisplay()); } catch (Exception e) { InstallOptionsPlugin.getDefault().log(e); Common.openError(shell, e.getMessage(), InstallOptionsPlugin.getShellImage()); } finally { pmd.close(); } } }); }
From source file:org.eclipse.buckminster.jnlp.p2.ui.general.wizard.AdvancedWizardDialog.java
License:Open Source License
@Override public void run(boolean fork, boolean cancelable, IRunnableWithProgress runnable) throws InvocationTargetException, InterruptedException { m_runningOperation = true;//from ww w . j av a 2 s . c om if (getWizard().needsProgressMonitor()) { getProgressMonitor().setCanceled(false); ProgressMonitorPart progressMonitorPart = (ProgressMonitorPart) getProgressMonitor(); progressMonitorPart.setVisible(true); } try { ModalContext.run(runnable, fork, getProgressMonitor(), getShell().getDisplay()); } finally { m_runningOperation = false; if (getWizard().needsProgressMonitor()) { ProgressMonitorPart progressMonitorPart = (ProgressMonitorPart) getProgressMonitor(); progressMonitorPart.setVisible(false); } } }
From source file:org.eclipse.debug.internal.ui.launchConfigurations.LaunchConfigurationsDialog.java
License:Open Source License
public void run(boolean fork, boolean cancelable, IRunnableWithProgress runnable) throws InvocationTargetException, InterruptedException { if (getShell() != null && getShell().isVisible()) { // Save focus control fLastControl = getShell().getDisplay().getFocusControl(); if (fLastControl != null && fLastControl.getShell() != getShell()) { fLastControl = null;/*from w ww . ja v a2 s.c o m*/ } // Attach the progress monitor part to the cancel button fProgressMonitorPart.attachToCancelComponent(null); fProgressMonitorPart.getParent().setVisible(true); fActiveRunningOperations++; //do work here collecting enabled states, otherwise to get these states we would need to //perform the validation of the dialog again, which is expensive and would cause flashing of widgets. Control[] children = ((Composite) fButtonComp.getChildren()[0]).getChildren(); boolean[] prev = new boolean[children.length + 2]; prev[0] = fTabViewer.getApplyButton().isEnabled(); prev[1] = fTabViewer.getRevertButton().isEnabled(); for (int i = 0; i < children.length; i++) { prev[i + 2] = children[i].isEnabled(); } try { updateRunnnableControls(false, prev); ModalContext.run(runnable, fork, fProgressMonitorPart, getShell().getDisplay()); } finally { fActiveRunningOperations--; updateRunnnableControls(true, prev); if (getShell() != null) { fProgressMonitorPart.getParent().setVisible(false); fProgressMonitorPart.removeFromCancelComponent(null); if (fLastControl != null) { fLastControl.setFocus(); } } } } else { PlatformUI.getWorkbench().getProgressService().run(fork, cancelable, runnable); } }
From source file:org.eclipse.egit.ui.internal.branch.LaunchFinder.java
License:Open Source License
/** * If there is a running launch covering at least one project from the given * repositories, return the first such launch configuration. * * @param repositories/*ww w. j a v a 2s . com*/ * to determine projects to be checked whether they are used in * running launches * @param monitor * for progress reporting and cancellation * @return the {@link ILaunchConfiguration}, or {@code null} if none found. */ @Nullable public static ILaunchConfiguration getRunningLaunchConfiguration(final Collection<Repository> repositories, IProgressMonitor monitor) { SubMonitor progress = SubMonitor.convert(monitor, 1); final ILaunchConfiguration[] result = { null }; IRunnableWithProgress operation = new IRunnableWithProgress() { @Override public void run(IProgressMonitor m) throws InvocationTargetException, InterruptedException { Set<IProject> projects = new HashSet<>(); for (Repository repository : repositories) { projects.addAll(Arrays.asList(ProjectUtil.getProjects(repository))); } result[0] = findLaunch(projects, m); } }; try { if (ModalContext.isModalContextThread(Thread.currentThread())) { operation.run(progress); } else { ModalContext.run(operation, true, progress, PlatformUI.getWorkbench().getDisplay()); } } catch (InvocationTargetException e) { // ignore } catch (InterruptedException e) { // ignore } return result[0]; }
From source file:org.eclipse.epf.library.edit.ui.UIHelper.java
License:Open Source License
public IStatus runInModalContext(final IRunnableWithProgress operation, boolean fork, IProgressMonitor monitor, Object uiContext) {//from w w w . j av a 2 s. c om org.eclipse.jface.operation.IRunnableWithProgress op = new org.eclipse.jface.operation.IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { operation.run(monitor); } }; try { ModalContext.run(op, true, monitor, ((Shell) uiContext).getDisplay()); return Status.OK_STATUS; } catch (Exception e) { LibraryEditPlugin.INSTANCE.log(e); Throwable ex; if (e instanceof InvocationTargetException) { ex = ((InvocationTargetException) e).getTargetException(); } else { ex = e; } String msg = TngUtil.toStackTraceString(ex); return new Status(IStatus.ERROR, LibraryEditPlugin.INSTANCE.getSymbolicName(), 0, msg, ex); } }
From source file:org.eclipse.equinox.security.sample.keystore.ui.AbstractLoginDialog.java
License:Open Source License
public void handle(final Callback[] callbacks) throws IOException { this.callbackArray = callbacks; final Display display = Display.getDefault(); display.syncExec(new Runnable() { public void run() { isCancelled = false;//from w ww.j a va 2 s .c o m setBlockOnOpen(false); open(); final Button okButton = getButton(IDialogConstants.OK_ID); okButton.setText(SampleMessages.loginButton); okButton.addSelectionListener(new SelectionListener() { public void widgetSelected(final SelectionEvent event) { processCallbacks = true; } public void widgetDefaultSelected(final SelectionEvent event) { // nothing to do } }); final Button cancel = getButton(IDialogConstants.CANCEL_ID); cancel.addSelectionListener(new SelectionListener() { public void widgetSelected(final SelectionEvent event) { isCancelled = true; processCallbacks = true; } public void widgetDefaultSelected(final SelectionEvent event) { // nothing to do } }); } }); try { ModalContext.setAllowReadAndDispatch(true); //Works for now. ModalContext.run(new IRunnableWithProgress() { public void run(final IProgressMonitor monitor) { // Wait here until OK or cancel is pressed, then let it rip. The event listener // is responsible for closing the dialog (in the loginSucceeded event). while (!processCallbacks) { try { Thread.sleep(100); } catch (final Exception e) { //do nothing } } processCallbacks = false; // Call the adapter to handle the callbacks if (!isCancelled()) internalHandle(); } }, true, new NullProgressMonitor(), Display.getDefault()); } catch (final Exception e) { final IOException ioe = new IOException(); ioe.initCause(e); throw ioe; } }
From source file:org.eclipse.gmf.tests.runtime.common.ui.internal.action.AbstractActionDelegateTest.java
License:Open Source License
/** * Tests that an error dialog can be successfully shown when * the action delegate runs on a non-UI thread. *//*from w w w. j a va 2 s. c om*/ public void ignore_errorDialogOnNonUIThread_125482() { // This line must be enabled to really perform the test. Otherwise, the // error dialog is not displayed and the SWTException would NEVER occur. // However, for the purpose of automated testing, the automated mode // will be true. // // ErrorDialog.AUTOMATED_MODE = false; AbstractActionDelegate actionDelegate = new AbstractActionDelegate() { protected void doRun(IProgressMonitor progressMonitor) { final Exception e = new Exception("Forced Exception"); //$NON-NLS-1$ final IWorkbenchPart part = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() .getActivePart(); IRunnableWithProgress runnable = new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { setAction(new Action("AbstractActionDelegateTest") { //$NON-NLS-1$ // nothing }); setWorkbenchPart(part); handle(e); } catch (SWTException swte) { fail("Do not expect SWT Exception: " + swte.getLocalizedMessage()); //$NON-NLS-1$ } } }; try { ModalContext.run(runnable, true, new NullProgressMonitor(), Display.getCurrent()); } catch (InterruptedException ie) { // do nothing } catch (InvocationTargetException ite) { // do nothing } } }; actionDelegate.run(new NullProgressMonitor()); }
From source file:org.eclipse.gmf.tests.runtime.common.ui.internal.action.AbstractActionHandlerTest.java
License:Open Source License
/** * Tests that an error dialog can be successfully shown when * the action handler runs on a non-UI thread. *//*from w w w .j ava2 s . com*/ public void ignore_errorDialogOnNonUIThread_132143() { // This line must be enabled to really perform the test. Otherwise, the // error dialog is not displayed and the SWTException would NEVER occur. // However, for the purpose of automated testing, the automated mode // will be true. // // ErrorDialog.AUTOMATED_MODE = false; final IWorkbenchPart part = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() .getActivePart(); AbstractActionHandler actionHandler = new AbstractActionHandler(part) { protected void doRun(IProgressMonitor progressMonitor) { final Exception e = new Exception("Forced Exception"); //$NON-NLS-1$ IRunnableWithProgress runnable = new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { setText("test_errorDialogOnNonUIThread_132143"); //$NON-NLS-1$ setWorkbenchPart(part); handle(e); } }; try { ModalContext.run(runnable, true, new NullProgressMonitor(), Display.getCurrent()); } catch (InvocationTargetException ite) { fail("Unexpected exception:" + ite); //$NON-NLS-1$ } catch (InterruptedException ie) { fail("Unexpected exception:" + ie); //$NON-NLS-1$ } } public void refresh() { // do nothing } }; actionHandler.run(new NullProgressMonitor()); }
From source file:org.eclipse.gmf.tests.runtime.common.ui.util.StatusLineUtilTest.java
License:Open Source License
/** * Tests that the status line can be successfully updated from a non-UI * thread.// w w w . j a v a 2 s .com */ public void ignore_statusLineUpdateOnNonUIThread_128868() throws Exception { final IWorkbenchPart part = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() .getActivePart(); IRunnableWithProgress runnable = new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { StatusLineUtil.outputErrorMessage(part, "test_statusLineUpdateOnNonUIThread_128868"); //$NON-NLS-1$ } }; try { ModalContext.run(runnable, true, new NullProgressMonitor(), Display.getCurrent()); } catch (InvocationTargetException ite) { fail("Unexpected exception:" + ite); //$NON-NLS-1$ } catch (InterruptedException ie) { fail("Unexpected exception:" + ie); //$NON-NLS-1$ } }