Search in sources :

Example 1 with MarkerAnnotationAndPosition

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

the class AbstractAnalysisMarkersParticipants method getProps.

@Override
public List<ICompletionProposalHandle> getProps(PySelection ps, IImageCache imageCache, File f, IPythonNature nature, IPyEdit edit, int offset) throws BadLocationException {
    fillParticipants();
    PySourceViewer s = ((PyEdit) edit).getPySourceViewer();
    int line = ps.getLineOfOffset(offset);
    OrderedSet<MarkerAnnotationAndPosition> markersAtLine = new OrderedSet<MarkerAnnotationAndPosition>();
    // Add it to a set to make sure that the entries are unique.
    // -- i.e.: the code analysis seems to be creating 2 markers in the following case (when sys is undefined):
    // sys.call1().call2()
    // So, we add it to a set to make sure we'll only analyze unique markers.
    // Note that it'll check equality by the marker type and text (not by position), so, if a given error
    // appears twice in the same line being correct, we'll only show the options once here (which is what
    // we want).
    List<MarkerAnnotationAndPosition> markersAtLine2 = s.getMarkersAtLine(line, getMarkerType());
    markersAtLine.addAll(markersAtLine2);
    ArrayList<ICompletionProposalHandle> props = new ArrayList<ICompletionProposalHandle>();
    if (markersAtLine != null) {
        IAnalysisPreferences analysisPreferences = new AnalysisPreferences(edit);
        String currLine = ps.getLine();
        for (MarkerAnnotationAndPosition marker : markersAtLine) {
            for (IAnalysisMarkersParticipant participant : participants) {
                try {
                    participant.addProps(marker, analysisPreferences, currLine, ps, offset, nature, (PyEdit) edit, props);
                } catch (Exception e) {
                    Log.log("Error when getting proposals.", e);
                }
            }
        }
    }
    return props;
}
Also used : OrderedSet(org.python.pydev.shared_core.structure.OrderedSet) AnalysisPreferences(com.python.pydev.analysis.AnalysisPreferences) IAnalysisPreferences(org.python.pydev.ast.analysis.IAnalysisPreferences) ArrayList(java.util.ArrayList) BadLocationException(org.eclipse.jface.text.BadLocationException) IAnalysisPreferences(org.python.pydev.ast.analysis.IAnalysisPreferences) ICompletionProposalHandle(org.python.pydev.shared_core.code_completion.ICompletionProposalHandle) PySourceViewer(org.python.pydev.editor.codefolding.PySourceViewer) IPyEdit(org.python.pydev.core.IPyEdit) PyEdit(org.python.pydev.editor.PyEdit) MarkerAnnotationAndPosition(org.python.pydev.editor.codefolding.MarkerAnnotationAndPosition)

Example 2 with MarkerAnnotationAndPosition

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

the class OrganizeImports method beforePerformArrangeImports.

/**
 * That's where everything happens.
 *
 * Important: if the document is in a rewrite session, trying to highlight a given session does not work
 * (so, we cannot be in a rewrite session in this case).
 */
