Example usage for org.eclipse.jface.dialogs ProgressMonitorDialog run

List of usage examples for org.eclipse.jface.dialogs ProgressMonitorDialog run

Introduction

In this page you can find the example usage for org.eclipse.jface.dialogs ProgressMonitorDialog run.

Prototype

@Override
public void run(boolean fork, boolean cancelable, IRunnableWithProgress runnable)
        throws InvocationTargetException, InterruptedException 

Source Link

Document

This implementation of IRunnableContext#run(boolean, boolean, IRunnableWithProgress) runs the given IRunnableWithProgress using the progress monitor for this progress dialog and blocks until the runnable has been run, regardless of the value of fork.

Usage

From source file:org.eclipse.sirius.tree.ui.tools.internal.editor.actions.EditorRefreshAction.java

License:Open Source License

/**
 * {@inheritDoc}/*from w w  w  . ja  va  2s .  c  o m*/
 * 
 * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
 */
public void run(final IAction action) {
    if (workbenchPart instanceof DTreeEditor) {
        final IRunnableWithProgress op = new IRunnableWithProgress() {
            public void run(final IProgressMonitor monitor) {
                final DTreeEditor treeEditor = (DTreeEditor) workbenchPart;
                treeEditor.enablePropertiesUpdate(false);
                RefreshActionListenerRegistry.INSTANCE
                        .notifyRepresentationIsAboutToBeRefreshed(treeEditor.getTreeModel());
                treeEditor.getEditingDomain().getCommandStack().execute(new RefreshRepresentationsCommand(
                        treeEditor.getEditingDomain(), monitor, treeEditor.getTreeModel()));
                treeEditor.enablePropertiesUpdate(true);
            }
        };
        final Shell activeShell = workbenchPart.getSite().getShell();
        final ProgressMonitorDialog monitorDialog = new ProgressMonitorDialog(activeShell);
        try {
            monitorDialog.run(false, false, op);
        } catch (final InvocationTargetException e) {
            MessageDialog.openError(activeShell, "Error", e.getTargetException().getMessage());
            SiriusPlugin.getDefault().error("Error while refreshing tree", e);
        } catch (final InterruptedException e) {
            MessageDialog.openInformation(activeShell, "Cancelled", e.getMessage());
        }
    }
}

From source file:org.eclipse.sirius.tree.ui.tools.internal.editor.actions.RefreshAction.java

License:Open Source License

private void run(final IRunnableWithProgress op) {
    final Shell activeShell = treeEditor.getSite().getShell();
    final ProgressMonitorDialog monitorDialog = new ProgressMonitorDialog(activeShell);
    try {//from ww w.ja  va  2s  .  co m
        treeEditor.enablePropertiesUpdate(false);
        monitorDialog.run(true, false, op);
    } catch (final InvocationTargetException e) {
        MessageDialog.openError(activeShell, "Error", e.getTargetException().getMessage());
        SiriusPlugin.getDefault().error("Error while refreshing tree", e);
    } catch (final InterruptedException e) {
        MessageDialog.openInformation(activeShell, "Cancelled", e.getMessage());
    } finally {
        treeEditor.enablePropertiesUpdate(true);
    }
}

From source file:org.eclipse.sirius.ui.tools.internal.actions.export.AbstractExportRepresentationsAction.java

License:Open Source License

/**
 * Display the export path and file format dialog and then export the
 * representations./*from  www  .  ja va2 s.  c o  m*/
 * 
 * @param exportPath
 *            the default export path.
 * @param dRepresentationToExport
 *            the representation to export.
 * @param session
 *            the corresponding session.
 */
