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

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

Introduction

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

Prototype

public void setBlockOnOpen(boolean shouldBlock) 

Source Link

Document

Sets whether the open method should block until the window closes.

Usage

From source file:org.eclipse.thym.ui.internal.engine.AvailableCordovaEnginesSection.java

License:Open Source License

private void handleSearch(final Composite parent) {
    DirectoryDialog directoryDialog = new DirectoryDialog(parent.getShell());
    directoryDialog.setMessage("Select the directory in which to search for hybrid mobile engines");
    directoryDialog.setText("Search for Hybrid Mobile Engines");

    String pathStr = directoryDialog.open();
    if (pathStr == null)
        return;/*from  ww  w  . j a  v a2  s.co m*/

    final IPath path = new Path(pathStr);
    final ProgressMonitorDialog dialog = new ProgressMonitorDialog(parent.getShell());
    dialog.setBlockOnOpen(false);
    dialog.setCancelable(true);
    dialog.open();
    final EngineSearchListener listener = new EngineSearchListener() {

        @Override
        public void engineFound(HybridMobileEngine engine) {
            addPathToPreference(engine.getLocation());
            getEngineProvider().engineFound(engine);
        }
    };

    IRunnableWithProgress runnable = new IRunnableWithProgress() {

        @Override
        public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            List<HybridMobileEngineLocator> locators = HybridCore.getEngineLocators();
            for (HybridMobileEngineLocator locator : locators) {
                locator.searchForRuntimes(path, listener, monitor);
            }
            parent.getDisplay().asyncExec(new Runnable() {

                @Override
                public void run() {
                    updateAvailableEngines();
                }
            });
        }
    };

    try {
        dialog.run(true, true, runnable);
    } catch (InvocationTargetException e) {
        if (e.getTargetException() != null) {
            if (e.getTargetException() instanceof CoreException) {
                StatusManager.handle((CoreException) e.getTargetException());
            } else {
                ErrorDialog.openError(parent.getShell(), "Local Engine Search Error", null,
                        new Status(IStatus.ERROR, HybridUI.PLUGIN_ID,
                                "Error when searching for local hybrid mobile engines",
                                e.getTargetException()));
            }
        }
    } catch (InterruptedException e) {
        HybridUI.log(IStatus.ERROR, "Search for Cordova Engines error", e);
    }
}

From source file:org.eclipse.ui.tests.dialogs.UIDialogs.java

License:Open Source License

public void testProgressInformation() {
    ProgressMonitorDialog dialog = new ProgressMonitorDialog(getShell());
    dialog.setBlockOnOpen(true);
    DialogCheck.assertDialog(dialog, this);
}

From source file:org.eclipse.ui.tests.dialogs.UIDialogsAuto.java

License:Open Source License

public void testProgressInformation() {
    ProgressMonitorDialog dialog = new ProgressMonitorDialog(getShell());
    dialog.setBlockOnOpen(true);
    DialogCheck.assertDialogTexts(dialog, this);
}

From source file:org.eclipse.wst.server.ui.internal.RuntimePreferencePage.java

License:Open Source License

/**
 * Create the preference options.//from   w w w  .  j  a va  2s  .  c  o  m
 *
 * @param parent org.eclipse.swt.widgets.Composite
 * @return org.eclipse.swt.widgets.Control
 */
