Search in sources :

Example 6 with CompletionContext

use of org.eclipse.jdt.core.CompletionContext in project eclipse.jdt.ui by eclipse-jdt.

the class SWTTemplateCompletionProposalComputer method computeCompletionEngine.

@Override
protected TemplateEngine computeCompletionEngine(JavaContentAssistInvocationContext context) {
    ICompilationUnit unit = context.getCompilationUnit();
    if (unit == null)
        return null;
    IJavaProject javaProject = unit.getJavaProject();
    if (javaProject == null)
        return null;
    if (isSWTOnClasspath(javaProject)) {
        CompletionContext coreContext = context.getCoreContext();
        if (coreContext != null) {
            int tokenLocation = coreContext.getTokenLocation();
            if ((tokenLocation & CompletionContext.TL_MEMBER_START) != 0) {
                return fSWTMembersTemplateEngine;
            }
            if ((tokenLocation & CompletionContext.TL_STATEMENT_START) != 0) {
                return fSWTStatementsTemplateEngine;
            }
        }
        return fSWTTemplateEngine;
    }
    return null;
}
Also used : CompletionContext(org.eclipse.jdt.core.CompletionContext) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IJavaProject(org.eclipse.jdt.core.IJavaProject)

Example 7 with CompletionContext

use of org.eclipse.jdt.core.CompletionContext in project che by eclipse.

the class JavaContentAssistInvocationContext method getRHSHistory.

/**
	 * Returns the content assist type history for the expected type.
	 *
	 * @return the content assist type history for the expected type
	 */
private RHSHistory getRHSHistory() {
    if (fRHSHistory == null) {
        CompletionContext context = getCoreContext();
        if (context != null) {
            char[][] expectedTypes = context.getExpectedTypesSignatures();
            if (expectedTypes != null && expectedTypes.length > 0) {
                String expected = SignatureUtil.stripSignatureToFQN(String.valueOf(expectedTypes[0]));
                fRHSHistory = JavaPlugin.getDefault().getContentAssistHistory().getHistory(expected);
            }
        }
        if (fRHSHistory == null)
            fRHSHistory = JavaPlugin.getDefault().getContentAssistHistory().getHistory(null);
    }
    return fRHSHistory;
}
Also used : CompletionContext(org.eclipse.jdt.core.CompletionContext)

Example 8 with CompletionContext

use of org.eclipse.jdt.core.CompletionContext in project che by eclipse.

the class JavaTypeCompletionProposalComputer method computeCompletionProposals.

/*
	 * @see org.eclipse.jdt.internal.ui.text.java.JavaCompletionProposalComputer#computeCompletionProposals(org.eclipse.jface.text.contentassist.TextContentAssistInvocationContext, org.eclipse.core.runtime.IProgressMonitor)
	 */
