Search in sources :

Example 81 with IInputValidator

use of org.eclipse.jface.dialogs.IInputValidator in project Pydev by fabioz.

the class DjangoShell method run.

@Override
public void run(IAction action) {
    try {
        // this.launchDjangoCommand("shell", false);
        PythonNature nature = PythonNature.getPythonNature(selectedProject);
        if (nature == null) {
            MessageDialog.openError(EditorUtils.getShell(), "PyDev nature not found", "Unable to perform action because the Pydev nature is not properly set.");
            return;
        }
        IPythonPathNature pythonPathNature = nature.getPythonPathNature();
        String settingsModule = null;
        Map<String, String> variableSubstitution = null;
        try {
            variableSubstitution = pythonPathNature.getVariableSubstitution();
            settingsModule = variableSubstitution.get(DjangoConstants.DJANGO_SETTINGS_MODULE);
        } catch (Exception e1) {
            throw new RuntimeException(e1);
        }
        if (settingsModule == null) {
            InputDialog d = new InputDialog(EditorUtils.getShell(), "Settings module", "Please enter the settings module to be used.\n" + "\n" + "Note that it can be edited later in:\np" + "roject properties > pydev pythonpath > string substitution variables.", selectedProject.getName() + ".settings", new IInputValidator() {

                @Override
                public String isValid(String newText) {
                    if (newText.length() == 0) {
                        return "Text must be entered.";
                    }
                    for (char c : newText.toCharArray()) {
                        if (c == ' ') {
                            return "Whitespaces not accepted";
                        }
                        if (c != '.' && !Character.isJavaIdentifierPart(c)) {
                            return "Invalid char: " + c;
                        }
                    }
                    return null;
                }
            });
            int retCode = d.open();
            if (retCode == InputDialog.OK) {
                settingsModule = d.getValue();
                variableSubstitution.put(DjangoConstants.DJANGO_SETTINGS_MODULE, settingsModule);
                try {
                    pythonPathNature.setVariableSubstitution(variableSubstitution);
                } catch (Exception e) {
                    Log.log(e);
                }
            }
            if (settingsModule == null) {
                return;
            }
        }
        List<IPythonNature> natures = Collections.singletonList((IPythonNature) nature);
        PydevConsoleFactory consoleFactory = new PydevConsoleFactory();
        PydevConsoleLaunchInfo launchInfo = new PydevIProcessFactory().createLaunch(nature.getRelatedInterpreterManager(), nature.getProjectInterpreter(), nature.getPythonPathNature().getCompleteProjectPythonPath(nature.getProjectInterpreter(), nature.getRelatedInterpreterManager()), nature, natures);
        PydevConsoleInterpreter interpreter = PydevConsoleFactory.createPydevInterpreter(launchInfo, natures, launchInfo.encoding);
        String djangoAdditionalCommands = PydevDebugPlugin.getDefault().getPreferenceStore().getString(PydevConsoleConstants.DJANGO_INTERPRETER_CMDS);
        djangoAdditionalCommands = djangoAdditionalCommands.replace("${" + DjangoConstants.DJANGO_SETTINGS_MODULE + "}", settingsModule);
        // os.environ.setdefault("DJANGO_SETTINGS_MODULE", "fooproject.settings")
        consoleFactory.createConsole(interpreter, djangoAdditionalCommands);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : InputDialog(org.eclipse.jface.dialogs.InputDialog) PydevConsoleInterpreter(org.python.pydev.debug.newconsole.PydevConsoleInterpreter) IPythonNature(org.python.pydev.core.IPythonNature) PythonNature(org.python.pydev.plugin.nature.PythonNature) PydevConsoleFactory(org.python.pydev.debug.newconsole.PydevConsoleFactory) IPythonPathNature(org.python.pydev.core.IPythonPathNature) IPythonNature(org.python.pydev.core.IPythonNature) PydevConsoleLaunchInfo(org.python.pydev.debug.newconsole.env.PydevIProcessFactory.PydevConsoleLaunchInfo) PydevIProcessFactory(org.python.pydev.debug.newconsole.env.PydevIProcessFactory) IInputValidator(org.eclipse.jface.dialogs.IInputValidator)

Example 82 with IInputValidator

use of org.eclipse.jface.dialogs.IInputValidator in project Pydev by fabioz.

the class PyConvertSpaceToTab method getTabSpace.

/**
 * Currently returns an int of the Preferences' Tab Width.
 * @param textEditor
 *
 * @return Tab width in preferences
 */
protected static String getTabSpace(ITextEditor textEditor) {
    class NumberValidator implements IInputValidator {

        /*
             * @see IInputValidator#isValid(String)
             */
        @Override
        public String isValid(String input) {
            if (input == null || input.length() == 0) {
                return " ";
            }
            try {
                int i = Integer.parseInt(input);
                if (i <= 0) {
                    return "Must be more than 0.";
                }
            } catch (NumberFormatException x) {
                return x.getMessage();
            }
            return null;
        }
    }
    InputDialog inputDialog = new InputDialog(EditorUtils.getShell(), "Tab length", "How many spaces should be considered for each tab?", "" + DefaultIndentPrefs.get(textEditor).getTabWidth(), new NumberValidator());
    if (inputDialog.open() != InputDialog.OK) {
        return null;
    }
    int tabWidth = Integer.parseInt(inputDialog.getValue());
    return new FastStringBuffer(tabWidth).appendN(' ', tabWidth).toString();
}
Also used : InputDialog(org.eclipse.jface.dialogs.InputDialog) FastStringBuffer(org.python.pydev.shared_core.string.FastStringBuffer) IInputValidator(org.eclipse.jface.dialogs.IInputValidator)

Example 83 with IInputValidator

use of org.eclipse.jface.dialogs.IInputValidator in project Pydev by fabioz.

the class AbstractInterpreterEditor method renameSelection.

private void renameSelection() {
    int index = getSelectionIndex();
    if (index >= 0) {
        TreeItem curr = treeWithInterpreters.getItem(index);
        final String initialName = getNameFromTreeItem(curr);
        InputDialog d = new InputDialog(this.getShell(), "New name", "Please specify the new name of the interpreter.", initialName, new IInputValidator() {

            @Override
            public String isValid(String newText) {
                if (newText == null || newText.trim().equals("")) {
                    return "Please specify a non-empty name.";
                }
                newText = newText.trim();
                if (newText.equals(initialName)) {
                    return null;
                }
                return InterpreterConfigHelpers.getDuplicatedMessageError(newText, null, nameToInfo);
            }
        });
        int retCode = d.open();
        if (retCode == InputDialog.OK) {
            String newName = d.getValue().trim();
            if (!newName.equals(initialName)) {
                IInterpreterInfo info = this.nameToInfo.get(initialName);
                info.setName(newName);
                curr.setText(0, newName);
                this.nameToInfo.remove(initialName);
                this.nameToInfo.put(newName, info);
                this.exeOrJarOfInterpretersToRestore.add(info.getExecutableOrJar());
            }
        }
    }
}
Also used : InputDialog(org.eclipse.jface.dialogs.InputDialog) InterpreterInputDialog(org.python.pydev.ui.dialogs.InterpreterInputDialog) TreeItem(org.eclipse.swt.widgets.TreeItem) IInterpreterInfo(org.python.pydev.core.IInterpreterInfo) IInputValidator(org.eclipse.jface.dialogs.IInputValidator)

Example 84 with IInputValidator

use of org.eclipse.jface.dialogs.IInputValidator in project Pydev by fabioz.

the class AbstractInterpreterEditor method doFillIntoGrid.

/**
 * @see org.eclipse.jface.preference.ListEditor#doFillIntoGrid(org.eclipse.swt.widgets.Composite, int)
 */
@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);
    try {
        if (this.getShowPackageTab()) {
            packageTab.createPackageControlTab(tabFolder, exeOrJarOfInterpretersToRestore, interpreterManager);
        }
    } catch (Exception e1) {
        // Not really expected, just new code, so, let's protect until it matures.
        Log.log(e1);
    }
    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() {

                @Override
                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);
            // $NON-NLS-1$
            addAPIBt = interpreterEditor.createBt(box, "Add from QScintilla api file", this);
        }

        @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() {

                        @Override
                        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() {

                                @Override
                                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();
}
Also used : AsynchronousProgressMonitorDialog(org.python.pydev.shared_ui.utils.AsynchronousProgressMonitorDialog) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Widget(org.eclipse.swt.widgets.Widget) DisposeEvent(org.eclipse.swt.events.DisposeEvent) IRunnableWithProgress(org.eclipse.jface.operation.IRunnableWithProgress) Button(org.eclipse.swt.widgets.Button) Iterator(java.util.Iterator) SelectionEvent(org.eclipse.swt.events.SelectionEvent) InterpreterInfo(org.python.pydev.ast.interpreter_managers.InterpreterInfo) IInterpreterInfo(org.python.pydev.core.IInterpreterInfo) List(java.util.List) ArrayList(java.util.ArrayList) DirectoryDialog(org.eclipse.swt.widgets.DirectoryDialog) InputDialog(org.eclipse.jface.dialogs.InputDialog) InterpreterInputDialog(org.python.pydev.ui.dialogs.InterpreterInputDialog) AsynchronousProgressMonitorDialog(org.python.pydev.shared_ui.utils.AsynchronousProgressMonitorDialog) ProgressMonitorDialog(org.eclipse.jface.dialogs.ProgressMonitorDialog) TabFolder(org.eclipse.swt.widgets.TabFolder) ByteArrayOutputStream(java.io.ByteArrayOutputStream) InvocationTargetException(java.lang.reflect.InvocationTargetException) CancelException(org.python.pydev.shared_core.progress.CancelException) InvocationTargetException(java.lang.reflect.InvocationTargetException) IPythonInterpreter(org.python.pydev.shared_core.jython.IPythonInterpreter) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) GridData(org.eclipse.swt.layout.GridData) FileDialog(org.eclipse.swt.widgets.FileDialog) File(java.io.File) IInputValidator(org.eclipse.jface.dialogs.IInputValidator)