protected Control createContents(Composite parent) {
    initializeDialogUnits(parent);
    PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, ContextIds.PREF_GENERAL);

    Composite composite = new Composite(parent, SWT.NONE);
    GridLayout layout = new GridLayout();
    layout.horizontalSpacing = convertHorizontalDLUsToPixels(4);
    layout.verticalSpacing = convertVerticalDLUsToPixels(3);
    layout.marginWidth = 0;
    layout.marginHeight = 0;
    layout.numColumns = 2;
    composite.setLayout(layout);
    GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL);
    composite.setLayoutData(data);

    Label label = new Label(composite, SWT.WRAP);
    data = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
    data.horizontalSpan = 2;
    label.setLayoutData(data);
    label.setText(Messages.preferenceRuntimesDescription);

    label = new Label(composite, SWT.WRAP);
    data = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
    data.horizontalSpan = 2;
    data.verticalIndent = 5;
    label.setLayoutData(data);
    label.setText(Messages.preferenceRuntimesTable);

    runtimeComp = new RuntimeComposite(composite, SWT.NONE, new RuntimeComposite.RuntimeSelectionListener() {
        public void runtimeSelected(IRuntime runtime) {
            if (runtime == null) {
                edit.setEnabled(false);
                remove.setEnabled(false);
                pathLabel.setText("");
            } else {
                IStatus status = runtime.validate(new NullProgressMonitor());
                if (status != null && status.getSeverity() == IStatus.ERROR) {
                    Color c = pathLabel.getDisplay().getSystemColor(SWT.COLOR_RED);
                    pathLabel.setForeground(c);
                    pathLabel.setText(status.getMessage());
                } else if (runtime.getLocation() != null) {
                    pathLabel.setForeground(edit.getForeground());
                    pathLabel.setText(runtime.getLocation() + "");
                } else
                    pathLabel.setText("");

                if (runtime.isReadOnly()) {
                    edit.setEnabled(false);
                    remove.setEnabled(false);
                } else {
                    if (runtime.getRuntimeType() != null)
                        edit.setEnabled(ServerUIPlugin.hasWizardFragment(runtime.getRuntimeType().getId()));
                    else
                        edit.setEnabled(false);
                    remove.setEnabled(true);
                }
            }
        }
    });
    runtimeComp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL));

    Composite buttonComp = new Composite(composite, SWT.NONE);
    layout = new GridLayout();
    layout.horizontalSpacing = 0;
    layout.verticalSpacing = convertVerticalDLUsToPixels(3);
    layout.marginWidth = 0;
    layout.marginHeight = 0;
    layout.numColumns = 1;
    buttonComp.setLayout(layout);
    data = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL);
    buttonComp.setLayoutData(data);

    Button add = SWTUtil.createButton(buttonComp, Messages.add);
    final RuntimeComposite runtimeComp2 = runtimeComp;
    add.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            if (showWizard(null) == Window.CANCEL)
                return;
            runtimeComp2.refresh();
        }
    });

    edit = SWTUtil.createButton(buttonComp, Messages.edit);
    edit.setEnabled(false);
    edit.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            IRuntime runtime = runtimeComp2.getSelectedRuntime();
            if (runtime != null) {
                IRuntimeWorkingCopy runtimeWorkingCopy = runtime.createWorkingCopy();
                if (showWizard(runtimeWorkingCopy) != Window.CANCEL) {
                    try {
                        runtimeComp2.refresh(runtime);
                    } catch (Exception ex) {
                        // ignore
                    }
                }
            }
        }
    });

    remove = SWTUtil.createButton(buttonComp, Messages.remove);
    remove.setEnabled(false);
    remove.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            IRuntime runtime = runtimeComp.getSelectedRuntime();
            if (removeRuntime(runtime))
                runtimeComp2.remove(runtime);
        }
    });

    Button search = SWTUtil.createButton(buttonComp, Messages.search);
    data = (GridData) search.getLayoutData();
    data.verticalIndent = 9;
    search.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            try {
                // select a target directory for the search
                DirectoryDialog directoryDialog = new DirectoryDialog(getShell());
                directoryDialog.setMessage(Messages.dialogRuntimeSearchMessage);
                directoryDialog.setText(Messages.dialogRuntimeSearchTitle);

                String pathStr = directoryDialog.open();
                if (pathStr == null)
                    return;

                final IPath path = new Path(pathStr);

                final ProgressMonitorDialog dialog = new ProgressMonitorDialog(getShell());
                dialog.setBlockOnOpen(false);
                dialog.setCancelable(true);
                dialog.open();
                final IProgressMonitor monitor = dialog.getProgressMonitor();
                final IRuntimeLocator[] locators = ServerPlugin.getRuntimeLocators();
                monitor.beginTask(Messages.dialogRuntimeSearchProgress, 100 * locators.length + 10);
                final List<IRuntimeWorkingCopy> list = new ArrayList<IRuntimeWorkingCopy>();

                final IRuntimeLocator.IRuntimeSearchListener listener = new IRuntimeLocator.IRuntimeSearchListener() {
                    public void runtimeFound(final IRuntimeWorkingCopy runtime) {
                        dialog.getShell().getDisplay().syncExec(new Runnable() {
                            public void run() {
                                monitor.subTask(runtime.getName());
                            }
                        });
                        list.add(runtime);
                    }
                };

                IRunnableWithProgress runnable = new IRunnableWithProgress() {
                    public void run(IProgressMonitor monitor2) {
                        int size = locators.length;
                        for (int i = 0; i < size; i++) {
                            if (!monitor2.isCanceled())
                                try {
                                    locators[i].searchForRuntimes(path, listener, monitor2);
                                } catch (CoreException ce) {
                                    if (Trace.WARNING) {
                                        Trace.trace(Trace.STRING_WARNING,
                                                "Error locating runtimes: " + locators[i].getId(), ce);
                                    }
                                }
                        }
                        if (Trace.INFO) {
                            Trace.trace(Trace.STRING_INFO, "Done search");
                        }
                    }
                };
                dialog.run(true, true, runnable);

                if (Trace.FINER) {
                    Trace.trace(Trace.STRING_FINER, "Found runtimes: " + list.size());
                }

                if (!monitor.isCanceled()) {
                    if (list.isEmpty()) {
                        EclipseUtil.openError(getShell(), Messages.infoNoRuntimesFound);
                        return;
                    }
                    monitor.worked(5);
                    if (Trace.FINER) {
                        Trace.trace(Trace.STRING_FINER, "Removing duplicates");
                    }
                    List<IRuntime> good = new ArrayList<IRuntime>();
                    Iterator iterator2 = list.iterator();
                    while (iterator2.hasNext()) {
                        boolean dup = false;
                        IRuntime wc = (IRuntime) iterator2.next();

                        IRuntime[] runtimes = ServerCore.getRuntimes();
                        if (runtimes != null) {
                            int size = runtimes.length;
                            for (int i = 0; i < size; i++) {
                                if (runtimes[i].getLocation() != null
                                        && runtimes[i].getLocation().equals(wc.getLocation()))
                                    dup = true;
                            }
                        }
                        if (!dup)
                            good.add(wc);
                    }
                    monitor.worked(5);

                    if (Trace.FINER) {
                        Trace.trace(Trace.STRING_FINER, "Adding runtimes: " + good.size());
                    }
                    Iterator iterator = good.iterator();
                    while (iterator.hasNext()) {
                        IRuntimeWorkingCopy wc = (IRuntimeWorkingCopy) iterator.next();
                        wc.save(false, monitor);
                    }
                    monitor.done();
                }
                dialog.close();
            } catch (Exception ex) {
                if (Trace.SEVERE) {
                    Trace.trace(Trace.STRING_SEVERE, "Error finding runtimes", ex);
                }
            }
            runtimeComp2.refresh();
        }
    });

    Button columnsButton = SWTUtil.createButton(buttonComp, Messages.actionColumns);
    data = (GridData) columnsButton.getLayoutData();
    final RuntimePreferencePage thisClass = this;
    columnsButton.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            ConfigureColumns.forTable(runtimeComp.getTable(), thisClass);
        }
    });

    pathLabel = new Label(parent, SWT.NONE);
    pathLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

    Dialog.applyDialogFont(composite);

    return composite;
}