protected void exportRepresentation(IPath exportPath, Iterable<DRepresentation> dRepresentationToExport,
        Session session) {
    final Shell shell = Display.getCurrent().getActiveShell();

    final AbstractExportRepresentationsAsImagesDialog dialog;
    if (Iterables.size(dRepresentationToExport) > 1) {
        dialog = new ExportSeveralRepresentationsAsImagesDialog(shell, exportPath);
    } else {
        dialog = new ExportOneRepresentationAsImageDialog(shell, exportPath,
                dRepresentationToExport.iterator().next().getName());
    }

    if (dialog.open() == Window.OK) {
        List<DRepresentation> toExport = Lists.<DRepresentation>newArrayList(dRepresentationToExport);
        final ExportAction exportAction = new ExportAction(session, toExport, dialog.getOutputPath(),
                dialog.getImageFormat(), dialog.isExportToHtml());
        final ProgressMonitorDialog pmd = new ProgressMonitorDialog(shell);
        try {
            pmd.run(false, false, exportAction);
        } catch (final InvocationTargetException e) {
            MessageDialog.openError(shell, "Error", e.getTargetException().getMessage());
        } catch (final InterruptedException e) {
            MessageDialog.openInformation(shell, "Cancelled", e.getMessage());
        } finally {
            pmd.close();
        }
    } else {
        dialog.close();
    }
}

From source file:org.eclipse.sirius.ui.tools.internal.actions.export.ExportRepresentationsFromFileAction.java

License:Open Source License

/**
 * {@inheritDoc}/*from  w ww  . j a  va  2  s. c  o m*/
 * 
 * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
 */
public void run(final IAction action) {

    final Shell shell = Display.getCurrent().getActiveShell();
    final IPath targetPath = this.sessionResourceFile.getParent().getLocation();
    final URI sessionResourceURI = URI.createPlatformResourceURI(sessionResourceFile.getFullPath().toOSString(),
            true);
    Session session = SessionManager.INSTANCE.getSession(sessionResourceURI,
            new SubProgressMonitor(new NullProgressMonitor(), 1));

    final Collection<DRepresentation> dRepresentationsToExportAsImage = DialectManager.INSTANCE
            .getAllRepresentations(session);
    if (!dRepresentationsToExportAsImage.isEmpty()) {
        final ExportSeveralRepresentationsAsImagesDialog dialog = new ExportSeveralRepresentationsAsImagesDialog(
                shell, targetPath);
        if (dialog.open() == Window.CANCEL) {
            dialog.close();
            return;
        }

        final IPath outputPath = dialog.getOutputPath();
        final ImageFileFormat imageFormat = dialog.getImageFormat();
        final boolean exportToHtml = dialog.isExportToHtml();

        IRunnableWithProgress exportAllRepresentationsRunnable = new WorkspaceModifyOperation() {

            @Override
            protected void execute(IProgressMonitor monitor)
                    throws CoreException, InvocationTargetException, InterruptedException {
                Session session = null;
                boolean isOpen = false;
                try {
                    monitor.beginTask("Export all representations to images", 10);
                    session = SessionManager.INSTANCE.getSession(sessionResourceURI,
                            new SubProgressMonitor(monitor, 1));
                    isOpen = session.isOpen();
                    if (!isOpen) {
                        session.open(new SubProgressMonitor(monitor, 1));
                    }

                    ExportAction exportAction = new ExportAction(session, dRepresentationsToExportAsImage,
                            outputPath, imageFormat, exportToHtml);
                    exportAction.run(new SubProgressMonitor(monitor, 7));

                } finally {
                    if (!isOpen && session != null) {
                        session.close(new SubProgressMonitor(monitor, 1));
                    }
                    monitor.done();
                }
            }
        };

        final ProgressMonitorDialog pmd = new ProgressMonitorDialog(shell);
        try {
            pmd.run(false, false, exportAllRepresentationsRunnable);
        } catch (final InvocationTargetException e) {
            SiriusEditPlugin.getPlugin().getLog()
                    .log(new Status(IStatus.ERROR, SiriusEditPlugin.ID, e.getLocalizedMessage(), e));
            MessageDialog.openError(shell, "Error", e.getTargetException().getMessage());
        } catch (final InterruptedException e) {
            SiriusEditPlugin.getPlugin().getLog()
                    .log(new Status(IStatus.ERROR, SiriusEditPlugin.ID, e.getLocalizedMessage(), e));
            MessageDialog.openInformation(shell, "Cancelled", e.getMessage());
        } finally {
            pmd.close();

        }
    } else {
        MessageDialog.openInformation(Display.getCurrent().getActiveShell(), "Export representations",
                "The selected session do not contain any representation to export.");
    }

}