@Override
public boolean beforePerformArrangeImports(final PySelection ps, final PyEdit edit, IFile f) {
    if ((!AnalysisPreferences.doAutoImportOnOrganizeImports(edit)) || edit == null) {
        return true;
    }
    didChange = false;
    ArrayList<MarkerAnnotationAndPosition> undefinedVariablesMarkers = getUndefinedVariableMarkers(edit);
    // sort them
    TreeMap<Integer, MarkerAnnotationAndPosition> map = new TreeMap<Integer, MarkerAnnotationAndPosition>();
    for (MarkerAnnotationAndPosition marker : undefinedVariablesMarkers) {
        if (marker.position == null) {
            continue;
        }
        int start = marker.position.offset;
        map.put(start, marker);
    }
    // create the participant that'll help (will not force a reparse)
    final UndefinedVariableFixParticipant variableFixParticipant = new UndefinedVariableFixParticipant(false);
    // These are the completions to apply. We must apply them all at once after finishing it because we can't do
    // it one by one during the processing because that'd make markers change.
    final List<ICompletionProposalExtension2> completionsToApply = new ArrayList<ICompletionProposalExtension2>();
    // keeps the strings we've already treated.
    final HashSet<String> treatedVars = new HashSet<String>();
    // variable to hold whether we should keep on choosing the imports
    final Boolean[] keepGoing = new Boolean[] { true };
    final IDialogSettings dialogSettings = AnalysisUiPlugin.getDialogSettings();
    // analyse the markers (one by one)
    for (final MarkerAnnotationAndPosition marker : map.values()) {
        if (!keepGoing[0]) {
            break;
        }
        try {
            final int start = marker.position.offset;
            final int end = start + marker.position.length;
            if (start >= 0 && end > start) {
                IDocument doc = ps.getDoc();
                ArrayList<ICompletionProposalHandle> props = new ArrayList<ICompletionProposalHandle>();
                try {
                    String string = doc.get(start, end - start);
                    if (treatedVars.contains(string)) {
                        continue;
                    }
                    variableFixParticipant.addProps(marker, null, null, ps, start, edit.getPythonNature(), edit, props);
                    if (props.size() > 0) {
                        // Sorting proposals on Ctrl+Shift+O.
                        ProposalsComparator proposalsComparator = new ProposalsComparator("", new ProposalsComparator.CompareContext(edit.getPythonNature()));
                        props.sort(proposalsComparator);
                        edit.selectAndReveal(start, end - start);
                        treatedVars.add(string);
                        Shell activeShell = Display.getCurrent().getActiveShell();
                        // Changed from ElementListSelectionDialog so that we can control the sorting.
                        TreeSelectionDialog dialog = new TreeSelectionDialog(activeShell, new LabelProvider() {

                            // get the image and text for each completion
                            @Override
                            public Image getImage(Object element) {
                                CtxInsensitiveImportComplProposal comp = ((CtxInsensitiveImportComplProposal) element);
                                return comp.getImage();
                            }

                            @Override
                            public String getText(Object element) {
                                CtxInsensitiveImportComplProposal comp = ((CtxInsensitiveImportComplProposal) element);
                                return comp.getDisplayString();
                            }
                        }, new ListContentProvider()) {

                            // override things to return the last position of the dialog correctly
                            @Override
                            protected Control createContents(Composite parent) {
                                Control ret = super.createContents(parent);
                                org.python.pydev.plugin.PydevPlugin.setCssId(parent, "py-add-imports-dialog", true);
                                return ret;
                            }

                            @Override
                            public boolean isHelpAvailable() {
                                return false;
                            }

                            @Override
                            protected void updateStatus(IStatus status) {
                                super.updateStatus(status);
                                PydevPlugin.fixSelectionStatusDialogStatusLineColor(this, this.getDialogArea().getBackground());
                            }

                            /**
                             * @see org.eclipse.ui.dialogs.SelectionDialog#getDialogBoundsSettings()
                             */
                            @Override
                            protected IDialogSettings getDialogBoundsSettings() {
                                IDialogSettings section = dialogSettings.getSection(DIALOG_SETTINGS);
                                if (section == null) {
                                    section = dialogSettings.addNewSection(DIALOG_SETTINGS);
                                }
                                return section;
                            }

                            /* (non-Javadoc)
                                 * @see org.eclipse.jface.dialogs.Dialog#getInitialSize()
                                 */
                            @Override
                            protected Point getInitialSize() {
                                IDialogSettings settings = getDialogBoundsSettings();
                                if (settings != null) {
                                    try {
                                        // $NON-NLS-1$
                                        int width = settings.getInt("DIALOG_WIDTH");
                                        // $NON-NLS-1$
                                        int height = settings.getInt("DIALOG_HEIGHT");
                                        if (width > 0 & height > 0) {
                                            return new Point(width, height);
                                        }
                                    } catch (NumberFormatException nfe) {
                                    // make the default return
                                    }
                                }
                                return new Point(300, 300);
                            }
                        };
                        dialog.setTitle("Choose import");
                        dialog.setMessage("Which import should be added?");
                        dialog.setInput(props);
                        dialog.setInitialSelection(props.get(0));
                        int returnCode = dialog.open();
                        if (returnCode == Window.OK) {
                            ICompletionProposalExtension2 firstResult = (ICompletionProposalExtension2) dialog.getFirstResult();
                            completionsToApply.add(firstResult);
                        } else if (returnCode == Window.CANCEL) {
                            keepGoing[0] = false;
                            continue;
                        }
                    }
                } catch (Exception e) {
                    Log.log(e);
                }
            }
        } catch (Exception e) {
            Log.log(e);
        }
    }
    for (ICompletionProposalExtension2 comp : completionsToApply) {
        // the offset is not used in this case, because the actual completion does nothing,
        int offset = 0;
        // we'll only add the import.
        comp.apply(edit.getPySourceViewer(), ' ', 0, offset);
        didChange = true;
    }
    return true;
}
Also used : IStatus(org.eclipse.core.runtime.IStatus) ArrayList(java.util.ArrayList) ICompletionProposalExtension2(org.eclipse.jface.text.contentassist.ICompletionProposalExtension2) Image(org.eclipse.swt.graphics.Image) Shell(org.eclipse.swt.widgets.Shell) ListContentProvider(org.python.pydev.ui.dialogs.ListContentProvider) Control(org.eclipse.swt.widgets.Control) ICompletionProposalHandle(org.python.pydev.shared_core.code_completion.ICompletionProposalHandle) MarkerAnnotationAndPosition(org.python.pydev.editor.codefolding.MarkerAnnotationAndPosition) HashSet(java.util.HashSet) TreeSelectionDialog(org.python.pydev.ui.dialogs.TreeSelectionDialog) CtxInsensitiveImportComplProposal(org.python.pydev.editor.codecompletion.proposals.CtxInsensitiveImportComplProposal) Composite(org.eclipse.swt.widgets.Composite) ProposalsComparator(org.python.pydev.ast.codecompletion.ProposalsComparator) Point(org.eclipse.swt.graphics.Point) TreeMap(java.util.TreeMap) Point(org.eclipse.swt.graphics.Point) UndefinedVariableFixParticipant(com.python.pydev.analysis.ctrl_1.UndefinedVariableFixParticipant) IDialogSettings(org.eclipse.jface.dialogs.IDialogSettings) LabelProvider(org.eclipse.jface.viewers.LabelProvider) IDocument(org.eclipse.jface.text.IDocument)