From source file:org.eclipse.wst.server.ui.internal.view.servers.RemoveModuleAction.java

License:Open Source License

protected void removeModules(final IModule[] modules) {
    try {/*w w  w.ja  v  a2s  . c om*/
        final ProgressMonitorDialog dialog = new ProgressMonitorDialog(shell);
        dialog.setBlockOnOpen(false);
        dialog.setCancelable(true);
        IRunnableWithProgress runnable = new IRunnableWithProgress() {
            public void run(IProgressMonitor monitor) {
                try {
                    IServerWorkingCopy wc = server.createWorkingCopy();
                    if (monitor.isCanceled()) {
                        return;
                    }
                    wc.modifyModules(null, modules, monitor);
                    if (monitor.isCanceled()) {
                        return;
                    }
                    server = wc.save(true, monitor);
                    if (Trace.INFO) {
                        Trace.trace(Trace.STRING_INFO, "Done save server configuration in RemoveModuleAction.");
                    }
                } catch (CoreException e) {
                    if (Trace.WARNING) {
                        Trace.trace(Trace.STRING_WARNING,
                                "Failed to save server configuration. Could not remove module", e);
                    }
                    saveServerException = e;
                }
            }
        };
        dialog.run(true, true, runnable);

        // Error when saving server so do not proceed on the remove action.
        if (saveServerException != null) {
            return;
        }

        if (server.getServerState() != IServer.STATE_STOPPED
                && ServerUIPlugin.getPreferences().getPublishOnAddRemoveModule()) {
            final IAdaptable info = new IAdaptable() {
                public Object getAdapter(Class adapter) {
                    if (Shell.class.equals(adapter))
                        return shell;
                    if (String.class.equals(adapter))
                        return "user";
                    return null;
                }
            };
            server.publish(IServer.PUBLISH_INCREMENTAL, null, info, null);
        }
    } catch (Exception e) {
        if (Trace.WARNING) {
            Trace.trace(Trace.STRING_WARNING, "Could not remove module", e);
        }
    }
}