From source file:org.eclipse.stp.bpmn.export.ImageExportWizard.java

License:Open Source License

/**
 * Does the same thing as the CopyToImageAction#run() method.
 * // w  w  w  .j a v  a  2s . c  om
 */
@SuppressWarnings("unchecked") //$NON-NLS-1$
@Override
public boolean performFinish() {
    List exporting = ((IExportImagePage) imagePage).getSelectedResources();
    if (exporting.isEmpty()) {
        ((DialogPage) imagePage)
                .setErrorMessage(BpmnDiagramMessages.ImageExportWizard_NoResourcesSelectedError);
        return false;
    }
    for (Object toExport : exporting) {
        if (toExport == null || !(toExport instanceof IFile)) {
            return false;
        }
        if (!((IFile) toExport).getFileExtension().equals("bpmn_diagram")) { //$NON-NLS-1$
            ((DialogPage) imagePage)
                    .setErrorMessage(BpmnDiagramMessages.ImageExportWizard_InvalidExtensionError);
            return false;
        }
    }

    // if more than one diagram is selected.
    if (exporting.size() > 1) {
        ((DialogPage) imagePage).setErrorMessage(BpmnDiagramMessages.ImageExportWizard_SelectOneDiagramError);
        return false;
    }
    // now getting serious and exporting for real

    Object selected = ((IExportImagePage) imagePage).getSelectedResources().get(0);

    IRunnableWithProgress runnable = createRunnable((IFile) selected, imagePage.getDestinationPath(),
            imagePage.getImageFormat());

    ProgressMonitorDialog progressMonitorDialog = new ProgressMonitorDialog(
            Display.getCurrent().getActiveShell());
    try {
        progressMonitorDialog.run(false, true, runnable);
    } catch (InvocationTargetException e) {
        Log.warning(DiagramUIRenderPlugin.getInstance(), DiagramUIRenderStatusCodes.IGNORED_EXCEPTION_WARNING,
                e.getTargetException().getMessage(), e.getTargetException());

        if (e.getTargetException() instanceof OutOfMemoryError) {
            openErrorDialog(DiagramUIRenderMessages.CopyToImageAction_outOfMemoryMessage);
        } else if (e.getTargetException() instanceof SWTError) {
            /**
             * SWT returns an out of handles error when processing large
             * diagrams
             */
            openErrorDialog(DiagramUIRenderMessages.CopyToImageAction_outOfMemoryMessage);
        } else {
            openErrorDialog(e.getTargetException().getMessage());
        }
        return true;
    } catch (InterruptedException e) {
        /* the user pressed cancel */
        Log.warning(DiagramUIRenderPlugin.getInstance(), DiagramUIRenderStatusCodes.IGNORED_EXCEPTION_WARNING,
                e.getMessage(), e);
    }

    return true;
}

From source file:org.eclipse.sudoku.ui.actions.NewBoardAction.java

License:Open Source License

/**
 * This method provides feedback to the user while it runs the provided
 * {@link Runnable}./*from  w w  w.j a v a 2  s.  c om*/
 * 
 * @param runnable
 *            the runnable to run.
 */
private void runWithProgress(final Runnable runnable) {
    ProgressMonitorDialog progress = new ProgressMonitorDialog(window.getShell());
    try {
        progress.run(false, false, new IRunnableWithProgress() {
            public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                monitor.beginTask("Generating Sudoku board", IProgressMonitor.UNKNOWN);
                runnable.run();
                monitor.done();
            }
        });
    } catch (Exception e) {
        SudokuUiActivator.logError(e);
    }
}

From source file:org.eclipse.tcf.te.tcf.filesystem.ui.internal.operations.UiExecutor.java

License:Open Source License

