Search in sources :

Example 11 with PyEdit

use of org.python.pydev.editor.PyEdit in project Pydev by fabioz.

the class PyGoToDefinition method findDefinitionsAndOpen.

public ItemPointer[] findDefinitionsAndOpen(boolean doOpenDefinition) {
    request = null;
    ps = PySelectionFromEditor.createPySelectionFromEditor(getTextEditor());
    final PyEdit pyEdit = getPyEdit();
    RefactoringRequest refactoringRequest;
    try {
        refactoringRequest = getRefactoringRequest();
    } catch (MisconfigurationException e1) {
        Log.log(e1);
        return new ItemPointer[0];
    }
    final Shell shell = EditorUtils.getShell();
    try {
        if (areRefactorPreconditionsOK(refactoringRequest)) {
            boolean acceptTypeshed = false;
            boolean findInAdditionalInfo = false;
            ItemPointer[] defs = findDefinition(pyEdit, acceptTypeshed, findInAdditionalInfo);
            boolean retry = defs == null || defs.length == 0;
            if (!retry) {
                if (defs.length == 1) {
                    if (defs[0].definition == null) {
                        retry = true;
                    } else if (defs[0].definition.module == null) {
                        retry = true;
                    } else if (defs[0].definition.module.getFile() == null) {
                        retry = true;
                    }
                }
            }
            if (retry) {
                acceptTypeshed = true;
                findInAdditionalInfo = true;
                defs = findDefinition(pyEdit, acceptTypeshed, findInAdditionalInfo);
            }
            if (doOpenDefinition) {
                openDefinition(defs, pyEdit, shell);
            }
            return defs;
        }
    } catch (Exception e) {
        Log.log(e);
        String msg = e.getMessage();
        if (msg == null) {
            msg = "Unable to get error msg (null)";
        }
        ErrorDialog.openError(shell, "Error", "Unable to do requested action", new Status(Status.ERROR, PydevPlugin.getPluginID(), 0, msg, e));
    }
    return null;
}
Also used : IStatus(org.eclipse.core.runtime.IStatus) Status(org.eclipse.core.runtime.Status) Shell(org.eclipse.swt.widgets.Shell) RefactoringRequest(org.python.pydev.ast.refactoring.RefactoringRequest) MisconfigurationException(org.python.pydev.core.MisconfigurationException) PyEdit(org.python.pydev.editor.PyEdit) TooManyMatchesException(org.python.pydev.ast.refactoring.TooManyMatchesException) BadLocationException(org.eclipse.jface.text.BadLocationException) MisconfigurationException(org.python.pydev.core.MisconfigurationException) ItemPointer(org.python.pydev.ast.item_pointer.ItemPointer)

Example 12 with PyEdit

use of org.python.pydev.editor.PyEdit in project Pydev by fabioz.

the class PyGoToDefinition method run.

/**
 * Overrides the run and calls -- and the whole default refactoring cycle from the beggining,
 * because unlike most refactoring operations, this one can work with dirty editors.
 * @return
 */
@Override
public void run(IAction action) {
    workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
    IEditorPart[] dirtyEditors = workbenchWindow.getActivePage().getDirtyEditors();
    Set<PyEdit> askReparse = new HashSet<PyEdit>();
    for (IEditorPart iEditorPart : dirtyEditors) {
        if (iEditorPart instanceof PyEdit) {
            PyEdit pyEdit = (PyEdit) iEditorPart;
            long astModificationTimeStamp = pyEdit.getAstModificationTimeStamp();
            IDocument doc = pyEdit.getDocument();
            if (astModificationTimeStamp != -1 && astModificationTimeStamp == (((IDocumentExtension4) doc).getModificationStamp())) {
            // All OK, the ast is synched!
            } else {
                askReparse.add(pyEdit);
            }
        }
    }
    if (askReparse.size() == 0) {
        findDefinitionsAndOpen(true);
    } else {
        // We don't have a match: ask for a reparse
        Object lock = new Object();
        for (PyEdit pyEdit : askReparse) {
            IParserObserver observer = new FindParserObserver(pyEdit, askReparse, lock);
            PyParser parser = pyEdit.getParser();
            // it will analyze when the next parse is finished
            parser.addParseListener(observer);
            parser.forceReparse();
        }
    }
}
Also used : PyParser(org.python.pydev.parser.PyParser) IEditorPart(org.eclipse.ui.IEditorPart) IParserObserver(org.python.pydev.shared_core.parsing.IParserObserver) PyEdit(org.python.pydev.editor.PyEdit) IDocument(org.eclipse.jface.text.IDocument) HashSet(java.util.HashSet)

Example 13 with PyEdit

use of org.python.pydev.editor.PyEdit in project Pydev by fabioz.

the class StepIntoSelectionHyperlinkDetector method detectHyperlinks.

/**
 * @see org.eclipse.jface.text.hyperlink.IHyperlinkDetector#detectHyperlinks(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion, boolean)
 */