Example 3 with MarkerAnnotationAndPosition

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

the class OrganizeImportsFixesUnused method getUnusedImports.

private ArrayList<MarkerAnnotationAndPosition> getUnusedImports(Iterator<MarkerAnnotationAndPosition> it) throws CoreException {
    ArrayList<MarkerAnnotationAndPosition> unusedImportsMarkers = new ArrayList<MarkerAnnotationAndPosition>();
    while (it.hasNext()) {
        MarkerAnnotationAndPosition marker = it.next();
        String type = marker.markerAnnotation.getMarker().getType();
        if (type != null && type.equals(IMiscConstants.PYDEV_ANALYSIS_PROBLEM_MARKER)) {
            Integer attribute = marker.markerAnnotation.getMarker().getAttribute(IMiscConstants.PYDEV_ANALYSIS_TYPE, -1);
            if (attribute != null) {
                if (attribute.equals(IMiscConstants.TYPE_UNUSED_IMPORT)) {
                    unusedImportsMarkers.add(marker);
                }
            }
        }
    }
    return unusedImportsMarkers;
}
Also used : ArrayList(java.util.ArrayList) MarkerAnnotationAndPosition(org.python.pydev.editor.codefolding.MarkerAnnotationAndPosition)

Example 4 with MarkerAnnotationAndPosition

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

the class PyMarkerTextHover method getMarkerHover.

/**
 * Fills the buffer with the text for markers we're hovering over.
 */