public static IStatus execute(final IOperation operation) {
    final Display display = Display.getCurrent();
    Assert.isNotNull(display);/*  ww  w  .j a v a  2  s .  com*/
    final Shell parent = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
    final ProgressMonitorDialog dlg = new ProgressMonitorDialog(parent);
    dlg.setOpenOnRun(false);

    display.timerExec(500, new Runnable() {
        @Override
        public void run() {
            Shell shell = dlg.getShell();
            if (shell != null && !shell.isDisposed()) {
                Shell activeShell = display.getActiveShell();
                if (activeShell == null || activeShell == parent) {
                    dlg.open();
                } else {
                    display.timerExec(500, this);
                }
            }
        }
    });
    final AtomicReference<IStatus> ref = new AtomicReference<IStatus>();
    try {
        dlg.run(true, true, new IRunnableWithProgress() {
            @Override
            public void run(IProgressMonitor monitor) {
                ref.set(operation.run(monitor));
            }
        });
    } catch (InvocationTargetException e) {
        ref.set(StatusHelper.getStatus(e.getTargetException()));
    } catch (InterruptedException e) {
        return Status.CANCEL_STATUS;
    }
    IStatus status = ref.get();
    if (!status.isOK() && status.getMessage().length() > 0) {
        ErrorDialog.openError(parent, operation.getName(), Messages.UiExecutor_errorRunningOperation, status);
        UIPlugin.getDefault().getLog().log(status);
    }
    return status;
}

From source file:org.eclipse.tcf.te.tcf.ui.activator.UIPlugin.java

License:Open Source License

@Override
public void start(BundleContext context) throws Exception {
    super.start(context);
    plugin = this;

    // Create and register the workbench listener instance
    listener = new IWorkbenchListener() {

        @Override//from   ww  w  .j  a  v  a2 s. com
        public boolean preShutdown(IWorkbench workbench, boolean forced) {
            boolean proceedShutdown = true;

            // If there are workbench listener registered here, than
            // invoke them now before closing all the channels.
            Object[] candidates = listeners.getListeners();
            for (Object listener : candidates) {
                if (!(listener instanceof IWorkbenchListener))
                    continue;
                proceedShutdown &= ((IWorkbenchListener) listener).preShutdown(workbench, forced);
                if (!proceedShutdown && !forced)
                    break;
            }

            if (proceedShutdown || forced) {
                final IPeerModel model = ModelManager.getPeerModel(true);
                if (model != null) {
                    final List<IPeerNode> peerNodes = new ArrayList<IPeerNode>();
                    for (IPeerNode peerNode : model.getPeerNodes()) {
                        if (peerNode.isConnectStateChangeActionAllowed(IConnectable.ACTION_DISCONNECT)) {
                            peerNodes.add(peerNode);
                        }
                    }

                    if (!peerNodes.isEmpty()) {
                        IRunnableWithProgress dialogRunnable = new IRunnableWithProgress() {
                            @Override
                            public void run(final IProgressMonitor monitor)
                                    throws InvocationTargetException, InterruptedException {
                                ProgressHelper.setTaskName(monitor, "Disconnecting Connections..."); //$NON-NLS-1$

                                final AsyncCallbackCollector collector = new AsyncCallbackCollector();

                                Protocol.invokeAndWait(new Runnable() {
                                    @Override
                                    public void run() {
                                        // Loop them and check if disconnect is available
                                        for (IPeerNode peerNode : peerNodes) {
                                            if (peerNode.isConnectStateChangeActionAllowed(
                                                    IConnectable.ACTION_DISCONNECT)) {
                                                peerNode.changeConnectState(IConnectable.ACTION_DISCONNECT,
                                                        new AsyncCallbackCollector.SimpleCollectorCallback(
                                                                collector),
                                                        null);
                                            }
                                        }

                                        collector.initDone();
                                    }
                                });

                                ExecutorsUtil.waitAndExecute(0, new IConditionTester() {
                                    @Override
                                    public boolean isConditionFulfilled() {
                                        return collector.getConditionTester().isConditionFulfilled()
                                                || (monitor != null && monitor.isCanceled());
                                    }

                                    @Override
                                    public void cleanup() {
                                    }
                                });
                            }

                        };

                        ProgressMonitorDialog dialog = new ProgressMonitorDialog(
                                workbench.getActiveWorkbenchWindow().getShell());
                        try {
                            dialog.run(true, true, dialogRunnable);
                        } catch (Exception e) {
                        }
                    }
                }

                // Close all channels now
                Tcf.getChannelManager().closeAll(!Protocol.isDispatchThread());
            }

            return proceedShutdown;
        }

        @Override
        public void postShutdown(IWorkbench workbench) {
            // If there are workbench listener registered here, than invoke them now.
            Object[] candidates = listeners.getListeners();
            for (Object listener : candidates) {
                if (!(listener instanceof IWorkbenchListener))
                    continue;
                ((IWorkbenchListener) listener).postShutdown(workbench);
            }
        }
    };
    PlatformUI.getWorkbench().addWorkbenchListener(listener);
    peerModelListener = new EditorPeerModelListener();
    Protocol.invokeLater(new Runnable() {
        @Override
        public void run() {
            ModelManager.getPeerModel().addListener(peerModelListener);
        }
    });
}

