Search in sources :

Example 6 with IPythonNature

use of org.python.pydev.core.IPythonNature in project Pydev by fabioz.

the class FindOccurrencesSearchQuery method run.

@Override
public IStatus run(IProgressMonitor monitor) throws OperationCanceledException {
    try {
        monitor.beginTask("Searching...", 100);
        req.pushMonitor(monitor);
        FindOccurrencesSearchResult searchResult = (FindOccurrencesSearchResult) getSearchResult();
        Map<Tuple<String, File>, HashSet<ASTEntry>> occurrences;
        try {
            req.pushMonitor(new SubProgressMonitor(monitor, 80));
            occurrences = pyRefactoring.findAllOccurrences(req);
        } finally {
            req.popMonitor().done();
        }
        if (occurrences == null) {
            return Status.OK_STATUS;
        }
        int length = req.qualifier.length();
        HashSet<Integer> foundOffsets = new HashSet<Integer>();
        try {
            req.pushMonitor(new SubProgressMonitor(monitor, 20));
            Set<Entry<Tuple<String, File>, HashSet<ASTEntry>>> entrySet = occurrences.entrySet();
            req.getMonitor().beginTask("Resolving occurrences...", entrySet.size());
            for (Map.Entry<Tuple<String, File>, HashSet<ASTEntry>> o : entrySet) {
                foundOffsets.clear();
                IFile workspaceFile = null;
                try {
                    IProject project = null;
                    IPythonNature nature = req.nature;
                    if (nature != null) {
                        project = nature.getProject();
                    }
                    workspaceFile = FindWorkspaceFiles.getWorkspaceFile(o.getKey().o2, project);
                    if (workspaceFile == null) {
                        Log.logInfo(StringUtils.format("Ignoring: %s. " + "Unable to resolve to a file in the Eclipse workspace.", o.getKey().o2));
                        continue;
                    }
                } catch (IllegalStateException e) {
                    // this can happen on tests (but if not on tests, we want to re-throw it
                    String message = e.getMessage();
                    if (message == null || !message.equals("Workspace is closed.")) {
                        throw e;
                    }
                    // otherwise, let's just keep going in the test...
                    continue;
                }
                IDocument doc = FileUtilsFileBuffer.getDocFromResource(workspaceFile);
                req.getMonitor().setTaskName("Resolving occurrences... " + workspaceFile);
                for (ASTEntry entry : o.getValue()) {
                    int offset = AbstractRenameRefactorProcess.getOffset(doc, entry);
                    if (!foundOffsets.contains(offset)) {
                        foundOffsets.add(offset);
                        if (DebugFlags.DEBUG_FIND_REFERENCES) {
                            System.out.println("Adding match:" + workspaceFile);
                        }
                        PySelection ps = new PySelection(doc, offset);
                        int lineNumber = ps.getLineOfOffset();
                        String lineContents = ps.getLine(lineNumber);
                        int lineStartOffset = ps.getLineOffset(lineNumber);
                        LineElement element = new LineElement(workspaceFile, lineNumber, lineStartOffset, lineContents, offset - lineStartOffset);
                        searchResult.addMatch(new FileMatch(workspaceFile, offset, length, element));
                    }
                }
            }
        } finally {
            req.popMonitor().done();
        }
    } catch (CoreException e) {
        Log.log(e);
    } finally {
        req.popMonitor().done();
    }
    return Status.OK_STATUS;
}
Also used : IFile(org.eclipse.core.resources.IFile) IPythonNature(org.python.pydev.core.IPythonNature) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor) IProject(org.eclipse.core.resources.IProject) ASTEntry(org.python.pydev.parser.visitors.scope.ASTEntry) Entry(java.util.Map.Entry) CoreException(org.eclipse.core.runtime.CoreException) LineElement(com.python.pydev.refactoring.refactorer.search.copied.LineElement) ASTEntry(org.python.pydev.parser.visitors.scope.ASTEntry) PySelection(org.python.pydev.core.docutils.PySelection) IFile(org.eclipse.core.resources.IFile) File(java.io.File) Map(java.util.Map) Tuple(org.python.pydev.shared_core.structure.Tuple) IDocument(org.eclipse.jface.text.IDocument) FileMatch(com.python.pydev.refactoring.refactorer.search.copied.FileMatch) HashSet(java.util.HashSet)

Example 7 with IPythonNature

use of org.python.pydev.core.IPythonNature in project Pydev by fabioz.

the class PythonNature method addNature.

/**
 * Utility routine to add PythonNature to the project
 *
 * @param projectPythonpath: @see {@link IPythonPathNature#setProjectSourcePath(String)}
 */