private void getMarkerHover(IRegion hoverRegion, PySourceViewer s, FastStringBuffer buf) {
    for (Iterator<MarkerAnnotationAndPosition> it = s.getMarkerIterator(); it.hasNext(); ) {
        MarkerAnnotationAndPosition marker = it.next();
        try {
            if (marker.position == null) {
                continue;
            }
            int cStart = marker.position.offset;
            int cEnd = cStart + marker.position.length;
            int offset = hoverRegion.getOffset();
            if (cStart <= offset && cEnd >= offset) {
                if (buf.length() > 0) {
                    buf.append(PyInformationPresenter.LINE_DELIM);
                }
                IMarker m = marker.markerAnnotation.getMarker();
                if (!PyMarkerUtils.showToUser(m)) {
                    continue;
                }
                Object msg = m.getAttribute(IMarker.MESSAGE);
                buf.appendObject(msg);
            }
        } catch (CoreException e) {
        // ignore marker does not exist anymore
        }
    }
}
Also used : CoreException(org.eclipse.core.runtime.CoreException) IMarker(org.eclipse.core.resources.IMarker) MarkerAnnotationAndPosition(org.python.pydev.editor.codefolding.MarkerAnnotationAndPosition)

Example 5 with MarkerAnnotationAndPosition

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

the class OrganizeImportsFixesUnused method findAndDeleteUnusedImports.

private void findAndDeleteUnusedImports(PySelection ps, PyEdit edit, IDocumentExtension4 doc, IFile f) throws Exception {
    Iterator<MarkerAnnotationAndPosition> it;
    if (edit != null) {
        it = edit.getPySourceViewer().getMarkerIterator();
    } else {
        IMarker[] markers = f.findMarkers(IMiscConstants.PYDEV_ANALYSIS_PROBLEM_MARKER, true, IResource.DEPTH_ZERO);
        MarkerAnnotationAndPosition[] maap = new MarkerAnnotationAndPosition[markers.length];
        int ix = 0;
        for (IMarker m : markers) {
            int start = (Integer) m.getAttribute(IMarker.CHAR_START);
            int end = (Integer) m.getAttribute(IMarker.CHAR_END);
            maap[ix++] = new MarkerAnnotationAndPosition(new MarkerAnnotation(m), new Position(start, end - start));
        }
        it = Arrays.asList(maap).iterator();
    }
    ArrayList<MarkerAnnotationAndPosition> unusedImportsMarkers = getUnusedImports(it);
    sortInReverseDocumentOrder(unusedImportsMarkers);
    deleteImports(doc, ps, unusedImportsMarkers);
}
Also used : MarkerAnnotation(org.eclipse.ui.texteditor.MarkerAnnotation) MarkerAnnotationAndPosition(org.python.pydev.editor.codefolding.MarkerAnnotationAndPosition) Position(org.eclipse.jface.text.Position) IMarker(org.eclipse.core.resources.IMarker) MarkerAnnotationAndPosition(org.python.pydev.editor.codefolding.MarkerAnnotationAndPosition)

Aggregations

MarkerAnnotationAndPosition (org.python.pydev.editor.codefolding.MarkerAnnotationAndPosition)8 ArrayList (java.util.ArrayList)4 IMarker (org.eclipse.core.resources.IMarker)3 Position (org.eclipse.jface.text.Position)2 MarkerAnnotation (org.eclipse.ui.texteditor.MarkerAnnotation)2 PySourceViewer (org.python.pydev.editor.codefolding.PySourceViewer)2 ICompletionProposalHandle (org.python.pydev.shared_core.code_completion.ICompletionProposalHandle)2 AnalysisPreferences (com.python.pydev.analysis.AnalysisPreferences)1 MarkerStub (com.python.pydev.analysis.MarkerStub)1 UndefinedVariableFixParticipant (com.python.pydev.analysis.ctrl_1.UndefinedVariableFixParticipant)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 TreeMap (java.util.TreeMap)1 CoreException (org.eclipse.core.runtime.CoreException)1 IStatus (org.eclipse.core.runtime.IStatus)1 IDialogSettings (org.eclipse.jface.dialogs.IDialogSettings)1 BadLocationException (org.eclipse.jface.text.BadLocationException)1 Document (org.eclipse.jface.text.Document)1 IDocument (org.eclipse.jface.text.IDocument)1 ICompletionProposalExtension2 (org.eclipse.jface.text.contentassist.ICompletionProposalExtension2)1