From source file:org.eclipse.zest.examples.cloudio.application.actions.LoadFileAction.java

License:Open Source License

@Override
public void run(IAction action) {
    FileDialog dialog = new FileDialog(getShell(), SWT.OPEN);

    dialog.setText("Select text file...");
    String sourceFile = dialog.open();
    if (sourceFile == null)
        return;/*  ww w . j a  v  a 2 s.c o  m*/
    ProgressMonitorDialog pd = new ProgressMonitorDialog(getShell());
    try {
        List<Type> types = TypeCollector.getData(new File(sourceFile), "UTF-8");
        pd.setBlockOnOpen(false);
        pd.open();
        pd.getProgressMonitor().beginTask("Generating cloud...", 200);
        TagCloudViewer viewer = getViewer();
        viewer.setInput(types, pd.getProgressMonitor());
        viewer.getCloud().layoutCloud(pd.getProgressMonitor(), false);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        pd.close();
    }
}

From source file:org.eclipse.zest.examples.cloudio.application.ui.TagCloudViewPart.java

License:Open Source License

private void createSideTab(SashForm form) {
    Composite parent = new Composite(form, SWT.NONE);
    parent.setLayout(new GridLayout());
    parent.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    options = new CloudOptionsComposite(parent, SWT.NONE, viewer) {

        protected Group addLayoutButtons(Composite parent) {
            Group buttons = super.addLayoutButtons(parent);

            Label l = new Label(buttons, SWT.NONE);
            l.setText("X Axis Variation");
            final Combo xAxis = new Combo(buttons, SWT.DROP_DOWN | SWT.READ_ONLY);
            xAxis.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
            xAxis.setItems(new String[] { "0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100" });
            xAxis.select(2);/*from   w  w  w.  j  a  v  a  2  s . com*/
            xAxis.addSelectionListener(new SelectionListener() {

                @Override
                public void widgetSelected(SelectionEvent e) {
                    String item = xAxis.getItem(xAxis.getSelectionIndex());
                    layouter.setOption(DefaultLayouter.X_AXIS_VARIATION, Integer.parseInt(item));

                }

                @Override
                public void widgetDefaultSelected(SelectionEvent e) {
                }
            });

            l = new Label(buttons, SWT.NONE);
            l.setText("Y Axis Variation");
            final Combo yAxis = new Combo(buttons, SWT.DROP_DOWN | SWT.READ_ONLY);
            yAxis.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
            yAxis.setItems(new String[] { "0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100" });
            yAxis.select(1);
            yAxis.addSelectionListener(new SelectionListener() {

                @Override
                public void widgetSelected(SelectionEvent e) {
                    String item = yAxis.getItem(yAxis.getSelectionIndex());
                    layouter.setOption(DefaultLayouter.Y_AXIS_VARIATION, Integer.parseInt(item));
                }

                @Override
                public void widgetDefaultSelected(SelectionEvent e) {
                }
            });

            Button run = new Button(buttons, SWT.NONE);
            run.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
            run.setText("Re-Position");
            run.addSelectionListener(new SelectionListener() {

                @Override
                public void widgetSelected(SelectionEvent e) {
                    final ProgressMonitorDialog dialog = new ProgressMonitorDialog(
                            viewer.getControl().getShell());
                    dialog.setBlockOnOpen(false);
                    dialog.open();
                    dialog.getProgressMonitor().beginTask("Layouting tag cloud...", 100);
                    viewer.reset(dialog.getProgressMonitor(), false);
                    dialog.close();
                }

                @Override
                public void widgetDefaultSelected(SelectionEvent e) {
                }
            });
            Button layout = new Button(buttons, SWT.NONE);
            layout.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
            layout.setText("Re-Layout");
            layout.addSelectionListener(new SelectionListener() {

                @Override
                public void widgetSelected(SelectionEvent e) {
                    ProgressMonitorDialog dialog = new ProgressMonitorDialog(viewer.getControl().getShell());
                    dialog.setBlockOnOpen(false);
                    dialog.open();
                    dialog.getProgressMonitor().beginTask("Layouting tag cloud...", 200);
                    viewer.setInput(viewer.getInput(), dialog.getProgressMonitor());
                    viewer.reset(dialog.getProgressMonitor(), false);
                    dialog.close();
                }

                @Override
                public void widgetDefaultSelected(SelectionEvent e) {
                }
            });
            return buttons;
        };

    };
    GridData gd = new GridData(SWT.FILL, SWT.CENTER, true, false);
    options.setLayoutData(gd);
}

