Example usage for org.eclipse.jface.operation ModalContext run

List of usage examples for org.eclipse.jface.operation ModalContext run

Introduction

In this page you can find the example usage for org.eclipse.jface.operation ModalContext run.

Prototype

public static void run(IRunnableWithProgress operation, boolean fork, IProgressMonitor monitor, Display display)
        throws InvocationTargetException, InterruptedException 

Source Link

Document

Runs the given runnable in a modal context, passing it a progress monitor.

Usage

From source file:org.eclipse.graphiti.ui.editor.DefaultPersistencyBehavior.java

License:Open Source License

/**
 * This method is called to save a diagram. The default implementation here
 * saves all changes done to any of the EMF resources loaded within the
 * {@link DiagramBehavior} so that the complete state of all modified
 * objects will be persisted in the file system.<br>
 * The default implementation also sets the current version information
 * (currently 0.14.0) to the diagram before saving it and wraps the save
 * operation inside a {@link IRunnableWithProgress} that cares about sending
 * only one {@link Resource} change event holding all modified files.
 * Besides also all adapters are temporarily switched off (see
 * {@link DiagramBehavior#disableAdapters()}).<br>
 * To only modify the actual saving clients should rather override
 * {@link #save(TransactionalEditingDomain, Map)}.
 * /* w w w  .  j  a v  a 2s.com*/
 * @param monitor
 *            the Eclipse {@link IProgressMonitor} to use to report progress
 */
public void saveDiagram(IProgressMonitor monitor) {
    if (monitor == null) {
        monitor = new NullProgressMonitor();
    }

    // set version info.
    final Diagram diagram = diagramBehavior.getDiagramTypeProvider().getDiagram();
    setDiagramVersion(diagram);

    Map<Resource, Map<?, ?>> saveOptions = createSaveOptions();
    final Set<Resource> savedResources = new HashSet<Resource>();
    final IRunnableWithProgress operation = createOperation(savedResources, saveOptions);

    diagramBehavior.disableAdapters();

    try {
        // This runs the options in a background thread reporting progress
        // to the progress monitor passed into this method (see Bug 393074)
        ModalContext.run(operation, true, monitor, Display.getDefault());

        BasicCommandStack commandStack = (BasicCommandStack) diagramBehavior.getEditingDomain()
                .getCommandStack();
        commandStack.saveIsDone();

        // Store the last executed command on the undo stack as save point
        // and refresh the dirty state of the editor
        savedCommand = commandStack.getUndoCommand();
        diagramBehavior.getDiagramContainer().updateDirtyState();
    } catch (InvocationTargetException e) {
        if (e.getCause() instanceof SaveException) {
            showSaveError(((SaveException) e.getCause()).getStatus());
        } else {
            T.racer().error("Save failed", e);
        }
    } catch (Exception exception) {
        // Something went wrong that shouldn't.
        T.racer().error(exception.getMessage(), exception);
    } finally {
        diagramBehavior.enableAdapters();
    }

    Resource[] savedResourcesArray = savedResources.toArray(new Resource[savedResources.size()]);
    diagramBehavior.getDiagramContainer().commandStackChanged(null);
    IDiagramTypeProvider provider = diagramBehavior.getConfigurationProvider().getDiagramTypeProvider();
    provider.resourcesSaved(provider.getDiagram(), savedResourcesArray);
}

From source file:org.eclipse.jst.ws.internal.creation.ui.extension.PreServiceAssembleCommand.java

License:Open Source License

private void addJavaProjectAsUtilityInModalCtx(final IProject projectToAdd, final IProject earProject,
        final IProgressMonitor monitor) {
    final IRunnableWithProgress addRunnable = new IRunnableWithProgress() {
        public void run(final IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            J2EEUtils.addJavaProjectAsUtilityJar(projectToAdd, earProject, monitor);
        }/*from   ww w  .j  a  va  2  s  . co  m*/
    };

    try {
        ModalContext.run(addRunnable, true, monitor, PlatformUI.getWorkbench().getDisplay());
    } catch (InvocationTargetException e) {
        // The executed runnable does not throw checked exceptions therefore if this happens, this is a runtime exception
        throw new RuntimeException(e);
    } catch (InterruptedException e) {
        // The executed runnable does not support cancellation and this should never happen
        throw new IllegalStateException(e);
    }
}

From source file:org.eclipse.jst.ws.internal.creation.ui.extension.PreServiceDevelopCommand.java

License:Open Source License

/**
 * Adds the projectToAdd as utility to the ear project specified. The operation is executed in a modal context in order to avoid locking the workspace root in the UI thread 
 *//*from   w  ww.j  a  va  2s.  com*/