public static IPythonNature addNature(// Only synchronized internally!
IProject project, IProgressMonitor monitor, String version, String projectPythonpath, String externalProjectPythonpath, String projectInterpreter, Map<String, String> variableSubstitution) throws CoreException {
    if (project == null || !project.isOpen()) {
        return null;
    }
    if (project.hasNature(PYTHON_NATURE_ID)) {
        // Return if it already has the nature configured.
        return getPythonNature(project);
    }
    boolean alreadyLocked = false;
    synchronized (mapLock) {
        if (mapLockAddNature.get(project) == null) {
            mapLockAddNature.put(project, new Object());
        } else {
            alreadyLocked = true;
        }
    }
    if (alreadyLocked) {
        // https://sourceforge.net/tracker/?func=detail&aid=3478567&group_id=85796&atid=577329
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
        // ignore
        }
        return getPythonNature(project);
    } else {
        IProjectDescription desc = project.getDescription();
        if (monitor == null) {
            monitor = new NullProgressMonitor();
        }
        if (projectInterpreter == null) {
            projectInterpreter = IPythonNature.DEFAULT_INTERPRETER;
        }
        try {
            // Lock only for the project and add the nature (at this point we know it hasn't been added).
            String[] natures = desc.getNatureIds();
            String[] newNatures = new String[natures.length + 1];
            System.arraycopy(natures, 0, newNatures, 0, natures.length);
            newNatures[natures.length] = PYTHON_NATURE_ID;
            desc.setNatureIds(newNatures);
            // add the builder. It is used for pylint, pychecker, code completion, etc.
            ICommand[] commands = desc.getBuildSpec();
            // now, add the builder if it still hasn't been added.
            if (hasBuilder(commands) == false && PyDevBuilderPreferences.usePydevBuilders()) {
                ICommand command = desc.newCommand();
                command.setBuilderName(BUILDER_ID);
                ICommand[] newCommands = new ICommand[commands.length + 1];
                System.arraycopy(commands, 0, newCommands, 1, commands.length);
                newCommands[0] = command;
                desc.setBuildSpec(newCommands);
            }
            project.setDescription(desc, monitor);
            IProjectNature n = getPythonNature(project);
            if (n instanceof PythonNature) {
                PythonNature nature = (PythonNature) n;
                // call initialize always - let it do the control.
                nature.init(version, projectPythonpath, externalProjectPythonpath, monitor, projectInterpreter, variableSubstitution);
                return nature;
            }
        } finally {
            synchronized (mapLock) {
                mapLockAddNature.remove(project);
            }
        }
    }
    return null;
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) IPythonNature(org.python.pydev.core.IPythonNature) AbstractPythonNature(org.python.pydev.core.nature.AbstractPythonNature) ICommand(org.eclipse.core.resources.ICommand) IProjectDescription(org.eclipse.core.resources.IProjectDescription) IProjectNature(org.eclipse.core.resources.IProjectNature)

Example 8 with IPythonNature

use of org.python.pydev.core.IPythonNature in project Pydev by fabioz.

the class PyRefactoringFindDefinition method findActualDefinition.

/**
 * @param request OUT: the request to be used in the find definition. It'll be prepared inside this method, and if it's not
 * a suitable request for the find definition, the return of this function will be null, otherwise, it was correctly
 * prepared for a find definition action.
 *
 * @param completionCache the completion cache to be used
 * @param selected OUT: fills the array with the found definitions
 *
 * @return an array with 2 strings: the activation token and the qualifier used. The return may be null, in which case
 *      the refactoring request is not valid for a find definition.
 * @throws CompletionRecursionException
 * @throws BadLocationException
 */
public static String[] findActualDefinition(RefactoringRequest request, ICompletionState completionCache, List<IDefinition> selected) throws CompletionRecursionException, BadLocationException {
    // ok, let's find the definition.
    request.getMonitor().beginTask("Find actual definition", 5);
    String[] tokenAndQual;
    try {
        // 1. we have to know what we're looking for (activationToken)
        request.communicateWork("Finding Definition");
        IModule mod = prepareRequestForFindDefinition(request);
        if (mod == null) {
            return null;
        }
        String modName = request.moduleName;
        request.communicateWork("Module name found:" + modName);
        tokenAndQual = PySelection.getActivationTokenAndQualifier(request.getDoc(), request.ps.getAbsoluteCursorOffset(), true);
        String tok = tokenAndQual[0] + tokenAndQual[1];
        // 2. check findDefinition (SourceModule)
        try {
            int beginLine = request.getBeginLine();
            int beginCol = request.getBeginCol() + 1;
            IPythonNature pythonNature = request.nature;
            PyRefactoringFindDefinition.findActualDefinition(request.getMonitor(), request.acceptTypeshed, mod, tok, selected, beginLine, beginCol, pythonNature, completionCache);
        } catch (OperationCanceledException e) {
            throw e;
        } catch (CompletionRecursionException e) {
            throw e;
        } catch (BadLocationException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    } finally {
        request.getMonitor().done();
    }
    return tokenAndQual;
}
Also used : IModule(org.python.pydev.core.IModule) CompletionRecursionException(org.python.pydev.core.structure.CompletionRecursionException) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) IPythonNature(org.python.pydev.core.IPythonNature) BadLocationException(org.eclipse.jface.text.BadLocationException) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) BadLocationException(org.eclipse.jface.text.BadLocationException) CompletionRecursionException(org.python.pydev.core.structure.CompletionRecursionException)

