Search in sources :

Example 6 with CustomCompletionProposal

use of org.eclipse.wst.sse.ui.internal.contentassist.CustomCompletionProposal in project webtools.sourceediting by eclipse.

the class JSPUseBeanCompletionProposalComputer method addAttributeValueProposals.

/**
 * @see org.eclipse.wst.xml.ui.internal.contentassist.DefaultXMLCompletionProposalComputer#addAttributeValueProposals(org.eclipse.wst.xml.ui.internal.contentassist.ContentAssistRequest, org.eclipse.wst.sse.ui.contentassist.CompletionProposalInvocationContext)
 */
protected void addAttributeValueProposals(ContentAssistRequest contentAssistRequest, CompletionProposalInvocationContext context) {
    IDOMNode node = (IDOMNode) contentAssistRequest.getNode();
    // only add attribute value proposals for specific elements
    if (node.getNodeName().equals(JSP11Namespace.ElementName.USEBEAN)) {
        // Find the attribute name for which this position should have a value
        IStructuredDocumentRegion open = node.getFirstStructuredDocumentRegion();
        ITextRegionList openRegions = open.getRegions();
        int i = openRegions.indexOf(contentAssistRequest.getRegion());
        if (i < 0)
            return;
        ITextRegion nameRegion = null;
        while (i >= 0) {
            nameRegion = openRegions.get(i--);
            if (nameRegion.getType() == DOMRegionContext.XML_TAG_ATTRIBUTE_NAME)
                break;
        }
        String attributeName = null;
        if (nameRegion != null)
            attributeName = open.getText(nameRegion);
        String currentValue = null;
        if (contentAssistRequest.getRegion().getType() == DOMRegionContext.XML_TAG_ATTRIBUTE_VALUE)
            currentValue = contentAssistRequest.getText();
        else
            // $NON-NLS-1$
            currentValue = "";
        String matchString = null;
        // fixups
        int start = contentAssistRequest.getReplacementBeginPosition();
        int length = contentAssistRequest.getReplacementLength();
        if (// $NON-NLS-1$ //$NON-NLS-2$
        currentValue.length() > StringUtils.strip(currentValue).length() && (currentValue.startsWith("\"") || currentValue.startsWith("'")) && contentAssistRequest.getMatchString().length() > 0) {
            matchString = currentValue.substring(1, contentAssistRequest.getMatchString().length());
            start++;
            length = matchString.length();
        } else
            matchString = currentValue.substring(0, contentAssistRequest.getMatchString().length());
        boolean existingComplicatedValue = contentAssistRequest.getRegion() != null && contentAssistRequest.getRegion() instanceof ITextRegionContainer;
        if (existingComplicatedValue) {
            contentAssistRequest.getProposals().clear();
            contentAssistRequest.getMacros().clear();
        } else {
            if (attributeName.equals(JSP11Namespace.ATTR_NAME_CLASS)) {
                // class is the concrete implementation class
                IResource resource = JSPContentAssistHelper.getResource(contentAssistRequest);
                ICompletionProposal[] classProposals = JavaTypeFinder.getClassProposals(resource, start, length);
                if (classProposals != null) {
                    for (int j = 0; j < classProposals.length; j++) {
                        JavaTypeCompletionProposal proposal = (JavaTypeCompletionProposal) classProposals[j];
                        if (matchString.length() == 0 || proposal.getQualifiedName().toLowerCase().startsWith(matchString.toLowerCase()) || proposal.getShortName().toLowerCase().startsWith(matchString.toLowerCase()))
                            contentAssistRequest.addProposal(proposal);
                    }
                }
            } else if (attributeName.equals(JSP11Namespace.ATTR_NAME_TYPE)) {
                // type is the more general type for the bean
                // which means it may be an interface
                IResource resource = JSPContentAssistHelper.getResource(contentAssistRequest);
                ICompletionProposal[] typeProposals = JavaTypeFinder.getTypeProposals(resource, start, length);
                if (typeProposals != null) {
                    for (int j = 0; j < typeProposals.length; j++) {
                        JavaTypeCompletionProposal proposal = (JavaTypeCompletionProposal) typeProposals[j];
                        if (matchString.length() == 0 || proposal.getQualifiedName().toLowerCase().startsWith(matchString.toLowerCase()) || proposal.getShortName().toLowerCase().startsWith(matchString.toLowerCase()))
                            contentAssistRequest.addProposal(proposal);
                    }
                }
            } else if (attributeName.equals(JSP11Namespace.ATTR_NAME_BEAN_NAME)) {
                IResource resource = JSPContentAssistHelper.getResource(contentAssistRequest);
                ICompletionProposal[] beanNameProposals = JavaTypeFinder.getBeanProposals(resource, start, length);
                if (beanNameProposals != null) {
                    for (int j = 0; j < beanNameProposals.length; j++) {
                        if (beanNameProposals[j] instanceof CustomCompletionProposal) {
                            JavaTypeCompletionProposal proposal = (JavaTypeCompletionProposal) beanNameProposals[j];
                            if (matchString.length() == 0 || proposal.getDisplayString().toLowerCase().startsWith(matchString.toLowerCase()))
                                contentAssistRequest.addProposal(proposal);
                        } else if (beanNameProposals[j] instanceof JavaTypeCompletionProposal) {
                            JavaTypeCompletionProposal proposal = (JavaTypeCompletionProposal) beanNameProposals[j];
                            if (matchString.length() == 0 || proposal.getQualifiedName().toLowerCase().startsWith(matchString.toLowerCase()) || proposal.getShortName().toLowerCase().startsWith(matchString.toLowerCase()))
                                contentAssistRequest.addProposal(proposal);
                        }
                    }
                }
            }
        }
    }
}
Also used : IStructuredDocumentRegion(org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion) CustomCompletionProposal(org.eclipse.wst.sse.ui.internal.contentassist.CustomCompletionProposal) ITextRegionContainer(org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionContainer) ITextRegionList(org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionList) IDOMNode(org.eclipse.wst.xml.core.internal.provisional.document.IDOMNode) ITextRegion(org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion) ICompletionProposal(org.eclipse.jface.text.contentassist.ICompletionProposal) IResource(org.eclipse.core.resources.IResource)