From source file:org.jboss.tools.aerogear.hybrid.ui.internal.engine.AvailableCordovaEnginesSection.java

License:Open Source License

private void handleSearch(final Composite parent) {
    DirectoryDialog directoryDialog = new DirectoryDialog(parent.getShell());
    directoryDialog.setMessage("Select the directory in which to search for hybrid mobile engines");
    directoryDialog.setText("Search for Hybrid Mobile Engines");

    String pathStr = directoryDialog.open();
    if (pathStr == null)
        return;/*from   w w  w  .  j  a va 2s  . c  o  m*/

    final IPath path = new Path(pathStr);
    final ProgressMonitorDialog dialog = new ProgressMonitorDialog(parent.getShell());
    dialog.setBlockOnOpen(false);
    dialog.setCancelable(true);
    dialog.open();
    final EngineSearchListener listener = new EngineSearchListener() {

        @Override
        public void libraryFound(PlatformLibrary library) {
            addPathToPreference(library.getLocation());
            getEngineProvider().libraryFound(library);
        }
    };

    IRunnableWithProgress runnable = new IRunnableWithProgress() {

        @Override
        public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            List<HybridMobileEngineLocator> locators = HybridCore.getEngineLocators();
            for (HybridMobileEngineLocator locator : locators) {
                locator.searchForRuntimes(path, listener, monitor);
            }
            parent.getDisplay().asyncExec(new Runnable() {

                @Override
                public void run() {
                    updateAvailableEngines();
                }
            });
        }
    };

    try {
        dialog.run(true, true, runnable);
    } catch (InvocationTargetException e) {
        if (e.getTargetException() != null) {
            if (e.getTargetException() instanceof CoreException) {
                StatusManager.handle((CoreException) e.getTargetException());
            } else {
                ErrorDialog.openError(parent.getShell(), "Local Engine Search Error", null,
                        new Status(IStatus.ERROR, HybridUI.PLUGIN_ID,
                                "Error when searching for local hybrid mobile engines",
                                e.getTargetException()));
            }
        }
    } catch (InterruptedException e) {
        HybridUI.log(IStatus.ERROR, "Search for Cordova Engines error", e);
    }
}