Example 9 with IPythonNature

use of org.python.pydev.core.IPythonNature in project Pydev by fabioz.

the class InterpreterManagersAPI method getInfoForFile.

/**
 * @param file the file we want to get info on.
 * @return a tuple with the nature to be used and the name of the module represented by the file in that scenario.
 */
public static Tuple<IPythonNature, String> getInfoForFile(File file) {
    IInterpreterManager pythonInterpreterManager2 = getPythonInterpreterManager(false);
    IInterpreterManager jythonInterpreterManager2 = getJythonInterpreterManager(false);
    IInterpreterManager ironpythonInterpreterManager2 = getIronpythonInterpreterManager(false);
    if (file != null) {
        // Check if we can resolve the manager for the passed file...
        Tuple<IPythonNature, String> infoForManager = getInfoForManager(file, pythonInterpreterManager2);
        if (infoForManager != null) {
            return infoForManager;
        }
        infoForManager = getInfoForManager(file, jythonInterpreterManager2);
        if (infoForManager != null) {
            return infoForManager;
        }
        infoForManager = getInfoForManager(file, ironpythonInterpreterManager2);
        if (infoForManager != null) {
            return infoForManager;
        }
        // Ok, the file is not part of the interpreter configuration, but it's still possible that it's part of a
        // project... (external projects), so, let's go on and see if there's some match there.
        List<IPythonNature> allPythonNatures = PythonNature.getAllPythonNatures();
        int size = allPythonNatures.size();
        for (int i = 0; i < size; i++) {
            IPythonNature nature = allPythonNatures.get(i);
            try {
                // Note: only resolve in the project sources, as we've already checked the system and we'll be
                // checking all projects anyways.
                String modName = nature.resolveModuleOnlyInProjectSources(FileUtils.getFileAbsolutePath(file), true);
                if (modName != null) {
                    return new Tuple<IPythonNature, String>(nature, modName);
                }
            } catch (Exception e) {
                Log.log(e);
            }
        }
    }
    if (pythonInterpreterManager2.isConfigured()) {
        try {
            return new Tuple<IPythonNature, String>(new SystemPythonNature(pythonInterpreterManager2), getModNameFromFile(file));
        } catch (MisconfigurationException e) {
        }
    }
    if (jythonInterpreterManager2.isConfigured()) {
        try {
            return new Tuple<IPythonNature, String>(new SystemPythonNature(jythonInterpreterManager2), getModNameFromFile(file));
        } catch (MisconfigurationException e) {
        }
    }
    if (ironpythonInterpreterManager2.isConfigured()) {
        try {
            return new Tuple<IPythonNature, String>(new SystemPythonNature(ironpythonInterpreterManager2), getModNameFromFile(file));
        } catch (MisconfigurationException e) {
        }
    }
    // Ok, nothing worked, let's just do a call which'll ask to configure python and return null!
    try {
        pythonInterpreterManager2.getDefaultInterpreterInfo(true);
    } catch (MisconfigurationException e) {
    // Ignore
    }
    return null;
}
Also used : MisconfigurationException(org.python.pydev.core.MisconfigurationException) IPythonNature(org.python.pydev.core.IPythonNature) SystemPythonNature(org.python.pydev.plugin.nature.SystemPythonNature) IInterpreterManager(org.python.pydev.core.IInterpreterManager) Tuple(org.python.pydev.shared_core.structure.Tuple) CoreException(org.eclipse.core.runtime.CoreException) MisconfigurationException(org.python.pydev.core.MisconfigurationException)

Example 10 with IPythonNature

use of org.python.pydev.core.IPythonNature 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)

Aggregations

IPythonNature (org.python.pydev.core.IPythonNature)85 MisconfigurationException (org.python.pydev.core.MisconfigurationException)33 ArrayList (java.util.ArrayList)30 File (java.io.File)26 IProject (org.eclipse.core.resources.IProject)20 IFile (org.eclipse.core.resources.IFile)18 CoreException (org.eclipse.core.runtime.CoreException)17 Tuple (org.python.pydev.shared_core.structure.Tuple)14 IDocument (org.eclipse.jface.text.IDocument)12 SourceModule (org.python.pydev.ast.codecompletion.revisited.modules.SourceModule)12 ICodeCompletionASTManager (org.python.pydev.core.ICodeCompletionASTManager)11 IModule (org.python.pydev.core.IModule)10 TokensList (org.python.pydev.core.TokensList)10 HashSet (java.util.HashSet)9 List (java.util.List)9 BadLocationException (org.eclipse.jface.text.BadLocationException)9 IInterpreterInfo (org.python.pydev.core.IInterpreterInfo)9 SimpleNode (org.python.pydev.parser.jython.SimpleNode)9 PyEdit (org.python.pydev.editor.PyEdit)8 SystemPythonNature (org.python.pydev.plugin.nature.SystemPythonNature)8