Example 7 with CustomCompletionProposal

use of org.eclipse.wst.sse.ui.internal.contentassist.CustomCompletionProposal in project webtools.sourceediting by eclipse.

the class JSPContentAssistProcessor method addAttributeValueProposals.

/**
 * add proposals for tags in attribute values
 */
protected void addAttributeValueProposals(ContentAssistRequest contentAssistRequest) {
    addTemplates(contentAssistRequest, TemplateContextTypeIdsJSP.ATTRIBUTE_VALUE);
    IDOMNode node = (IDOMNode) contentAssistRequest.getNode();
    // add JSP extra proposals from JSPBeanInfoContentAssistProcessor
    // JSPPropertyContentAssistProcessor
    // 2.1
    // get results from JSPUseBean and JSPProperty here
    // (look up processor in a map based on node name)
    JSPDummyContentAssistProcessor extraProcessor = (JSPDummyContentAssistProcessor) fNameToProcessorMap.get(node.getNodeName());
    if (extraProcessor != null && contentAssistRequest != null) {
        extraProcessor.addAttributeValueProposals(contentAssistRequest);
    }
    ModelQuery mq = ModelQueryUtil.getModelQuery(node.getOwnerDocument());
    if (mq != null) {
        CMDocument doc = mq.getCorrespondingCMDocument(node);
        // this shouldn't have to have the prefix coded in
        if (// $NON-NLS-1$
        doc instanceof JSPCMDocument || doc instanceof CMNodeWrapper || node.getNodeName().startsWith("jsp:"))
            return;
    }
    // Find the attribute name for which this position should have a value
    IStructuredDocumentRegion open = node.getFirstStructuredDocumentRegion();
    ITextRegionList openRegions = open.getRegions();
    int i = openRegions.indexOf(contentAssistRequest.getRegion());
    if (i < 0)
        return;
    ITextRegion nameRegion = null;
    while (i >= 0) {
        nameRegion = openRegions.get(i--);
        if (nameRegion.getType() == DOMRegionContext.XML_TAG_ATTRIBUTE_NAME)
            break;
    }
    // on an empty value, add all the JSP and taglib tags
    CMElementDeclaration elementDecl = getCMElementDeclaration(node);
    if (nameRegion != null && elementDecl != null) {
        String attributeName = open.getText(nameRegion);
        if (attributeName != null) {
            String currentValue = node.getAttributes().getNamedItem(attributeName).getNodeValue();
            if (currentValue == null || currentValue.length() == 0) {
                // $NON-NLS-1$
                List additionalElements = ModelQueryUtil.getModelQuery(node.getOwnerDocument()).getAvailableContent((Element) node, elementDecl, ModelQuery.INCLUDE_ATTRIBUTES);
                for (i = 0; i < additionalElements.size(); i++) {
                    Object additionalElement = additionalElements.get(i);
                    if (additionalElement instanceof CMElementDeclaration) {
                        CMElementDeclaration ed = (CMElementDeclaration) additionalElement;
                        String tagname = getContentGenerator().getRequiredName(node, ed);
                        // $NON-NLS-1$
                        StringBuffer contents = new StringBuffer("\"");
                        getContentGenerator().generateTag(node, ed, contents);
                        // $NON-NLS-1$
                        contents.append('"');
                        CustomCompletionProposal proposal = new CustomCompletionProposal(contents.toString(), contentAssistRequest.getReplacementBeginPosition(), contentAssistRequest.getReplacementLength(), contents.length(), JSPEditorPluginImageHelper.getInstance().getImage(JSPEditorPluginImages.IMG_OBJ_TAG_GENERIC), tagname, null, null, XMLRelevanceConstants.R_JSP_ATTRIBUTE_VALUE);
                        contentAssistRequest.addProposal(proposal);
                    }
                }
            }
        }
    } else if (contentAssistRequest.getRegion().getType() == DOMRegionContext.XML_TAG_ATTRIBUTE_VALUE) {
        try {
            // Create a new model for Content Assist to operate on. This
            // will simulate
            // a full Document and then adjust the offset numbers in the
            // list of results.
            IStructuredModel internalModel = null;
            IModelManager mmanager = StructuredModelManager.getModelManager();
            internalModel = mmanager.createUnManagedStructuredModelFor(ContentTypeIdForJSP.ContentTypeID_JSP);
            IDOMNode xmlNode = null;
            IDOMModel xmlOuterModel = null;
            if (contentAssistRequest.getNode() instanceof IDOMNode) {
                xmlNode = (IDOMNode) contentAssistRequest.getNode();
                xmlOuterModel = xmlNode.getModel();
                internalModel.setResolver(xmlOuterModel.getResolver());
                internalModel.setBaseLocation(xmlOuterModel.getBaseLocation());
            }
            String contents = StringUtils.strip(contentAssistRequest.getText());
            if (xmlNode != null && contents != null) {
                int additionalShifts = 0;
                // Be sure that custom tags from taglibs also show up
                // by
                // adding taglib declarations to the internal model.
                TLDCMDocumentManager mgr = TaglibController.getTLDCMDocumentManager(xmlOuterModel.getStructuredDocument());
                if (mgr != null) {
                    List trackers = mgr.getCMDocumentTrackers(contentAssistRequest.getReplacementBeginPosition());
                    if (trackers != null) {
                        for (i = 0; i < trackers.size(); i++) {
                            CMDocumentTracker tracker = (CMDocumentTracker) trackers.get(i);
                            String declaration = tracker.getStructuredDocumentRegion().getText();
                            if (declaration != null) {
                                contents = declaration + contents;
                                additionalShifts += declaration.length();
                            }
                        }
                    }
                }
                // Also copy any jsp:useBean tags so that
                // jsp:[gs]etProperty will function
                Document doc = null;
                if (contentAssistRequest.getNode().getNodeType() == Node.DOCUMENT_NODE)
                    doc = (Document) node;
                else
                    doc = node.getOwnerDocument();
                NodeList useBeans = doc.getElementsByTagName(JSP12Namespace.ElementName.USEBEAN);
                for (int k = 0; k < useBeans.getLength(); k++) {
                    IDOMNode useBean = (IDOMNode) useBeans.item(k);
                    if (useBean.getStartOffset() < contentAssistRequest.getReplacementBeginPosition()) {
                        // $NON-NLS-1$
                        StringBuffer useBeanText = new StringBuffer("<jsp:useBean");
                        for (int j = 0; j < useBean.getAttributes().getLength(); j++) {
                            Attr attr = (Attr) useBean.getAttributes().item(j);
                            useBeanText.append(' ');
                            useBeanText.append(attr.getName());
                            // $NON-NLS-1$
                            useBeanText.append("=\"");
                            useBeanText.append(attr.getValue());
                            useBeanText.append('"');
                        }
                        // $NON-NLS-1$
                        useBeanText.append("/>");
                        additionalShifts += useBeanText.length();
                        contents = useBeanText.toString() + contents;
                    }
                }
                internalModel.getStructuredDocument().set(contents);
                int internalOffset = 0;
                boolean quoted = false;
                // if quoted, use position inside and shift by one
                if (contentAssistRequest.getMatchString().length() > 0 && (contentAssistRequest.getMatchString().charAt(0) == '\'' || contentAssistRequest.getMatchString().charAt(0) == '"')) {
                    internalOffset = contentAssistRequest.getMatchString().length() - 1 + additionalShifts;
                    quoted = true;
                } else // if unquoted, use position inside
                if (contentAssistRequest.getMatchString().length() > 0 && contentAssistRequest.getMatchString().charAt(0) == '<')
                    internalOffset = contentAssistRequest.getMatchString().length() + additionalShifts;
                else
                    internalOffset = contentAssistRequest.getReplacementBeginPosition() - contentAssistRequest.getStartOffset() + additionalShifts;
                depthCount++;
                IndexedRegion internalNode = null;
                int tmpOffset = internalOffset;
                while (internalNode == null && tmpOffset >= 0) internalNode = internalModel.getIndexedRegion(tmpOffset--);
                if (internalModel.getFactoryRegistry() != null) {
                    // set up the internal model
                    if (internalModel.getFactoryRegistry().getFactoryFor(PageDirectiveAdapter.class) == null) {
                        internalModel.getFactoryRegistry().addFactory(new PageDirectiveAdapterFactory());
                    }
                    PageDirectiveAdapter outerEmbeddedTypeAdapter = (PageDirectiveAdapter) xmlOuterModel.getDocument().getAdapterFor(PageDirectiveAdapter.class);
                    PageDirectiveAdapter internalEmbeddedTypeAdapter = (PageDirectiveAdapter) ((INodeNotifier) ((Node) internalNode).getOwnerDocument()).getAdapterFor(PageDirectiveAdapter.class);
                    internalEmbeddedTypeAdapter.setEmbeddedType(outerEmbeddedTypeAdapter.getEmbeddedType());
                }
                AdapterFactoryRegistry adapterRegistry = JSPUIPlugin.getDefault().getAdapterFactoryRegistry();
                Iterator adapterList = adapterRegistry.getAdapterFactories();
                // of content
                while (adapterList.hasNext()) {
                    try {
                        AdapterFactoryProvider provider = (AdapterFactoryProvider) adapterList.next();
                        if (provider.isFor(internalModel.getModelHandler())) {
                            provider.addAdapterFactories(internalModel);
                        }
                    } catch (Exception e) {
                        Logger.logException(e);
                    }
                }
                /**
                 * the internal adapter does all the real work of using
                 * the JSP content model to form proposals
                 */
                ICompletionProposal[] results = null;
                depthCount--;
                if (results != null) {
                    for (i = 0; i < results.length; i++) {
                        contentAssistRequest.addProposal(new CustomCompletionProposal(((CustomCompletionProposal) results[i]).getReplacementString(), ((CustomCompletionProposal) results[i]).getReplacementOffset() - additionalShifts + contentAssistRequest.getStartOffset() + (quoted ? 1 : 0), ((CustomCompletionProposal) results[i]).getReplacementLength(), ((CustomCompletionProposal) results[i]).getCursorPosition(), results[i].getImage(), results[i].getDisplayString(), ((CustomCompletionProposal) results[i]).getContextInformation(), ((CustomCompletionProposal) results[i]).getAdditionalProposalInfo(), (results[i] instanceof IRelevanceCompletionProposal) ? ((IRelevanceCompletionProposal) results[i]).getRelevance() : IRelevanceConstants.R_NONE));
                    }
                }
            }
        } catch (Exception e) {
            // $NON-NLS-1$
            Logger.logException("Error in embedded JSP Content Assist", e);
        }
    }
}
Also used : IStructuredDocumentRegion(org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion) CMNodeWrapper(org.eclipse.wst.xml.core.internal.provisional.contentmodel.CMNodeWrapper) IDOMModel(org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel) PageDirectiveAdapterFactory(org.eclipse.jst.jsp.core.internal.document.PageDirectiveAdapterFactory) CustomCompletionProposal(org.eclipse.wst.sse.ui.internal.contentassist.CustomCompletionProposal) IModelManager(org.eclipse.wst.sse.core.internal.provisional.IModelManager) PageDirectiveAdapter(org.eclipse.jst.jsp.core.internal.document.PageDirectiveAdapter) Document(org.w3c.dom.Document) JSPCMDocument(org.eclipse.wst.html.core.internal.contentmodel.JSPCMDocument) IDocument(org.eclipse.jface.text.IDocument) CMDocument(org.eclipse.wst.xml.core.internal.contentmodel.CMDocument) IStructuredDocument(org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument) Attr(org.w3c.dom.Attr) IDOMNode(org.eclipse.wst.xml.core.internal.provisional.document.IDOMNode) CMDocumentTracker(org.eclipse.wst.xml.core.internal.provisional.contentmodel.CMDocumentTracker) IRelevanceCompletionProposal(org.eclipse.wst.sse.ui.internal.contentassist.IRelevanceCompletionProposal) Iterator(java.util.Iterator) List(java.util.List) ITextRegionList(org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionList) ArrayList(java.util.ArrayList) NodeList(org.w3c.dom.NodeList) INodeNotifier(org.eclipse.wst.sse.core.internal.provisional.INodeNotifier) JSPCMDocument(org.eclipse.wst.html.core.internal.contentmodel.JSPCMDocument) CMDocument(org.eclipse.wst.xml.core.internal.contentmodel.CMDocument) AdapterFactoryProvider(org.eclipse.wst.sse.ui.internal.provisional.registry.AdapterFactoryProvider) TLDCMDocumentManager(org.eclipse.jst.jsp.core.internal.contentmodel.tld.TLDCMDocumentManager) NodeList(org.w3c.dom.NodeList) IndexedRegion(org.eclipse.wst.sse.core.internal.provisional.IndexedRegion) BadLocationException(org.eclipse.jface.text.BadLocationException) ITextRegionList(org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionList) CMElementDeclaration(org.eclipse.wst.xml.core.internal.contentmodel.CMElementDeclaration) ITextRegion(org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion) JSPCMDocument(org.eclipse.wst.html.core.internal.contentmodel.JSPCMDocument) ModelQuery(org.eclipse.wst.xml.core.internal.contentmodel.modelquery.ModelQuery) IStructuredModel(org.eclipse.wst.sse.core.internal.provisional.IStructuredModel) AdapterFactoryRegistry(org.eclipse.wst.sse.ui.internal.provisional.registry.AdapterFactoryRegistry)

