Search in sources :

Example 11 with CompletionContext

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

the class ContentAssistService method computeContentAssist.

protected JSONArray computeContentAssist(String username, String resourcePath, int offset, String prefix) throws JSONException {
    final List<CompletionProposal> proposals = new ArrayList<CompletionProposal>();
    final CompletionContext[] completionContextParam = new CompletionContext[] { null };
    ICompilationUnit liveEditUnit = liveEditUnits.getLiveEditUnit(username, resourcePath);
    try {
        if (liveEditUnit != null) {
            CompletionRequestor collector = new CompletionRequestor() {

                @Override
                public void accept(CompletionProposal proposal) {
                    proposals.add(proposal);
                }

                @Override
                public void acceptContext(CompletionContext context) {
                    super.acceptContext(context);
                    completionContextParam[0] = context;
                }
            };
            // Allow completions for unresolved types - since 3.3
            collector.setAllowsRequiredProposals(CompletionProposal.FIELD_REF, CompletionProposal.TYPE_REF, true);
            collector.setAllowsRequiredProposals(CompletionProposal.FIELD_REF, CompletionProposal.TYPE_IMPORT, true);
            collector.setAllowsRequiredProposals(CompletionProposal.FIELD_REF, CompletionProposal.FIELD_IMPORT, true);
            collector.setAllowsRequiredProposals(CompletionProposal.METHOD_REF, CompletionProposal.TYPE_REF, true);
            collector.setAllowsRequiredProposals(CompletionProposal.METHOD_REF, CompletionProposal.TYPE_IMPORT, true);
            collector.setAllowsRequiredProposals(CompletionProposal.METHOD_REF, CompletionProposal.METHOD_IMPORT, true);
            collector.setAllowsRequiredProposals(CompletionProposal.CONSTRUCTOR_INVOCATION, CompletionProposal.TYPE_REF, true);
            collector.setAllowsRequiredProposals(CompletionProposal.ANONYMOUS_CLASS_CONSTRUCTOR_INVOCATION, CompletionProposal.TYPE_REF, true);
            collector.setAllowsRequiredProposals(CompletionProposal.ANONYMOUS_CLASS_DECLARATION, CompletionProposal.TYPE_REF, true);
            collector.setAllowsRequiredProposals(CompletionProposal.TYPE_REF, CompletionProposal.TYPE_REF, true);
            liveEditUnit.codeComplete(offset, collector, new NullProgressMonitor());
        }
    } catch (JavaModelException e) {
        e.printStackTrace();
    }
    List<JSONObject> jsonProposals = new ArrayList<JSONObject>(proposals.size());
    CompletionContext completionContext = completionContextParam[0];
    for (CompletionProposal proposal : proposals) {
        JSONObject jsonDescription = getDescription(proposal, completionContext);
        ProposalReplcamentInfo replacementInfo = new CompletionProposalReplacementProvider(liveEditUnit, proposal, completionContext, offset, prefix).createReplacement();
        JSONObject jsonProposal = new JSONObject();
        jsonProposal.put("description", jsonDescription);
        jsonProposal.put("proposal", replacementInfo.replacement);
        int initOffset = offset - prefix.length();
        if (replacementInfo.extraChanges != null) {
            jsonProposal.put("additionalEdits", Utils.editsToJsonArray(replacementInfo.extraChanges));
            initOffset += Utils.getOffsetAdjustment(replacementInfo.extraChanges, initOffset);
        }
        if (replacementInfo.positions != null && !replacementInfo.positions.isEmpty()) {
            jsonProposal.put("positions", getPositions(replacementInfo.positions, initOffset));
        }
        jsonProposal.put("escapePosition", initOffset + replacementInfo.replacement.length());
        jsonProposal.put("style", "attributedString");
        jsonProposal.put("replace", true);
        jsonProposal.put("relevance", proposal.getRelevance());
        jsonProposals.add(jsonProposal);
    }
    Collections.sort(jsonProposals, new Comparator<JSONObject>() {

        @Override
        public int compare(JSONObject o1, JSONObject o2) {
            try {
                int diff = o2.getInt("relevance") - o1.getInt("relevance");
                if (diff == 0) {
                    JSONArray nameDescription1 = o1.getJSONObject("description").getJSONArray("segments");
                    JSONArray nameDescription2 = o2.getJSONObject("description").getJSONArray("segments");
                    StringBuilder nameBuffer1 = new StringBuilder();
                    for (int i = 0; i < nameDescription1.length(); i++) {
                        nameBuffer1.append(nameDescription1.getJSONObject(i).getString("value"));
                    }
                    StringBuilder nameBuffer2 = new StringBuilder();
                    for (int i = 0; i < nameDescription2.length(); i++) {
                        nameBuffer2.append(nameDescription2.getJSONObject(i).getString("value"));
                    }
                    return nameBuffer1.toString().compareTo(nameBuffer2.toString());
                } else {
                    return diff;
                }
            } catch (JSONException e) {
                return -1;
            }
        }
    });
    return new JSONArray(jsonProposals);
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) JavaModelException(org.eclipse.jdt.core.JavaModelException) CompletionProposal(org.eclipse.jdt.core.CompletionProposal) CompletionRequestor(org.eclipse.jdt.core.CompletionRequestor) ArrayList(java.util.ArrayList) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) CompletionContext(org.eclipse.jdt.core.CompletionContext) JSONObject(org.json.JSONObject)