@Override
public List<ICompletionProposal> computeCompletionProposals(ContentAssistInvocationContext context, IProgressMonitor monitor) {
    List<ICompletionProposal> types = super.computeCompletionProposals(context, monitor);
    if (!(context instanceof JavaContentAssistInvocationContext))
        return types;
    JavaContentAssistInvocationContext javaContext = (JavaContentAssistInvocationContext) context;
    CompletionContext coreContext = javaContext.getCoreContext();
    if (coreContext != null && coreContext.getTokenLocation() != CompletionContext.TL_CONSTRUCTOR_START)
        return types;
    try {
        if (types.size() > 0 && context.computeIdentifierPrefix().length() == 0) {
            IType expectedType = javaContext.getExpectedType();
            if (expectedType != null) {
                // empty prefix completion - insert LRU types if known, but prune if they already occur in the core list
                // compute minmimum relevance and already proposed list
                int relevance = Integer.MAX_VALUE;
                Set<String> proposed = new HashSet<String>();
                for (Iterator<ICompletionProposal> it = types.iterator(); it.hasNext(); ) {
                    AbstractJavaCompletionProposal p = (AbstractJavaCompletionProposal) it.next();
                    IJavaElement element = p.getJavaElement();
                    if (element instanceof IType)
                        proposed.add(((IType) element).getFullyQualifiedName());
                    relevance = Math.min(relevance, p.getRelevance());
                }
                // insert history types
                List<String> history = JavaPlugin.getDefault().getContentAssistHistory().getHistory(expectedType.getFullyQualifiedName()).getTypes();
                relevance -= history.size() + 1;
                for (Iterator<String> it = history.iterator(); it.hasNext(); ) {
                    String type = it.next();
                    if (proposed.contains(type))
                        continue;
                    IJavaCompletionProposal proposal = createTypeProposal(relevance, type, javaContext);
                    if (proposal != null)
                        types.add(proposal);
                    relevance++;
                }
            }
        }
    } catch (BadLocationException x) {
        // log & ignore
        JavaPlugin.log(x);
    } catch (JavaModelException x) {
        // log & ignore
        JavaPlugin.log(x);
    }
    return types;
}
Also used : IJavaElement(org.eclipse.jdt.core.IJavaElement) JavaContentAssistInvocationContext(org.eclipse.jdt.ui.text.java.JavaContentAssistInvocationContext) JavaModelException(org.eclipse.jdt.core.JavaModelException) IJavaCompletionProposal(org.eclipse.jdt.ui.text.java.IJavaCompletionProposal) IType(org.eclipse.jdt.core.IType) CompletionContext(org.eclipse.jdt.core.CompletionContext) ICompletionProposal(org.eclipse.che.jface.text.contentassist.ICompletionProposal) BadLocationException(org.eclipse.jface.text.BadLocationException) HashSet(java.util.HashSet)

Example 9 with CompletionContext

use of org.eclipse.jdt.core.CompletionContext in project eclipse.jdt.ls by eclipse.

the class CompletionResolveHandler method resolve.