From source file:org.python.pydev.editor.actions.PySelectInterpreter.java

License:Open Source License

@Override
public void run(IAction action) {
    try {/*  w w w . j a v  a2  s. com*/
        PyEdit editor = getPyEdit();
        IPythonNature nature = editor.getPythonNature();
        if (nature != null) {
            IInterpreterManager interpreterManager = nature.getRelatedInterpreterManager();

            final IInterpreterInfo[] interpreterInfos = interpreterManager.getInterpreterInfos();
            if (interpreterInfos == null || interpreterInfos.length == 0) {
                PyDialogHelpers.openWarning("No interpreters available",
                        "Unable to change default interpreter because no interpreters are available (add more interpreters in the related preferences page).");
                return;
            }
            if (interpreterInfos.length == 1) {
                PyDialogHelpers.openWarning("Only 1 interpreters available",
                        "Unable to change default interpreter because only 1 interpreter is configured (add more interpreters in the related preferences page).");
                return;
            }
            // Ok, more than 1 found.
            IWorkbenchWindow workbenchWindow = EditorUtils.getActiveWorkbenchWindow();
            Assert.isNotNull(workbenchWindow);
            SelectionDialog listDialog = AbstractInterpreterPreferencesPage.createChooseIntepreterInfoDialog(
                    workbenchWindow, interpreterInfos, "Select interpreter to be made the default.", false);

            int open = listDialog.open();
            if (open != ListDialog.OK || listDialog.getResult().length != 1) {
                return;
            }
            Object[] result = listDialog.getResult();
            if (result == null || result.length == 0) {
                return;

            }
            final IInterpreterInfo selectedInterpreter = ((IInterpreterInfo) result[0]);
            if (selectedInterpreter != interpreterInfos[0]) {
                // Ok, some interpreter (which wasn't already the default) was selected.
                Arrays.sort(interpreterInfos, (a, b) -> {
                    if (a == selectedInterpreter) {
                        return -1;
                    }
                    if (b == selectedInterpreter) {
                        return 1;
                    }
                    return 0; // Don't change order for the others.
                });

                Shell shell = EditorUtils.getShell();

                //this is the default interpreter
                ProgressMonitorDialog monitorDialog = new AsynchronousProgressMonitorDialog(shell);
                monitorDialog.setBlockOnOpen(false);

                try {
                    IRunnableWithProgress operation = new IRunnableWithProgress() {

                        @Override
                        public void run(IProgressMonitor monitor)
                                throws InvocationTargetException, InterruptedException {
                            monitor.beginTask("Restoring PYTHONPATH", IProgressMonitor.UNKNOWN);
                            try {
                                Set<String> interpreterNamesToRestore = new HashSet<>(); // i.e.: don't restore the PYTHONPATH (only order was changed).
                                interpreterManager.setInfos(interpreterInfos, interpreterNamesToRestore,
                                        monitor);
                            } finally {
                                monitor.done();
                            }
                        }
                    };

                    monitorDialog.run(true, true, operation);

                } catch (Exception e) {
                    Log.log(e);
                }
            }
        }
    } catch (Exception e) {
        Log.log(e);
    }
}

From source file:org.python.pydev.ui.pythonpathconf.AbstractInterpreterEditor.java

License:Open Source License

/**
 * @see org.eclipse.jface.preference.ListEditor#doFillIntoGrid(org.eclipse.swt.widgets.Composite, int)
 *//*w w  w . ja va 2 s  .c om*/