Example 12 with CompletionContext

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

the class JavaCompletionProcessor method computeCompletionProposals.

public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int position) {
    try {
        setErrorMessage(null);
        if (editor.getConsoleConfiguration() == null) {
            setErrorMessage(HibernateConsoleMessages.JavaCompletionProcessor_no_console_configuration_found);
            return new ICompletionProposal[0];
        }
        // has to do this because of https://bugs.eclipse.org/bugs/show_bug.cgi?id=141518
        String prefix = HibernateConsoleMessages.JavaCompletionProcessor_session_session;
        IJavaCompletionProposal[] results = new IJavaCompletionProposal[0];
        IJavaProject[] projects = null;
        // try {
        projects = ProjectUtils.findJavaProjects(editor.getConsoleConfiguration());
        /*} catch (RuntimeException e){
				String mess = NLS.bind(HibernateConsoleMessages.JavaCompletionProcessor_error_find_project,
						editor.getConsoleConfiguration().getName());
				HibernateConsolePlugin.getDefault().logErrorMessage(mess, e);
			}*/
        for (int i = 0; projects != null && i < projects.length && results.length <= 0; i++) {
            IJavaProject javaProject = projects[i];
            collector = new CompletionProposalCollector(javaProject);
            collector.acceptContext(new CompletionContext());
            try {
                editor.codeComplete(prefix, collector, position, javaProject);
            } catch (JavaModelException x) {
                Shell shell = viewer.getTextWidget().getShell();
                ErrorDialog.openError(shell, HibernateConsoleMessages.JavaCompletionProcessor_error, HibernateConsoleMessages.JavaCompletionProcessor_error_while_performing_code_completion, x.getStatus());
                HibernateConsolePlugin.getDefault().log(x);
            }
            results = collector.getJavaCompletionProposals();
        }
        CompletionHelper.transpose(null, -prefix.length(), results);
        return results;
    } finally {
        if (collector != null) {
            setErrorMessage(collector.getErrorMessage());
            collector = null;
        }
    }
}
Also used : CompletionContext(org.eclipse.jdt.core.CompletionContext) JavaModelException(org.eclipse.jdt.core.JavaModelException) Shell(org.eclipse.swt.widgets.Shell) IJavaProject(org.eclipse.jdt.core.IJavaProject) CompletionProposalCollector(org.eclipse.jdt.ui.text.java.CompletionProposalCollector) ICompletionProposal(org.eclipse.jface.text.contentassist.ICompletionProposal) IJavaCompletionProposal(org.eclipse.jdt.ui.text.java.IJavaCompletionProposal)

Example 13 with CompletionContext

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

the class CompletionHelper method completeOnJavaTypes.