Example 85 with IInputValidator

use of org.eclipse.jface.dialogs.IInputValidator in project Pydev by fabioz.

the class ToStringLabelProvider method widgetSelected.

@Override
public void widgetSelected(SelectionEvent e) {
    Object source = e.getSource();
    if (source == btAdd) {
        InputDialog dialog = new InputDialog(getShell(), "Add custom command to list", "Add custom command to list", "", new IInputValidator() {

            @Override
            public String isValid(String newText) {
                if (newText.trim().length() == 0) {
                    return "Command not entered.";
                }
                if (input.contains(newText)) {
                    return "Command already entered.";
                }
                return null;
            }
        });
        int open = dialog.open();
        if (open == InputDialog.OK) {
            String value = dialog.getValue();
            input.add(value);
            // Save it.
            saveCurrentCommands(value);
            updateGui();
        }
    } else if (source == btRemove) {
        removeSelection();
    }
}
Also used : InputDialog(org.eclipse.jface.dialogs.InputDialog) Point(org.eclipse.swt.graphics.Point) IInputValidator(org.eclipse.jface.dialogs.IInputValidator)

Aggregations

IInputValidator (org.eclipse.jface.dialogs.IInputValidator)101 InputDialog (org.eclipse.jface.dialogs.InputDialog)88 Composite (org.eclipse.swt.widgets.Composite)20 IStatus (org.eclipse.core.runtime.IStatus)16 SelectionEvent (org.eclipse.swt.events.SelectionEvent)13 ArrayList (java.util.ArrayList)12 Button (org.eclipse.swt.widgets.Button)12 GridData (org.eclipse.swt.layout.GridData)11 GridLayout (org.eclipse.swt.layout.GridLayout)10 FacetsListInputDialog (com.amalto.workbench.dialogs.FacetsListInputDialog)9 List (java.util.List)8 IStructuredSelection (org.eclipse.jface.viewers.IStructuredSelection)8 Label (org.eclipse.swt.widgets.Label)8 SelectionListener (org.eclipse.swt.events.SelectionListener)7 Control (org.eclipse.swt.widgets.Control)7 Display (org.eclipse.swt.widgets.Display)7 IResource (org.eclipse.core.resources.IResource)6 CoreException (org.eclipse.core.runtime.CoreException)6 Window (org.eclipse.jface.window.Window)6 Event (org.eclipse.swt.widgets.Event)6