Example 8 with CustomCompletionProposal

use of org.eclipse.wst.sse.ui.internal.contentassist.CustomCompletionProposal in project webtools.sourceediting by eclipse.

the class XSLCompletionTest method testVariableInsertPositionOffset.

// Bug 281420 - Variable inserts wrong.
@Test
public void testVariableInsertPositionOffset() throws Exception {
    fileName = "bug281420.xsl";
    String xslFilePath = projectName + File.separator + fileName;
    loadFileForTesting(xslFilePath);
    ICompletionProposal[] proposals = getProposals(7, 29);
    assertTrue("Did not find any proposals.", proposals.length > 0);
    CustomCompletionProposal testprop = null;
    for (int cnt = 0; cnt < proposals.length; cnt++) {
        if (proposals[cnt].getDisplayString().equals("$test")) {
            testprop = (CustomCompletionProposal) proposals[cnt];
        }
    }
    if (testprop == null) {
        fail("Didn't find the $test proposal");
    }
    int startoffset = calculateOffset(7, 28);
    if (testprop.getReplacementOffset() != startoffset) {
        fail("Replacement Offset position worng expected " + startoffset + "but received " + testprop.getReplacementOffset());
    }
}
Also used : ICompletionProposal(org.eclipse.jface.text.contentassist.ICompletionProposal) CustomCompletionProposal(org.eclipse.wst.sse.ui.internal.contentassist.CustomCompletionProposal) Test(org.junit.Test) AbstractSourceViewerTest(org.eclipse.wst.xsl.ui.tests.AbstractSourceViewerTest)