public static ICompletionProposal[] completeOnJavaTypes(IJavaProject javaProject, Settings settings, String packageName, String start, int offset) {
    if (javaProject != null) {
        IEvaluationContext context = javaProject.newEvaluationContext();
        if (packageName != null) {
            context.setPackageName(packageName);
        }
        HibernateResultCollector rc = new HibernateResultCollector(javaProject);
        rc.acceptContext(new CompletionContext());
        // rc.reset(offset, javaProject, null);
        rc.setAccepts(settings);
        try {
            // cannot send in my own document as it won't compile as
            // java - so we just send in
            // the smallest snippet possible
            context.codeComplete(start, start.length(), rc);
        } catch (JavaModelException jme) {
            HibernateConsolePlugin.getDefault().logErrorMessage(HibernateConsoleMessages.CompletionHelper_could_not_complete_java_types, jme);
        }
        IJavaCompletionProposal[] results = rc.getJavaCompletionProposals();
        transpose(start, offset, results);
        return results;
    }
    return new ICompletionProposal[0];
}
Also used : CompletionContext(org.eclipse.jdt.core.CompletionContext) JavaModelException(org.eclipse.jdt.core.JavaModelException) ICompletionProposal(org.eclipse.jface.text.contentassist.ICompletionProposal) IEvaluationContext(org.eclipse.jdt.core.eval.IEvaluationContext) IJavaCompletionProposal(org.eclipse.jdt.ui.text.java.IJavaCompletionProposal)

Example 14 with CompletionContext

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

the class SnippetCompletionProposal method getGenericSnippets.