@Override
protected void doFillIntoGrid(Composite parent, int numColumns) {
    super.doFillIntoGrid(parent, numColumns);
    GridData gd = new GridData();

    tabFolder = new TabFolder(parent, SWT.None);
    gd = new GridData();
    gd.horizontalAlignment = SWT.FILL;
    gd.verticalAlignment = SWT.FILL;
    gd.grabExcessVerticalSpace = true;
    gd.horizontalSpan = numColumns;
    tabFolder.setLayoutData(gd);

    createTreeLibsControlTab();

    //----------------------- FORCED BUILTINS
    forcedBuiltins = new AbstractListWithNewRemoveControl(this) {

        @Override
        protected List<String> getStringsFromInfo(InterpreterInfo info) {
            ArrayList<String> ret = new ArrayList<String>();
            for (Iterator<String> iter = info.forcedLibsIterator(); iter.hasNext();) {
                ret.add(iter.next());
            }
            return ret;
        }

        @Override
        protected void removeSelectedFrominfo(InterpreterInfo info, String[] builtins) {
            for (String builtin : builtins) {
                info.removeForcedLib(builtin);
            }
            exeOrJarOfInterpretersWithBuiltinsChanged.add(info.getExecutableOrJar());
        }

        @Override
        protected String getInput() {
            IInputValidator validator = new IInputValidator() {

                public String isValid(String newText) {
                    for (char c : newText.toCharArray()) {
                        if (!Character.isJavaIdentifierPart(c) && c != ' ' && c != ',' && c != '.') {
                            return "Can only accept valid python module names (char: '" + c + "' not accepted)";
                        }
                    }
                    return null;
                }
            };
            InputDialog d = new InputDialog(getShell(), "Builtin to add", "Builtin to add (comma separated)",
                    "", validator);

            int retCode = d.open();
            String builtins = null;
            if (retCode == InputDialog.OK) {
                builtins = d.getValue();
            }
            return builtins;
        }

        @Override
        protected void addInputToInfo(InterpreterInfo info, String builtins) {
            java.util.List<String> split = StringUtils.splitAndRemoveEmptyTrimmed(builtins, ',');
            for (String string : split) {
                String trimmed = string.trim();
                if (trimmed.length() > 0) {
                    info.addForcedLib(trimmed);
                }
            }
            exeOrJarOfInterpretersWithBuiltinsChanged.add(info.getExecutableOrJar());
        }

    };
    forcedBuiltins.createTab("Forced Builtins", "Forced Builtins (check <a>Manual</a> for more info).");

    //----------------------- PREDEFINED COMPLETIONS
    predefinedCompletions = new AbstractListWithNewRemoveControl(this) {

        private Button addAPIBt;

        @Override
        protected List<String> getStringsFromInfo(InterpreterInfo info) {
            return info.getPredefinedCompletionsPath();
        }

        @Override
        protected void removeSelectedFrominfo(InterpreterInfo info, String[] items) {
            for (String item : items) {
                info.removePredefinedCompletionPath(item);
            }
            exeOrJarOfInterpretersWithPredefinedChanged.add(info.getExecutableOrJar());
        }

        @Override
        protected String getInput() {
            DirectoryDialog dialog = new DirectoryDialog(getShell());
            dialog.setFilterPath(lastDirectoryDialogPath);
            String filePath = dialog.open();
            if (filePath != null) {
                lastDirectoryDialogPath = filePath;
            }
            return filePath;
        }

        @Override
        protected void addInputToInfo(InterpreterInfo info, String item) {
            info.addPredefinedCompletionsPath(item);
            exeOrJarOfInterpretersWithPredefinedChanged.add(info.getExecutableOrJar());
        }

        @Override
        protected void createButtons(AbstractInterpreterEditor interpreterEditor) {
            super.createButtons(interpreterEditor);
            addAPIBt = interpreterEditor.createBt(box, "Add from QScintilla api file", this);//$NON-NLS-1$
        }

        @Override
        public void widgetDisposed(DisposeEvent event) {
            super.widgetDisposed(event);
            if (addAPIBt != null) {
                addAPIBt.dispose();
                addAPIBt = null;
            }
        }

        @Override
        public void widgetSelected(SelectionEvent event) {
            super.widgetSelected(event);
            Widget widget = event.widget;
            if (widget == addAPIBt) {
                addAPIBt();
            }
        }

        private void addAPIBt() {
            final AbstractInterpreterEditor interpreterEditor = this.container.get();
            Assert.isNotNull(interpreterEditor);

            final InterpreterInfo info = interpreterEditor.getSelectedInfo();
            if (info != null) {
                FileDialog dialog = new FileDialog(getShell(), SWT.PRIMARY_MODAL | SWT.MULTI);

                dialog.setFilterExtensions(new String[] { "*.api" });
                dialog.setText("Select .api file to be converted to .pypredef.");

                dialog.setFilterPath(lastFileDialogPath);
                final String filePath = dialog.open();
                if (filePath != null) {
                    lastFileDialogPath = filePath;
                    File filePath1 = new File(filePath);
                    final String dir = filePath1.getParent();

                    IInputValidator validator = new IInputValidator() {

                        public String isValid(String newText) {
                            if (newText.length() == 0) {
                                return "Number not provided.";
                            }
                            try {
                                Integer.parseInt(newText);
                            } catch (NumberFormatException e) {
                                return "The string: " + newText + " is not a valid integer.";
                            }
                            return null;
                        }
                    };
                    final InputDialog d = new InputDialog(getShell(), "Number of tokens to consider module",
                            "Please specify the number of tokens to consider a module from the .api file\n\n"
                                    + "i.e.: if there's a PyQt4.QtCore.QObject and PyQt4.QtCore is a module and QtObject "
                                    + "is the first class, the number of tokens to consider a module would be 2 (one for "
                                    + "PyQt4 and another for QtCore).",
                            "", validator);

                    int retCode = d.open();
                    final ByteArrayOutputStream output = new ByteArrayOutputStream();
                    if (retCode == InputDialog.OK) {

                        ProgressMonitorDialog monitorDialog = new AsynchronousProgressMonitorDialog(getShell());
                        monitorDialog.setBlockOnOpen(false);
                        final Exception[] exception = new Exception[1];
                        try {
                            IRunnableWithProgress operation = new IRunnableWithProgress() {

                                public void run(final IProgressMonitor monitor)
                                        throws InvocationTargetException, InterruptedException {
                                    monitor.beginTask("Restoring PYTHONPATH", IProgressMonitor.UNKNOWN);

                                    IPythonInterpreter interpreter = JythonPlugin.newPythonInterpreter(false,
                                            false);
                                    interpreter.setErr(output);
                                    interpreter.setOut(output);
                                    HashMap<String, Object> locals = new HashMap<String, Object>();
                                    locals.put("api_file", filePath);
                                    locals.put("parts_for_module", d.getValue());
                                    locals.put("cancel_monitor", monitor);
                                    try {
                                        JythonPlugin.exec(locals, "convert_api_to_pypredef.py", interpreter);
                                    } catch (Exception e) {
                                        Log.log(e + "\n\n" + output.toString());
                                        exception[0] = e;
                                    }

                                    monitor.done();
                                }
                            };

                            monitorDialog.run(true, true, operation);

                        } catch (Exception e) {
                            Log.log(e);
                        }

                        Exception e = exception[0];
                        String contents = output.toString();
                        if (e == null && contents.indexOf("SUCCESS") != -1) {
                            addInputToInfo(info, dir);
                            interpreterEditor.updateTree();
                        } else {
                            if (e != null) {
                                MessageDialog.openError(getShell(), "Error creating .pypredef files",
                                        e.getMessage() + "\n\n" + contents);
                            } else {
                                MessageDialog.openError(getShell(), "Error creating .pypredef files", contents);
                            }
                        }
                    }
                }
            }
        }

    };
    predefinedCompletions.createTab("Predefined",
            "Predefined completions (check <a>Manual</a> for more info).");
    createEnvironmentVariablesTab();
    createStringSubstitutionTab();

}