Example 9 with CustomCompletionProposal

use of org.eclipse.wst.sse.ui.internal.contentassist.CustomCompletionProposal in project webtools.sourceediting by eclipse.

the class AbstractContentAssistProcessor method addTagInsertionProposals.

protected void addTagInsertionProposals(ContentAssistRequest contentAssistRequest, int childPosition) {
    List cmnodes = null;
    Node parent = contentAssistRequest.getParent();
    String error = null;
    // only valid if it's XML (check added 2/17/2004)
    if ((parent != null) && (parent.getNodeType() == Node.DOCUMENT_NODE) && ((IDOMDocument) parent).isXMLType() && !isCursorAfterXMLPI(contentAssistRequest)) {
        return;
    }
    // only want proposals if cursor is after doctype...
    if (!isCursorAfterDoctype(contentAssistRequest)) {
        return;
    }
    // have a content model (so can't propose any children..)
    if ((parent != null) && (parent instanceof IDOMNode) && isCommentNode((IDOMNode) parent)) {
        // loop and find non comment node?
        while ((parent != null) && isCommentNode((IDOMNode) parent)) {
            parent = parent.getParentNode();
        }
    }
    if (parent.getNodeType() == Node.ELEMENT_NODE) {
        CMElementDeclaration parentDecl = getCMElementDeclaration(parent);
        if (parentDecl != null) {
            // XSD-specific ability - no filtering
            CMDataType childType = parentDecl.getDataType();
            if (childType != null) {
                String[] childStrings = childType.getEnumeratedValues();
                String defaultValue = childType.getImpliedValue();
                if (childStrings != null || defaultValue != null) {
                    // the content string is the sole valid child...so
                    // replace the rest
                    int begin = contentAssistRequest.getReplacementBeginPosition();
                    int length = contentAssistRequest.getReplacementLength();
                    if (parent instanceof IDOMNode) {
                        if (((IDOMNode) parent).getLastStructuredDocumentRegion() != ((IDOMNode) parent).getFirstStructuredDocumentRegion()) {
                            begin = ((IDOMNode) parent).getFirstStructuredDocumentRegion().getEndOffset();
                            length = ((IDOMNode) parent).getLastStructuredDocumentRegion().getStartOffset() - begin;
                        }
                    }
                    String proposedInfo = getAdditionalInfo(parentDecl, childType);
                    for (int i = 0; i < childStrings.length; i++) {
                        if (!childStrings[i].equals(defaultValue)) {
                            CustomCompletionProposal textProposal = new CustomCompletionProposal(childStrings[i], begin, length, childStrings[i].length(), XMLEditorPluginImageHelper.getInstance().getImage(XMLEditorPluginImages.IMG_OBJ_ENUM), childStrings[i], null, proposedInfo, XMLRelevanceConstants.R_TAG_INSERTION);
                            contentAssistRequest.addProposal(textProposal);
                        }
                    }
                    if (defaultValue != null) {
                        CustomCompletionProposal textProposal = new CustomCompletionProposal(defaultValue, begin, length, defaultValue.length(), XMLEditorPluginImageHelper.getInstance().getImage(XMLEditorPluginImages.IMG_OBJ_DEFAULT), defaultValue, null, proposedInfo, XMLRelevanceConstants.R_TAG_INSERTION);
                        contentAssistRequest.addProposal(textProposal);
                    }
                }
            }
        }
        if ((parentDecl != null) && (parentDecl.getContentType() == CMElementDeclaration.PCDATA)) {
            addPCDATAProposal(parentDecl.getNodeName(), contentAssistRequest);
        } else {
            // retrieve the list of all possible children within this
            // parent context
            cmnodes = getAvailableChildElementDeclarations((Element) parent, childPosition, ModelQueryAction.INSERT);
            // retrieve the list of the possible children within this
            // parent context and at this index
            List strictCMNodeSuggestions = null;
            if (XMLUIPreferenceNames.SUGGESTION_STRATEGY_VALUE_STRICT.equals(XMLUIPlugin.getInstance().getPreferenceStore().getString(XMLUIPreferenceNames.SUGGESTION_STRATEGY))) {
                strictCMNodeSuggestions = getValidChildElementDeclarations((Element) parent, childPosition, ModelQueryAction.INSERT);
            }
            Iterator nodeIterator = cmnodes.iterator();
            if (!nodeIterator.hasNext()) {
                if (getCMElementDeclaration(parent) != null) {
                    error = NLS.bind(XMLUIMessages._Has_no_available_child, (new Object[] { parent.getNodeName() }));
                } else {
                    error = NLS.bind(XMLUIMessages.Element__is_unknown, (new Object[] { parent.getNodeName() }));
                }
            }
            String matchString = contentAssistRequest.getMatchString();
            // matchstring
            while ((matchString.length() > 0) && (Character.isWhitespace(matchString.charAt(0)) || beginsWith(matchString, "<"))) {
                // $NON-NLS-1$
                matchString = matchString.substring(1);
            }
            while (nodeIterator.hasNext()) {
                Object o = nodeIterator.next();
                if (o instanceof CMElementDeclaration) {
                    CMElementDeclaration elementDecl = (CMElementDeclaration) o;
                    // only add proposals for the child element's that
                    // begin with the matchstring
                    String tagname = getRequiredName(parent, elementDecl);
                    boolean isStrictCMNodeSuggestion = strictCMNodeSuggestions != null ? strictCMNodeSuggestions.contains(elementDecl) : false;
                    Image image = CMImageUtil.getImage(elementDecl);
                    if (image == null) {
                        if (strictCMNodeSuggestions != null) {
                            image = isStrictCMNodeSuggestion ? XMLEditorPluginImageHelper.getInstance().getImage(XMLEditorPluginImages.IMG_OBJ_TAG_GENERIC_EMPHASIZED) : XMLEditorPluginImageHelper.getInstance().getImage(XMLEditorPluginImages.IMG_OBJ_TAG_GENERIC_DEEMPHASIZED);
                        } else {
                            image = XMLEditorPluginImageHelper.getInstance().getImage(XMLEditorPluginImages.IMG_OBJ_TAG_GENERIC);
                        }
                    }
                    // elementDecl);
                    if (beginsWith(tagname, matchString)) {
                        String proposedText = getRequiredText(parent, elementDecl);
                        // https://bugs.eclipse.org/bugs/show_bug.cgi?id=89811
                        // place cursor in first empty quotes
                        int markupAdjustment = getCursorPositionForProposedText(proposedText);
                        String proposedInfo = getAdditionalInfo(parentDecl, elementDecl);
                        int relevance = isStrictCMNodeSuggestion ? XMLRelevanceConstants.R_STRICTLY_VALID_TAG_INSERTION : XMLRelevanceConstants.R_TAG_INSERTION;
                        CustomCompletionProposal proposal = new CustomCompletionProposal(proposedText, contentAssistRequest.getReplacementBeginPosition(), contentAssistRequest.getReplacementLength(), markupAdjustment, image, tagname, null, proposedInfo, relevance);
                        contentAssistRequest.addProposal(proposal);
                    }
                }
            }
            if (contentAssistRequest.getProposals().size() == 0) {
                if (error != null) {
                    setErrorMessage(error);
                } else if ((contentAssistRequest.getMatchString() != null) && (contentAssistRequest.getMatchString().length() > 0)) {
                    setErrorMessage(NLS.bind(XMLUIMessages.No_known_child_tag, (new Object[] { parent.getNodeName(), contentAssistRequest.getMatchString() })));
                // $NON-NLS-1$ = "No known child tag names of <{0}> begin with \"{1}\"."
                } else {
                    setErrorMessage(NLS.bind(XMLUIMessages.__Has_no_known_child, (new Object[] { parent.getNodeName() })));
                }
            }
        }
    } else if (parent.getNodeType() == Node.DOCUMENT_NODE) {
        // Can only prompt with elements if the cursor position is past
        // the XML processing
        // instruction and DOCTYPE declaration
        boolean xmlpiFound = false;
        boolean doctypeFound = false;
        int minimumOffset = -1;
        for (Node child = parent.getFirstChild(); child != null; child = child.getNextSibling()) {
            // $NON-NLS-1$
            boolean xmlpi = ((child.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) && child.getNodeName().equals("xml"));
            boolean doctype = child.getNodeType() == Node.DOCUMENT_TYPE_NODE;
            if (xmlpi || (doctype && (minimumOffset < 0))) {
                minimumOffset = ((IDOMNode) child).getFirstStructuredDocumentRegion().getStartOffset() + ((IDOMNode) child).getFirstStructuredDocumentRegion().getTextLength();
            }
            xmlpiFound = xmlpiFound || xmlpi;
            doctypeFound = doctypeFound || doctype;
        }
        if (contentAssistRequest.getReplacementBeginPosition() >= minimumOffset) {
            List childDecls = getAvailableRootChildren((Document) parent, childPosition);
            for (int i = 0; i < childDecls.size(); i++) {
                CMElementDeclaration ed = (CMElementDeclaration) childDecls.get(i);
                if (ed != null) {
                    Image image = CMImageUtil.getImage(ed);
                    if (image == null) {
                        image = XMLEditorPluginImageHelper.getInstance().getImage(XMLEditorPluginImages.IMG_OBJ_TAG_GENERIC);
                    }
                    String proposedText = getRequiredText(parent, ed);
                    String tagname = getRequiredName(parent, ed);
                    // account for the &lt; and &gt;
                    int markupAdjustment = getContentGenerator().getMinimalStartTagLength(parent, ed);
                    String proposedInfo = getAdditionalInfo(null, ed);
                    CustomCompletionProposal proposal = new CustomCompletionProposal(proposedText, contentAssistRequest.getReplacementBeginPosition(), contentAssistRequest.getReplacementLength(), markupAdjustment, image, tagname, null, proposedInfo, XMLRelevanceConstants.R_TAG_INSERTION);
                    contentAssistRequest.addProposal(proposal);
                }
            }
        }
    }
}
Also used : CMDataType(org.eclipse.wst.xml.core.internal.contentmodel.CMDataType) IDOMNode(org.eclipse.wst.xml.core.internal.provisional.document.IDOMNode) CMNode(org.eclipse.wst.xml.core.internal.contentmodel.CMNode) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) IDOMElement(org.eclipse.wst.xml.core.internal.provisional.document.IDOMElement) CustomCompletionProposal(org.eclipse.wst.sse.ui.internal.contentassist.CustomCompletionProposal) IDOMDocument(org.eclipse.wst.xml.core.internal.provisional.document.IDOMDocument) Image(org.eclipse.swt.graphics.Image) Document(org.w3c.dom.Document) IDOMDocument(org.eclipse.wst.xml.core.internal.provisional.document.IDOMDocument) CMDocument(org.eclipse.wst.xml.core.internal.contentmodel.CMDocument) IStructuredDocument(org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument) CMElementDeclaration(org.eclipse.wst.xml.core.internal.contentmodel.CMElementDeclaration) IDOMNode(org.eclipse.wst.xml.core.internal.provisional.document.IDOMNode) Iterator(java.util.Iterator) CMNodeList(org.eclipse.wst.xml.core.internal.contentmodel.CMNodeList) List(java.util.List) ITextRegionList(org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionList) ArrayList(java.util.ArrayList) NodeList(org.w3c.dom.NodeList)