private static List<CompletionItem> getGenericSnippets(SnippetCompletionContext scc) throws JavaModelException {
    CompletionResponse response = new CompletionResponse();
    response.setContext(scc.getCompletionContext());
    response.setOffset(scc.getCompletionContext().getOffset());
    List<CompletionItem> res = new ArrayList<>();
    CompletionContext completionContext = scc.getCompletionContext();
    char[] completionToken = completionContext.getToken();
    if (completionToken == null) {
        return Collections.emptyList();
    }
    int tokenLocation = completionContext.getTokenLocation();
    JavaContextType contextType = (JavaContextType) JavaLanguageServerPlugin.getInstance().getTemplateContextRegistry().getContextType(JavaContextType.ID_STATEMENTS);
    if (contextType == null) {
        return Collections.emptyList();
    }
    ICompilationUnit cu = scc.getCompilationUnit();
    IDocument document = new Document(cu.getSource());
    DocumentTemplateContext javaContext = contextType.createContext(document, completionContext.getOffset(), completionToken.length, cu);
    Template[] templates = null;
    if ((tokenLocation & CompletionContext.TL_STATEMENT_START) != 0) {
        templates = JavaLanguageServerPlugin.getInstance().getTemplateStore().getTemplates(JavaContextType.ID_STATEMENTS);
    } else {
    // We only support statement templates for now.
    }
    if (templates == null || templates.length == 0) {
        return Collections.emptyList();
    }
    String uri = JDTUtils.toURI(cu);
    Template[] availableTemplates = Arrays.stream(templates).filter(t -> javaContext.canEvaluate(t)).toArray(Template[]::new);
    List<CompletionProposal> proposals = new ArrayList<>();
    for (int i = 0; i < availableTemplates.length; i++) {
        Template template = availableTemplates[i];
        final CompletionItem item = new CompletionItem();
        item.setLabel(template.getName());
        item.setKind(CompletionItemKind.Snippet);
        item.setInsertTextFormat(InsertTextFormat.Snippet);
        item.setInsertText(SnippetUtils.templateToSnippet(template.getPattern()));
        item.setDetail(template.getDescription());
        Map<String, String> data = new HashMap<>(3);
        data.put(CompletionResolveHandler.DATA_FIELD_URI, uri);
        data.put(CompletionResolveHandler.DATA_FIELD_REQUEST_ID, String.valueOf(response.getId()));
        data.put(CompletionResolveHandler.DATA_FIELD_PROPOSAL_ID, String.valueOf(i));
        item.setData(data);
        proposals.add(i, new SnippetCompletionProposal(template));
        res.add(item);
    }
    response.setProposals(proposals);
    CompletionResponses.store(response);
    return res;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) Arrays(java.util.Arrays) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) Template(org.eclipse.jface.text.templates.Template) CoreException(org.eclipse.core.runtime.CoreException) CompletionContext(org.eclipse.jdt.core.CompletionContext) CompletionOnFieldType(org.eclipse.jdt.internal.codeassist.complete.CompletionOnFieldType) Map(java.util.Map) CodeTemplateContextType(org.eclipse.jdt.internal.core.manipulation.CodeTemplateContextType) IPackageDeclaration(org.eclipse.jdt.core.IPackageDeclaration) JDTUtils(org.eclipse.jdt.ls.core.internal.JDTUtils) DocumentTemplateContext(org.eclipse.jface.text.templates.DocumentTemplateContext) InsertTextFormat(org.eclipse.lsp4j.InsertTextFormat) TokenScanner(org.eclipse.jdt.internal.corext.dom.TokenScanner) IJavaProject(org.eclipse.jdt.core.IJavaProject) Predicate(java.util.function.Predicate) Status(org.eclipse.core.runtime.Status) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) CompletionOnKeyword2(org.eclipse.jdt.internal.codeassist.complete.CompletionOnKeyword2) JavaModelUtil(org.eclipse.jdt.internal.corext.util.JavaModelUtil) IType(org.eclipse.jdt.core.IType) CompletionItem(org.eclipse.lsp4j.CompletionItem) List(java.util.List) CompletionResponse(org.eclipse.jdt.ls.core.internal.handlers.CompletionResponse) InternalCompletionContext(org.eclipse.jdt.internal.codeassist.InternalCompletionContext) JavaContextType(org.eclipse.jdt.ls.core.internal.corext.template.java.JavaContextType) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) JavaModelException(org.eclipse.jdt.core.JavaModelException) HashMap(java.util.HashMap) ASTNode(org.eclipse.jdt.internal.compiler.ast.ASTNode) ArrayList(java.util.ArrayList) TemplateException(org.eclipse.jface.text.templates.TemplateException) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) CompletionItemKind(org.eclipse.lsp4j.CompletionItemKind) TemplateBuffer(org.eclipse.jface.text.templates.TemplateBuffer) Strings(org.eclipse.jdt.internal.core.manipulation.util.Strings) BadLocationException(org.eclipse.jface.text.BadLocationException) CodeTemplateContext(org.eclipse.jdt.internal.core.manipulation.CodeTemplateContext) JavaCore(org.eclipse.jdt.core.JavaCore) ASTNodeSearchUtil(org.eclipse.jdt.internal.corext.refactoring.structure.ASTNodeSearchUtil) JavaLanguageServerPlugin(org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin) CompletionResponses(org.eclipse.jdt.ls.core.internal.handlers.CompletionResponses) CompletionProposal(org.eclipse.jdt.core.CompletionProposal) Initializer(org.eclipse.jdt.core.dom.Initializer) CoreASTProvider(org.eclipse.jdt.core.manipulation.CoreASTProvider) CodeGenerationTemplate(org.eclipse.jdt.ls.core.internal.preferences.CodeGenerationTemplate) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) IMethod(org.eclipse.jdt.core.IMethod) ITerminalSymbols(org.eclipse.jdt.core.compiler.ITerminalSymbols) CompletionOnSingleNameReference(org.eclipse.jdt.internal.codeassist.complete.CompletionOnSingleNameReference) Collections(java.util.Collections) CompletionResolveHandler(org.eclipse.jdt.ls.core.internal.handlers.CompletionResolveHandler) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompletionProposal(org.eclipse.jdt.core.CompletionProposal) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) Template(org.eclipse.jface.text.templates.Template) CodeGenerationTemplate(org.eclipse.jdt.ls.core.internal.preferences.CodeGenerationTemplate) CompletionContext(org.eclipse.jdt.core.CompletionContext) InternalCompletionContext(org.eclipse.jdt.internal.codeassist.InternalCompletionContext) CompletionResponse(org.eclipse.jdt.ls.core.internal.handlers.CompletionResponse) JavaContextType(org.eclipse.jdt.ls.core.internal.corext.template.java.JavaContextType) CompletionItem(org.eclipse.lsp4j.CompletionItem) DocumentTemplateContext(org.eclipse.jface.text.templates.DocumentTemplateContext) IDocument(org.eclipse.jface.text.IDocument)

Example 15 with CompletionContext

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

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<>();
                for (ICompletionProposal iCompletionProposal : types) {
                    AbstractJavaCompletionProposal p = (AbstractJavaCompletionProposal) iCompletionProposal;
                    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 (String type : history) {
                    if (proposed.contains(type))
                        continue;
                    IJavaCompletionProposal proposal = createTypeProposal(relevance, type, javaContext);
                    if (proposal != null)
                        types.add(proposal);
                    relevance++;
                }
            }
        }
    } catch (BadLocationException | 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.jface.text.contentassist.ICompletionProposal) BadLocationException(org.eclipse.jface.text.BadLocationException) HashSet(java.util.HashSet)

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