@Override
public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) {
    ITextEditor editor = getAdapter(ITextEditor.class);
    if (editor instanceof PyEdit) {
        PyEdit pyEdit = (PyEdit) editor;
        // should only enable step into selection when the current debug context
        // is an instance of IJavaStackFrame
        IAdaptable debugContext = DebugUITools.getDebugContext();
        if (debugContext == null) {
            return null;
        }
        if (!(debugContext instanceof PyStackFrame)) {
            return null;
        }
        PyStackFrame pyStackFrame = (PyStackFrame) debugContext;
        SmartStepIntoVariant[] stepIntoTargets = pyStackFrame.getStepIntoTargets();
        if (stepIntoTargets == null) {
            Log.log("Unable to get Smart Step Into Targets.");
            return null;
        }
        int offset = region.getOffset();
        try {
            IDocument document = pyEdit.getDocument();
            // see if we can find a word there
            IRegion wordRegion = TextSelectionUtils.findWord(document, offset);
            if (wordRegion == null || wordRegion.getLength() == 0) {
                return null;
            }
            String selectedWord;
            // don't highlight keywords
            try {
                selectedWord = document.get(wordRegion.getOffset(), wordRegion.getLength());
                if (PythonLanguageUtils.isKeyword(selectedWord)) {
                    return null;
                }
            } catch (BadLocationException e) {
                Log.log(e);
                return null;
            }
            ICoreTextSelection textSelection = pyEdit.getTextSelection();
            int line = textSelection.getStartLine();
            List<SmartStepIntoVariant> found = new ArrayList<>();
            for (SmartStepIntoVariant smartStepIntoVariant : stepIntoTargets) {
                if (line == smartStepIntoVariant.line && selectedWord.equals(smartStepIntoVariant.name)) {
                    found.add(smartStepIntoVariant);
                }
            }
            if (found.size() == 0) {
                Log.log("Unable to find step into target with name: " + selectedWord + " at line: " + line + "\nAvailable: " + StringUtils.join("; ", stepIntoTargets));
                return null;
            }
            SmartStepIntoVariant target;
            if (found.size() > 1) {
                // i.e.: the target is backwards.
                Collections.reverse(found);
                Iterator<SmartStepIntoVariant> iterator = found.iterator();
                target = iterator.next();
                TextSelectionUtils ts = new TextSelectionUtils(document, textSelection);
                // Let's check if there's more than one occurrence of the same word in the given line.
                String lineContents = ts.getLine(line);
                List<Integer> wordOffsets = StringUtils.findWordOffsets(lineContents, selectedWord);
                if (wordOffsets.size() > 0) {
                    int offsetInLine = wordRegion.getOffset() - ts.getStartLineOffset();
                    for (Integer i : wordOffsets) {
                        if (i >= offsetInLine) {
                            break;
                        }
                        target = iterator.next();
                        if (!iterator.hasNext()) {
                            break;
                        }
                    }
                }
            } else {
                // size == 1
                target = found.get(0);
            }
            // return a hyperlink even without trying to find the definition (which may be costly)
            return new IHyperlink[] { new StepIntoSelectionHyperlink((PyStackFrame) debugContext, pyEdit, wordRegion, line, selectedWord, target) };
        } catch (Exception e) {
            Log.log(e);
            return null;
        }
    }
    return null;
}
Also used : IAdaptable(org.eclipse.core.runtime.IAdaptable) PyStackFrame(org.python.pydev.debug.model.PyStackFrame) ITextEditor(org.eclipse.ui.texteditor.ITextEditor) SmartStepIntoVariant(org.python.pydev.debug.model.SmartStepIntoVariant) ArrayList(java.util.ArrayList) ICoreTextSelection(org.python.pydev.shared_core.string.ICoreTextSelection) IRegion(org.eclipse.jface.text.IRegion) DebugException(org.eclipse.debug.core.DebugException) BadLocationException(org.eclipse.jface.text.BadLocationException) TextSelectionUtils(org.python.pydev.shared_core.string.TextSelectionUtils) IHyperlink(org.eclipse.jface.text.hyperlink.IHyperlink) PyEdit(org.python.pydev.editor.PyEdit) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 14 with PyEdit

use of org.python.pydev.editor.PyEdit in project Pydev by fabioz.

the class PyReloadCode method onSave.

@Override
public void onSave(BaseEditor baseEditor, IProgressMonitor monitor) {
    if (!DebugPrefsPage.getReloadModuleOnChange()) {
        return;
    }
    PyEdit edit = (PyEdit) baseEditor;
    File file = edit.getEditorFile();
    if (file != null) {
        IDebugTarget[] debugTargets = DebugPlugin.getDefault().getLaunchManager().getDebugTargets();
        if (debugTargets.length > 0) {
            ICallback<Boolean, IDebugTarget> callbackThatFilters = new ICallback<Boolean, IDebugTarget>() {

                @Override
                public Boolean call(IDebugTarget arg) {
                    return arg instanceof AbstractDebugTarget;
                }
            };
            List<IDebugTarget> filter = ArrayUtils.filter(debugTargets, callbackThatFilters);
            if (filter.size() > 0) {
                try {
                    IPythonNature pythonNature = edit.getPythonNature();
                    if (pythonNature != null) {
                        String moduleName = pythonNature.resolveModule(file);
                        if (moduleName != null) {
                            for (IDebugTarget iDebugTarget : filter) {
                                AbstractDebugTarget target = (AbstractDebugTarget) iDebugTarget;
                                target.postCommand(new ReloadCodeCommand(target, moduleName));
                            }
                        }
                    }
                } catch (MisconfigurationException e) {
                    Log.log(e);
                }
            }
        }
    }
}
Also used : MisconfigurationException(org.python.pydev.core.MisconfigurationException) IPythonNature(org.python.pydev.core.IPythonNature) ICallback(org.python.pydev.shared_core.callbacks.ICallback) IDebugTarget(org.eclipse.debug.core.model.IDebugTarget) ReloadCodeCommand(org.python.pydev.debug.model.remote.ReloadCodeCommand) File(java.io.File) PyEdit(org.python.pydev.editor.PyEdit)