public CompletionItem resolve(CompletionItem param, IProgressMonitor monitor) {
    @SuppressWarnings("unchecked") Map<String, String> data = JSONUtility.toModel(param.getData(), Map.class);
    // clean resolve data
    param.setData(null);
    if (!CompletionProposalRequestor.SUPPORTED_KINDS.contains(param.getKind()) || data == null || !data.containsKey(DATA_FIELD_URI) || !data.containsKey(DATA_FIELD_REQUEST_ID) || !data.containsKey(DATA_FIELD_PROPOSAL_ID)) {
        return param;
    }
    int proposalId = Integer.parseInt(data.get(DATA_FIELD_PROPOSAL_ID));
    long requestId = Long.parseLong(data.get(DATA_FIELD_REQUEST_ID));
    CompletionResponse completionResponse = CompletionResponses.get(requestId);
    if (completionResponse == null || completionResponse.getProposals().size() <= proposalId) {
        throw new IllegalStateException("Invalid completion proposal");
    }
    String uri = data.get(DATA_FIELD_URI);
    ICompilationUnit unit = JDTUtils.resolveCompilationUnit(uri);
    if (unit == null) {
        throw new IllegalStateException(NLS.bind("Unable to match Compilation Unit from {0} ", uri));
    }
    if (monitor.isCanceled()) {
        param.setData(null);
        return param;
    }
    // generic snippets
    if (param.getKind() == CompletionItemKind.Snippet) {
        try {
            CompletionContext ctx = completionResponse.getContext();
            CompletionProposal proposal = completionResponse.getProposals().get(proposalId);
            Template template = ((SnippetCompletionProposal) proposal).getTemplate();
            String content = SnippetCompletionProposal.evaluateGenericTemplate(unit, ctx, template);
            Range range = JDTUtils.toRange(unit, ctx.getOffset(), 0);
            TextEdit textEdit = new TextEdit(range, content);
            param.setTextEdit(Either.forLeft(textEdit));
            param.setDocumentation(SnippetUtils.beautifyDocument(content));
            param.setData(null);
        } catch (JavaModelException e) {
            JavaLanguageServerPlugin.logException(e.getMessage(), e);
        }
        return param;
    }
    if (manager.getClientPreferences().isResolveAdditionalTextEditsSupport()) {
        CompletionProposalReplacementProvider proposalProvider = new CompletionProposalReplacementProvider(unit, completionResponse.getContext(), completionResponse.getOffset(), manager.getPreferences(), manager.getClientPreferences());
        proposalProvider.updateAdditionalTextEdits(completionResponse.getProposals().get(proposalId), param, '\0');
    }
    if (data.containsKey(DATA_FIELD_DECLARATION_SIGNATURE)) {
        String typeName = stripSignatureToFQN(String.valueOf(data.get(DATA_FIELD_DECLARATION_SIGNATURE)));
        try {
            IMember member = null;
            IType type = unit.getJavaProject().findType(typeName);
            CompletionProposal proposal = completionResponse.getProposals().get(proposalId);
            if (type != null && data.containsKey(DATA_FIELD_NAME)) {
                String name = data.get(DATA_FIELD_NAME);
                String[] paramSigs = CharOperation.NO_STRINGS;
                if (data.containsKey(DATA_FIELD_SIGNATURE)) {
                    if (proposal instanceof InternalCompletionProposal) {
                        Binding binding = ((InternalCompletionProposal) proposal).getBinding();
                        if (binding instanceof MethodBinding) {
                            MethodBinding methodBinding = (MethodBinding) binding;
                            MethodBinding original = methodBinding.original();
                            char[] signature;
                            if (original != binding) {
                                signature = Engine.getSignature(original);
                            } else {
                                signature = Engine.getSignature(methodBinding);
                            }
                            String[] parameters = Signature.getParameterTypes(String.valueOf(fix83600(signature)));
                            for (int i = 0; i < parameters.length; i++) {
                                parameters[i] = getLowerBound(parameters[i]);
                            }
                            paramSigs = parameters;
                        }
                    }
                }
                IMethod method = type.getMethod(name, paramSigs);
                IMethod[] methods = type.findMethods(method);
                if (methods != null && methods.length > 0) {
                    method = methods[0];
                }
                if (method.exists()) {
                    member = method;
                } else {
                    IField field = type.getField(name);
                    if (field.exists()) {
                        member = field;
                    }
                }
            } else {
                member = type;
            }
            if (member != null && member.exists() && !monitor.isCanceled()) {
                String javadoc = null;
                try {
                    final IMember curMember = member;
                    javadoc = SimpleTimeLimiter.create(Executors.newCachedThreadPool()).callWithTimeout(() -> {
                        Reader reader;
                        if (manager.getClientPreferences().isSupportsCompletionDocumentationMarkdown()) {
                            reader = JavadocContentAccess2.getMarkdownContentReader(curMember);
                        } else {
                            reader = JavadocContentAccess.getPlainTextContentReader(curMember);
                        }
                        return reader == null ? null : CharStreams.toString(reader);
                    }, 500, TimeUnit.MILLISECONDS);
                } catch (UncheckedTimeoutException | TimeoutException tooSlow) {
                    // Ignore error for now as it's spamming clients on content assist.
                    // TODO cache javadoc resolution results?
                    // JavaLanguageServerPlugin.logError("Unable to get documentation under 500ms");
                    monitor.setCanceled(true);
                } catch (Exception e) {
                    JavaLanguageServerPlugin.logException("Unable to read documentation", e);
                    monitor.setCanceled(true);
                }
                String constantValue = null;
                if (proposal.getKind() == CompletionProposal.FIELD_REF) {
                    try {
                        IField field = JDTUtils.resolveField(proposal, unit.getJavaProject());
                        Region nameRegion = null;
                        if (field != null) {
                            ITypeRoot typeRoot = field.getTypeRoot();
                            ISourceRange nameRange = ((ISourceReference) field).getNameRange();
                            if (SourceRange.isAvailable(nameRange)) {
                                nameRegion = new Region(nameRange.getOffset(), nameRange.getLength());
                            }
                            constantValue = JDTUtils.getConstantValue(field, typeRoot, nameRegion);
                        }
                    } catch (JavaModelException e) {
                        JavaLanguageServerPlugin.log(e);
                    }
                }
                if (constantValue != null) {
                    if (manager.getClientPreferences().isSupportsCompletionDocumentationMarkdown()) {
                        javadoc = (javadoc == null ? EMPTY_STRING : javadoc) + "\n\n" + VALUE + constantValue;
                    } else {
                        javadoc = (javadoc == null ? EMPTY_STRING : javadoc) + VALUE + constantValue;
                    }
                }
                String defaultValue = null;
                if (proposal.getKind() == CompletionProposal.METHOD_REF || proposal.getKind() == CompletionProposal.ANNOTATION_ATTRIBUTE_REF) {
                    try {
                        IMethod method = JDTUtils.resolveMethod(proposal, unit.getJavaProject());
                        Region nameRegion = null;
                        if (method != null) {
                            ITypeRoot typeRoot = method.getTypeRoot();
                            ISourceRange nameRange = ((ISourceReference) method).getNameRange();
                            if (SourceRange.isAvailable(nameRange)) {
                                nameRegion = new Region(nameRange.getOffset(), nameRange.getLength());
                            }
                            defaultValue = JDTUtils.getAnnotationMemberDefaultValue(method, typeRoot, nameRegion);
                        }
                    } catch (JavaModelException e) {
                        JavaLanguageServerPlugin.log(e);
                    }
                }
                if (defaultValue != null) {
                    if (manager.getClientPreferences().isSupportsCompletionDocumentationMarkdown()) {
                        javadoc = (javadoc == null ? EMPTY_STRING : javadoc) + "\n\n" + DEFAULT + defaultValue;
                    } else {
                        javadoc = (javadoc == null ? EMPTY_STRING : javadoc) + DEFAULT + defaultValue;
                    }
                }
                if (javadoc != null) {
                    if (manager.getClientPreferences().isSupportsCompletionDocumentationMarkdown()) {
                        MarkupContent markupContent = new MarkupContent();
                        markupContent.setKind(MarkupKind.MARKDOWN);
                        markupContent.setValue(javadoc);
                        param.setDocumentation(markupContent);
                    } else {
                        param.setDocumentation(javadoc);
                    }
                }
            }
        } catch (JavaModelException e) {
            JavaLanguageServerPlugin.logException("Unable to resolve compilation", e);
            monitor.setCanceled(true);
        }
    }
    if (monitor.isCanceled()) {
        param.setData(null);
    }
    return param;
}
Also used : JavaModelException(org.eclipse.jdt.core.JavaModelException) Reader(java.io.Reader) UncheckedTimeoutException(com.google.common.util.concurrent.UncheckedTimeoutException) IMember(org.eclipse.jdt.core.IMember) Template(org.eclipse.jface.text.templates.Template) IType(org.eclipse.jdt.core.IType) InternalCompletionProposal(org.eclipse.jdt.internal.codeassist.InternalCompletionProposal) CompletionProposalReplacementProvider(org.eclipse.jdt.ls.core.internal.contentassist.CompletionProposalReplacementProvider) MethodBinding(org.eclipse.jdt.internal.compiler.lookup.MethodBinding) SnippetCompletionProposal(org.eclipse.jdt.ls.core.internal.contentassist.SnippetCompletionProposal) IMethod(org.eclipse.jdt.core.IMethod) TimeoutException(java.util.concurrent.TimeoutException) UncheckedTimeoutException(com.google.common.util.concurrent.UncheckedTimeoutException) ISourceRange(org.eclipse.jdt.core.ISourceRange) MethodBinding(org.eclipse.jdt.internal.compiler.lookup.MethodBinding) Binding(org.eclipse.jdt.internal.compiler.lookup.Binding) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) SnippetCompletionProposal(org.eclipse.jdt.ls.core.internal.contentassist.SnippetCompletionProposal) InternalCompletionProposal(org.eclipse.jdt.internal.codeassist.InternalCompletionProposal) CompletionProposal(org.eclipse.jdt.core.CompletionProposal) ITypeRoot(org.eclipse.jdt.core.ITypeRoot) ISourceRange(org.eclipse.jdt.core.ISourceRange) Range(org.eclipse.lsp4j.Range) SourceRange(org.eclipse.jdt.core.SourceRange) IField(org.eclipse.jdt.core.IField) MarkupContent(org.eclipse.lsp4j.MarkupContent) TimeoutException(java.util.concurrent.TimeoutException) JavaModelException(org.eclipse.jdt.core.JavaModelException) UncheckedTimeoutException(com.google.common.util.concurrent.UncheckedTimeoutException) CompletionContext(org.eclipse.jdt.core.CompletionContext) TextEdit(org.eclipse.lsp4j.TextEdit) Region(org.eclipse.jface.text.Region) ISourceReference(org.eclipse.jdt.core.ISourceReference)