private void addJavaProjectAsUtilityInModalCtx(final IProject projectToAdd, final IProject earProject,
        final IProgressMonitor monitor) throws IOException, CoreException {
    final IRunnableWithProgress addRunnable = new IRunnableWithProgress() {
        public void run(final IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            J2EEUtils.addJavaProjectAsUtilityJar(projectToAdd, earProject, monitor);
            try {
                final String uri = projectToAdd.getName() + ".jar";
                J2EEUtils.addJAROrModuleDependency(earProject, uri);
            } catch (IOException e) {
                throw new InvocationTargetException(e);
            } catch (CoreException e) {
                throw new InvocationTargetException(e);
            }
        }
    };

    try {
        ModalContext.run(addRunnable, true, monitor, PlatformUI.getWorkbench().getDisplay());
    } catch (InvocationTargetException e) {
        final Throwable cause = e.getCause();
        // IOExcetpion and CoreException thrown by J2EEUtils.addJAROrModuleDependency
        if (cause instanceof IOException) {
            throw (IOException) cause;
        }
        if (cause instanceof CoreException) {
            throw (CoreException) cause;
        }

        // Other unexpected exception has occurred, rethrow it as a runtime exception
        throw new RuntimeException(e);
    } catch (InterruptedException e) {
        // The executed runnable does not support cancellation and therefore this can never happen
        throw new IllegalStateException(e);
    }
}

From source file:org.eclipse.ltk.internal.ui.refactoring.RefactoringWizardDialog2.java

License:Open Source License

public void run(boolean fork, boolean cancelable, IRunnableWithProgress runnable)
        throws InvocationTargetException, InterruptedException {
    if (fProgressMonitorPart == null) {
        ModalContext.run(runnable, false, new NullProgressMonitor(), getShell().getDisplay());
    } else {/*from  w w w .j ava 2  s .  com*/
        Object state = null;
        if (fActiveRunningOperations == 0)
            state = aboutToStart(fork && cancelable);

        fActiveRunningOperations++;
        try {
            ModalContext.run(runnable, fork, fProgressMonitorPart, getShell().getDisplay());
        } finally {
            fActiveRunningOperations--;
            //Stop if this is the last one
            if (state != null)
                stopped(state);
        }
    }
}

From source file:org.eclipse.mylyn.commons.ui.ProgressContainer.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.
 * 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.
 *///from  w ww  .  java2s.c  o  m
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 {
        activeRunningOperations--;
        // Stop if this is the last one
        if (state != null) {
            stopped(state);
        }
    }
}

From source file:org.eclipse.net4j.util.ui.UIUtil.java

License:Open Source License

/**
 * @since 3.3//from  w w w.j a  va 2s  . co m
 */
public static void runWithProgress(final IRunnableWithProgress runnable) {
    try {
        IRunnableWithProgress op = new IRunnableWithProgress() {
            public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                ModalContext.run(runnable, true, monitor, PlatformUI.getWorkbench().getDisplay());
            }
        };

        PlatformUI.getWorkbench().getProgressService().run(false, true, op);
    } catch (InvocationTargetException ex) {
        OM.LOG.error(ex.getCause());
    } catch (InterruptedException ex) {
        //$FALL-THROUGH$
    }
}

From source file:org.eclipse.php.composer.internal.ui.dialogs.AddDependencyWizardDialog.java

License:Open Source License

@Override
public void run(boolean fork, boolean cancelable, IRunnableWithProgress runnable)
        throws InvocationTargetException, InterruptedException {
    try {//w ww.j  a v  a  2 s. c o  m
        if (getWizard().needsProgressMonitor()) {
            if (cancelable && fork) {
                Button cancelButton = getButton(IDialogConstants.CANCEL_ID);
                ((ProgressMonitorPart) getProgressMonitor()).attachToCancelComponent(cancelButton);
            }
            ((ProgressMonitorPart) getProgressMonitor()).setVisible(true);
        }

        lockUI = true;
        ModalContext.run(runnable, fork, getProgressMonitor(), getShell().getDisplay());
    } 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 && !((ProgressMonitorPart) getProgressMonitor()).isDisposed()) {
            getProgressMonitor().done();
        }
        lockUI = false;
    }
}

From source file:org.eclipse.rap.security.dummy.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  va2 s.  c om
            setBlockOnOpen(false);
            open();
            final Button okButton = getButton(IDialogConstants.OK_ID);
            okButton.setText("Login");
            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.rcptt.ui.controls.StatusBarComposite.java

License:Open Source License

public void runWithProgress(String name, final IRunnableWithProgress runnable, boolean fork) {
    if (name == null || name.length() <= 0) {
        name = DEFAULT_TASKNAME;//from w  ww  . j a  va 2  s .  com
    }
    final String message = name;
    asyncExec(new Runnable() {
        public void run() {
            setProgressBarLayout();
            show();
            layout();
            setMessage(message, false);
        }
    });
    final ProgressMonitor monitor = new ProgressMonitor();
    try {
        ModalContext.run(runnable, fork, monitor, shell.getDisplay());
    } catch (final InvocationTargetException e) {
        handleError(message, e.getTargetException());
    } catch (InterruptedException e) {
        // Canceled
    }
}

From source file:org.eclipse.remote.ui.dialogs.RemoteResourceBrowser.java

License:Open Source License

@Override
public void run(boolean fork, boolean cancelable, IRunnableWithProgress runnable)
        throws InvocationTargetException, InterruptedException {
    fProgressMonitor.attachToCancelComponent(null);
    fProgressMonitor.getParent().setVisible(true);
    try {/* ww w .j a  va 2  s .  c  o  m*/
        ModalContext.run(runnable, fork, fProgressMonitor, getShell().getDisplay());
    } finally {
        fProgressMonitor.getParent().setVisible(false);
        fProgressMonitor.removeFromCancelComponent(null);
    }
}