From source file:org.eclipse.tcf.te.ui.controls.net.RemoteHostAddressControl.java

License:Open Source License

/**
 * If the user entered a host name, we have to validate that we can really resolve the name
 * to an IP address. Because this may really take a while, give the user the feedback what
 * we are actually doing.//from  www.j  av  a  2  s.  c  o m
 */
private void onCheckAddress() {
    ProgressMonitorDialog dialog = new ProgressMonitorDialog(getParentControl().getShell());
    try {
        dialog.run(false, false, new IRunnableWithProgress() {
            private final String address = getEditFieldControlText();
            private final Control control = getEditFieldControl();
            private final IDialogPage parentPage = getParentPage();

            /* (non-Javadoc)
             * @see org.eclipse.jface.operation.IRunnableWithProgress#run(org.eclipse.core.runtime.IProgressMonitor)
             */
            @Override
            public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                try {
                    monitor.setTaskName(getTaskNameCheckNameAddress());
                    InetAddress[] addresses = InetAddress.getAllByName(address);
                    if (Platform.inDebugMode() && addresses != null) {
                        StringBuilder message = new StringBuilder();
                        message.append("RemoteHostAddressControl: Name '"); //$NON-NLS-1$
                        message.append(address);
                        message.append("' resolves to: "); //$NON-NLS-1$
                        boolean firstAddress = true;
                        for (InetAddress address : addresses) {
                            if (!firstAddress)
                                message.append(", "); //$NON-NLS-1$
                            message.append(address.getHostAddress());
                            firstAddress = false;
                        }

                        IStatus status = new Status(IStatus.WARNING, UIPlugin.getUniqueIdentifier(),
                                message.toString());
                        UIPlugin.getDefault().getLog().log(status);
                    }

                    setCheckResultMessage(IMessageProvider.INFORMATION,
                            getInformationTextCheckNameAddressSuccess());
                } catch (Exception e) {
                    setCheckResultMessage(IMessageProvider.WARNING, getErrorTextCheckNameAddressFailed());
                    control.setFocus();
                } finally {
                    // Trigger the wizard container update
                    IWizardContainer container = null;

                    try {
                        // Try to get the wizard container from the parent page
                        if (parentPage != null) {
                            Class<?>[] paramTypes = new Class[0];
                            Object[] args = new Object[0];
                            final Method method = parentPage.getClass().getMethod("getContainer", paramTypes); //$NON-NLS-1$
                            if (!method.isAccessible()) {
                                AccessController.doPrivileged(new PrivilegedAction<Object>() {
                                    @Override
                                    public Object run() {
                                        method.setAccessible(true);
                                        return null;
                                    }
                                });
                            }
                            Object result = method.invoke(parentPage, args);
                            if (result instanceof IWizardContainer) {
                                container = (IWizardContainer) result;
                            }
                        }
                    } catch (Exception e) {
                        // If the object does not have a "getContainer()" method,
                        // or the invocation fails or the access to the method
                        // is denied, we are done here and break the loop
                        container = null;
                    }

                    if (container != null) {
                        container.updateButtons();
                        container.updateMessage();
                    }
                }
            }
        });
    } catch (Exception e) {
    }
}