Example 10 with CompletionContext

use of org.eclipse.jdt.core.CompletionContext in project jbosstools-hibernate by jbosstools.

the class FieldPropertyHandler method attributeCompletionProposals.

public ICompletionProposal[] attributeCompletionProposals(IJavaProject project, Node node, String attributeName, String start, int offset) {
    // TODO: should also try to find properties getXXX()
    if (project != null) {
        Node parentNode = node.getParentNode();
        String typename = null;
        typename = this.extractor.getNearestType(project, parentNode);
        if (typename == null) {
            // could not locate type
            return new IJavaCompletionProposal[0];
        }
        HibernateResultCollector rc = null;
        try {
            IType type = project.findType(typename);
            // nothing to look for then
            if (type == null)
                return new ICompletionProposal[0];
            rc = new HibernateResultCollector(project);
            rc.acceptContext(new CompletionContext());
            // TODO: only handle properties ?
            rc.setAccepts(false, false, false, false, true, false);
            // rc.reset(offset, javaProject, null);
            type.codeComplete(start.toCharArray(), -1, start.length(), new char[0][0], new char[0][0], new int[0], false, rc);
        } catch (JavaModelException jme) {
        // TODO: report
        }
        IJavaCompletionProposal[] results = rc.getJavaCompletionProposals();
        CompletionHelper.transpose(start, offset, results);
        return results;
    }
    return new ICompletionProposal[0];
}
Also used : CompletionContext(org.eclipse.jdt.core.CompletionContext) JavaModelException(org.eclipse.jdt.core.JavaModelException) Node(org.w3c.dom.Node) ICompletionProposal(org.eclipse.jface.text.contentassist.ICompletionProposal) IJavaCompletionProposal(org.eclipse.jdt.ui.text.java.IJavaCompletionProposal) HibernateResultCollector(org.hibernate.eclipse.hqleditor.HibernateResultCollector) IType(org.eclipse.jdt.core.IType)

Aggregations

CompletionContext (org.eclipse.jdt.core.CompletionContext)15 JavaModelException (org.eclipse.jdt.core.JavaModelException)9 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)6 IJavaProject (org.eclipse.jdt.core.IJavaProject)5 IType (org.eclipse.jdt.core.IType)5 IJavaCompletionProposal (org.eclipse.jdt.ui.text.java.IJavaCompletionProposal)5 ICompletionProposal (org.eclipse.jface.text.contentassist.ICompletionProposal)4 CompletionProposal (org.eclipse.jdt.core.CompletionProposal)3 BadLocationException (org.eclipse.jface.text.BadLocationException)3 ArrayList (java.util.ArrayList)2 HashSet (java.util.HashSet)2 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)2 IJavaElement (org.eclipse.jdt.core.IJavaElement)2 IMethod (org.eclipse.jdt.core.IMethod)2 JavaContentAssistInvocationContext (org.eclipse.jdt.ui.text.java.JavaContentAssistInvocationContext)2 UncheckedTimeoutException (com.google.common.util.concurrent.UncheckedTimeoutException)1 Reader (java.io.Reader)1 Arrays (java.util.Arrays)1 Collections (java.util.Collections)1 HashMap (java.util.HashMap)1