Example 10 with CustomCompletionProposal

use of org.eclipse.wst.sse.ui.internal.contentassist.CustomCompletionProposal in project webtools.sourceediting by eclipse.

the class AbstractContentAssistProcessor method addAttributeValueProposals.

protected void addAttributeValueProposals(ContentAssistRequest contentAssistRequest) {
    IDOMNode node = (IDOMNode) contentAssistRequest.getNode();
    // Find the attribute region and name for which this position should
    // have a value proposed
    IStructuredDocumentRegion open = node.getFirstStructuredDocumentRegion();
    ITextRegionList openRegions = open.getRegions();
    int i = openRegions.indexOf(contentAssistRequest.getRegion());
    if (i < 0) {
        return;
    }
    ITextRegion nameRegion = null;
    while (i >= 0) {
        nameRegion = openRegions.get(i--);
        if (nameRegion.getType() == DOMRegionContext.XML_TAG_ATTRIBUTE_NAME) {
            break;
        }
    }
    // the name region is REQUIRED to do anything useful
    if (nameRegion != null) {
        // Retrieve the declaration
        CMElementDeclaration elementDecl = getCMElementDeclaration(node);
        // String attributeName = nameRegion.getText();
        String attributeName = open.getText(nameRegion);
        CMAttributeDeclaration attrDecl = null;
        // declaration for the attribute otherwise
        if (elementDecl != null) {
            CMNamedNodeMap attributes = elementDecl.getAttributes();
            CMNamedNodeMapImpl allAttributes = new CMNamedNodeMapImpl(attributes) {

                private Map caseInsensitive;

                private Map getCaseInsensitiveMap() {
                    if (caseInsensitive == null)
                        caseInsensitive = new HashMap();
                    return caseInsensitive;
                }

                public CMNode getNamedItem(String name) {
                    CMNode node = super.getNamedItem(name);
                    if (node == null) {
                        node = (CMNode) getCaseInsensitiveMap().get(name.toLowerCase(Locale.US));
                    }
                    return node;
                }

                public void put(CMNode cmNode) {
                    super.put(cmNode);
                    getCaseInsensitiveMap().put(cmNode.getNodeName().toLowerCase(Locale.US), cmNode);
                }
            };
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                List nodes = ModelQueryUtil.getModelQuery(node.getOwnerDocument()).getAvailableContent((Element) node, elementDecl, ModelQuery.INCLUDE_ATTRIBUTES);
                for (int k = 0; k < nodes.size(); k++) {
                    CMNode cmnode = (CMNode) nodes.get(k);
                    if (cmnode.getNodeType() == CMNode.ATTRIBUTE_DECLARATION) {
                        allAttributes.put(cmnode);
                    }
                }
            }
            attributes = allAttributes;
            String noprefixName = DOMNamespaceHelper.getUnprefixedName(attributeName);
            if (attributes != null) {
                attrDecl = (CMAttributeDeclaration) attributes.getNamedItem(noprefixName);
                if (attrDecl == null) {
                    attrDecl = (CMAttributeDeclaration) attributes.getNamedItem(attributeName);
                }
            }
            if (attrDecl == null) {
                setErrorMessage(UNKNOWN_ATTR, attributeName);
            }
        }
        String currentValue = node.getAttributes().getNamedItem(attributeName).getNodeValue();
        String proposedInfo = null;
        Image image = CMImageUtil.getImage(attrDecl);
        if (image == null) {
            if ((attrDecl != null) && (attrDecl.getUsage() == CMAttributeDeclaration.REQUIRED)) {
                image = XMLEditorPluginImageHelper.getInstance().getImage(XMLEditorPluginImages.IMG_OBJ_ATT_REQ_OBJ);
            } else {
                image = XMLEditorPluginImageHelper.getInstance().getImage(XMLEditorPluginImages.IMG_OBJ_ATTRIBUTE);
            }
        }
        if ((attrDecl != null) && (attrDecl.getAttrType() != null)) {
            // attribute is known, prompt with values from the declaration
            proposedInfo = getAdditionalInfo(elementDecl, attrDecl);
            List possibleValues = getPossibleDataTypeValues(node, attrDecl);
            String defaultValue = attrDecl.getAttrType().getImpliedValue();
            if (possibleValues.size() > 0 || defaultValue != null) {
                // ENUMERATED VALUES
                String matchString = contentAssistRequest.getMatchString();
                if (matchString == null) {
                    // $NON-NLS-1$
                    matchString = "";
                }
                if ((matchString.length() > 0) && (matchString.startsWith("\"") || matchString.startsWith("'"))) {
                    matchString = matchString.substring(1);
                }
                boolean currentValid = false;
                // d210858, if the region's a container, don't suggest the
                // enumerated values as they probably won't help
                boolean existingComplicatedValue = (contentAssistRequest.getRegion() != null) && (contentAssistRequest.getRegion() instanceof ITextRegionContainer);
                if (!existingComplicatedValue) {
                    int rOffset = contentAssistRequest.getReplacementBeginPosition();
                    int rLength = contentAssistRequest.getReplacementLength();
                    for (Iterator j = possibleValues.iterator(); j.hasNext(); ) {
                        String possibleValue = (String) j.next();
                        if (!possibleValue.equals(defaultValue)) {
                            currentValid = currentValid || possibleValue.equals(currentValue);
                            if ((matchString.length() == 0) || possibleValue.startsWith(matchString)) {
                                // $NON-NLS-2$//$NON-NLS-1$
                                String rString = "\"" + possibleValue + "\"";
                                CustomCompletionProposal proposal = new CustomCompletionProposal(rString, rOffset, rLength, possibleValue.length() + 1, XMLEditorPluginImageHelper.getInstance().getImage(XMLEditorPluginImages.IMG_OBJ_ENUM), rString, null, proposedInfo, XMLRelevanceConstants.R_XML_ATTRIBUTE_VALUE);
                                contentAssistRequest.addProposal(proposal);
                            }
                        }
                    }
                    if (defaultValue != null && ((matchString.length() == 0) || defaultValue.startsWith(matchString))) {
                        // $NON-NLS-2$//$NON-NLS-1$
                        String rString = "\"" + defaultValue + "\"";
                        CustomCompletionProposal proposal = new CustomCompletionProposal(rString, rOffset, rLength, defaultValue.length() + 1, XMLEditorPluginImageHelper.getInstance().getImage(XMLEditorPluginImages.IMG_OBJ_DEFAULT), rString, null, proposedInfo, XMLRelevanceConstants.R_XML_ATTRIBUTE_VALUE);
                        contentAssistRequest.addProposal(proposal);
                    }
                }
            } else if (((attrDecl.getUsage() == CMAttributeDeclaration.FIXED) || (attrDecl.getAttrType().getImpliedValueKind() == CMDataType.IMPLIED_VALUE_FIXED)) && (attrDecl.getAttrType().getImpliedValue() != null)) {
                // FIXED values
                String value = attrDecl.getAttrType().getImpliedValue();
                if ((value != null) && (value.length() > 0)) {
                    // $NON-NLS-2$//$NON-NLS-1$
                    String rValue = "\"" + value + "\"";
                    CustomCompletionProposal proposal = new CustomCompletionProposal(rValue, contentAssistRequest.getReplacementBeginPosition(), contentAssistRequest.getReplacementLength(), rValue.length() + 1, image, rValue, null, proposedInfo, XMLRelevanceConstants.R_XML_ATTRIBUTE_VALUE);
                    contentAssistRequest.addProposal(proposal);
                    if ((currentValue.length() > 0) && !value.equals(currentValue)) {
                        // $NON-NLS-2$//$NON-NLS-1$
                        rValue = "\"" + currentValue + "\"";
                        proposal = new CustomCompletionProposal(rValue, contentAssistRequest.getReplacementBeginPosition(), contentAssistRequest.getReplacementLength(), rValue.length() + 1, image, rValue, null, proposedInfo, XMLRelevanceConstants.R_XML_ATTRIBUTE_VALUE);
                        contentAssistRequest.addProposal(proposal);
                    }
                }
            }
        } else {
            // unknown attribute, so supply nice empty values
            proposedInfo = getAdditionalInfo(null, elementDecl);
            CustomCompletionProposal proposal = null;
            if ((currentValue != null) && (currentValue.length() > 0)) {
                // $NON-NLS-2$//$NON-NLS-1$
                String rValue = "\"" + currentValue + "\"";
                proposal = new CustomCompletionProposal(rValue, contentAssistRequest.getReplacementBeginPosition(), contentAssistRequest.getReplacementLength(), 1, image, rValue, null, proposedInfo, XMLRelevanceConstants.R_XML_ATTRIBUTE_VALUE);
                contentAssistRequest.addProposal(proposal);
            }
        }
    } else {
        setErrorMessage(UNKNOWN_CONTEXT);
    }
}
Also used : CMNamedNodeMapImpl(org.eclipse.wst.xml.core.internal.contentmodel.basic.CMNamedNodeMapImpl) IStructuredDocumentRegion(org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion) HashMap(java.util.HashMap) CustomCompletionProposal(org.eclipse.wst.sse.ui.internal.contentassist.CustomCompletionProposal) ITextRegionContainer(org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionContainer) Image(org.eclipse.swt.graphics.Image) ITextRegionList(org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionList) CMElementDeclaration(org.eclipse.wst.xml.core.internal.contentmodel.CMElementDeclaration) IDOMNode(org.eclipse.wst.xml.core.internal.provisional.document.IDOMNode) ITextRegion(org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion) Iterator(java.util.Iterator) CMAttributeDeclaration(org.eclipse.wst.xml.core.internal.contentmodel.CMAttributeDeclaration) CMNode(org.eclipse.wst.xml.core.internal.contentmodel.CMNode) CMNodeList(org.eclipse.wst.xml.core.internal.contentmodel.CMNodeList) List(java.util.List) ITextRegionList(org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionList) ArrayList(java.util.ArrayList) NodeList(org.w3c.dom.NodeList) CMNamedNodeMap(org.eclipse.wst.xml.core.internal.contentmodel.CMNamedNodeMap) Map(java.util.Map) CMNamedNodeMap(org.eclipse.wst.xml.core.internal.contentmodel.CMNamedNodeMap) HashMap(java.util.HashMap) NamedNodeMap(org.w3c.dom.NamedNodeMap)