Example 15 with PyEdit

use of org.python.pydev.editor.PyEdit in project Pydev by fabioz.

the class PySetNextTarget method setNextToLine.

@Override
public boolean setNextToLine(IWorkbenchPart part, ISelection selection, ISuspendResume target) throws CoreException {
    // System.out.println("Run to line:"+target);
    PyStackFrame stack = null;
    if (target instanceof PyStackFrame) {
        stack = (PyStackFrame) target;
        target = stack.getThread();
    }
    if (!(part instanceof PyEdit)) {
        return false;
    }
    PyEdit pyEdit = (PyEdit) part;
    SimpleNode ast = pyEdit.getAST();
    if (ast == null) {
        IDocument doc = pyEdit.getDocument();
        SourceModule sourceModule;
        IPythonNature nature = null;
        try {
            nature = pyEdit.getPythonNature();
        } catch (MisconfigurationException e) {
            // Let's try to find a suitable nature
            File editorFile = pyEdit.getEditorFile();
            if (editorFile == null || !editorFile.exists()) {
                Log.log(e);
                return false;
            }
            nature = InterpreterManagersAPI.getInfoForFile(editorFile).o1;
        }
        if (nature == null) {
            Log.log("Unable to determine nature!");
            return false;
        }
        try {
            sourceModule = AbstractModule.createModuleFromDoc("", pyEdit.getEditorFile(), doc, nature, true);
        } catch (MisconfigurationException e) {
            Log.log(e);
            return false;
        }
        ast = sourceModule.getAst();
    }
    if (ast == null) {
        Log.log("Cannot determine context to run to.");
        return false;
    }
    if (target instanceof PyThread && selection instanceof ITextSelection) {
        ITextSelection textSelection = (ITextSelection) selection;
        PyThread pyThread = (PyThread) target;
        if (!pyThread.isPydevThread()) {
            int sourceLine = stack.getLineNumber();
            int targetLine = textSelection.getStartLine();
            if (!NodeUtils.isValidContextForSetNext(ast, sourceLine, targetLine)) {
                return false;
            }
            String functionName = NodeUtils.getContextName(targetLine, ast);
            if (functionName == null) {
                // global context
                functionName = "";
            } else {
                functionName = FullRepIterable.getLastPart(functionName).trim();
            }
            pyThread.setNextStatement(targetLine + 1, functionName);
            return true;
        }
    }
    return true;
}
Also used : SourceModule(org.python.pydev.ast.codecompletion.revisited.modules.SourceModule) MisconfigurationException(org.python.pydev.core.MisconfigurationException) IPythonNature(org.python.pydev.core.IPythonNature) File(java.io.File) PyEdit(org.python.pydev.editor.PyEdit) IDocument(org.eclipse.jface.text.IDocument) ITextSelection(org.eclipse.jface.text.ITextSelection) SimpleNode(org.python.pydev.parser.jython.SimpleNode)

Aggregations

PyEdit (org.python.pydev.editor.PyEdit)64 PySelection (org.python.pydev.core.docutils.PySelection)22 IFile (org.eclipse.core.resources.IFile)15 ArrayList (java.util.ArrayList)14 BadLocationException (org.eclipse.jface.text.BadLocationException)13 Path (org.eclipse.core.runtime.Path)12 IDocument (org.eclipse.jface.text.IDocument)12 MisconfigurationException (org.python.pydev.core.MisconfigurationException)9 ICompletionProposalHandle (org.python.pydev.shared_core.code_completion.ICompletionProposalHandle)9 IPythonNature (org.python.pydev.core.IPythonNature)8 File (java.io.File)7 ICallbackListener (org.python.pydev.shared_core.callbacks.ICallbackListener)7 ByteArrayInputStream (java.io.ByteArrayInputStream)5 IRegion (org.eclipse.jface.text.IRegion)5 ITextSelection (org.eclipse.jface.text.ITextSelection)5 IEditorInput (org.eclipse.ui.IEditorInput)5 SimpleNode (org.python.pydev.parser.jython.SimpleNode)5 CoreException (org.eclipse.core.runtime.CoreException)4 RefactoringRequest (org.python.pydev.ast.refactoring.RefactoringRequest)4 IInterpreterManager (org.python.pydev.core.IInterpreterManager)4