Aggregations

CustomCompletionProposal (org.eclipse.wst.sse.ui.internal.contentassist.CustomCompletionProposal)48 IDOMNode (org.eclipse.wst.xml.core.internal.provisional.document.IDOMNode)22 Image (org.eclipse.swt.graphics.Image)20 IStructuredDocumentRegion (org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion)17 CMElementDeclaration (org.eclipse.wst.xml.core.internal.contentmodel.CMElementDeclaration)17 CMNode (org.eclipse.wst.xml.core.internal.contentmodel.CMNode)14 ArrayList (java.util.ArrayList)13 Iterator (java.util.Iterator)13 ITextRegionList (org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionList)13 List (java.util.List)12 ICompletionProposal (org.eclipse.jface.text.contentassist.ICompletionProposal)12 ITextRegion (org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion)12 Node (org.w3c.dom.Node)11 IStructuredDocument (org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument)9 CMDocument (org.eclipse.wst.xml.core.internal.contentmodel.CMDocument)9 NodeList (org.w3c.dom.NodeList)8 Document (org.w3c.dom.Document)7 Element (org.w3c.dom.Element)7 ITextRegionContainer (org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionContainer)6 IDOMDocument (org.eclipse.wst.xml.core.internal.provisional.document.IDOMDocument)6