Search in sources :

Example 61 with XmlAttribute

use of com.intellij.psi.xml.XmlAttribute in project android by JetBrains.

the class LayoutPsiPullParserTest method compareParsers.

private void compareParsers(PsiFile file, NextEventType nextEventType) throws Exception {
    assertTrue(file instanceof XmlFile);
    XmlFile xmlFile = (XmlFile) file;
    KXmlParser referenceParser = createReferenceParser(file);
    LayoutPsiPullParser parser = LayoutPsiPullParser.create(xmlFile, new RenderLogger("test", myModule));
    assertEquals("Expected " + name(referenceParser.getEventType()) + " but was " + name(parser.getEventType()) + " (at line:column " + describePosition(referenceParser) + ")", referenceParser.getEventType(), parser.getEventType());
    while (true) {
        int expected, next;
        switch(nextEventType) {
            case NEXT:
                expected = referenceParser.next();
                next = parser.next();
                break;
            case NEXT_TOKEN:
                expected = referenceParser.nextToken();
                next = parser.nextToken();
                break;
            case NEXT_TAG:
                {
                    try {
                        expected = referenceParser.nextTag();
                    } catch (Exception e) {
                        expected = referenceParser.getEventType();
                    }
                    try {
                        next = parser.nextTag();
                    } catch (Exception e) {
                        next = parser.getEventType();
                    }
                    break;
                }
            default:
                throw new AssertionError("Unexpected type");
        }
        PsiElement element = null;
        if (expected == START_TAG) {
            assertNotNull(parser.getViewCookie());
            assertTrue(parser.getViewCookie() instanceof TagSnapshot);
            element = ((TagSnapshot) parser.getViewCookie()).tag;
        }
        if (expected == START_TAG) {
            assertEquals(referenceParser.getName(), parser.getName());
            if (element != xmlFile.getRootTag()) {
                // KXmlParser seems to not include xmlns: attributes on the root tag!{
                SortedSet<String> referenceAttributes = new TreeSet<>();
                SortedSet<String> attributes = new TreeSet<>();
                for (int i = 0; i < referenceParser.getAttributeCount(); i++) {
                    String s = referenceParser.getAttributePrefix(i) + ':' + referenceParser.getAttributeName(i) + '=' + referenceParser.getAttributeValue(i);
                    referenceAttributes.add(s);
                }
                for (int i = 0; i < parser.getAttributeCount(); i++) {
                    String s = parser.getAttributePrefix(i) + ':' + parser.getAttributeName(i) + '=' + parser.getAttributeValue(i);
                    attributes.add(s);
                    if (parser.getAttributeNamespace(i) != null) {
                        //noinspection ConstantConditions
                        assertEquals(normalizeValue(parser.getAttributeValue(i)), normalizeValue(parser.getAttributeValue(parser.getAttributeNamespace(i), parser.getAttributeName(i))));
                    }
                }
                assertEquals(referenceAttributes, attributes);
            }
            if (element instanceof XmlTag) {
                XmlTag tag = (XmlTag) element;
                for (XmlAttribute attribute : tag.getAttributes()) {
                    String namespace = attribute.getNamespace();
                    String name = attribute.getLocalName();
                    if (namespace.isEmpty()) {
                        String prefix = attribute.getNamespacePrefix();
                        if (!prefix.isEmpty()) {
                            name = prefix + ":" + prefix;
                        }
                    }
                    //noinspection ConstantConditions
                    assertEquals(namespace + ':' + name + " in element " + parser.getName(), normalizeValue(referenceParser.getAttributeValue(namespace, name)), normalizeValue(parser.getAttributeValue(namespace, name)));
                }
            }
        } else if (expected == XmlPullParser.TEXT || expected == XmlPullParser.COMMENT) {
            assertEquals(StringUtil.notNullize(referenceParser.getText()).trim(), StringUtil.notNullize(parser.getText()).trim());
        }
        if (expected != next) {
            assertEquals("Expected " + name(expected) + " but was " + name(next) + "(At " + describePosition(referenceParser) + ")", expected, next);
        }
        if (expected == XmlPullParser.END_DOCUMENT) {
            break;
        }
    }
}
Also used : XmlAttribute(com.intellij.psi.xml.XmlAttribute) XmlFile(com.intellij.psi.xml.XmlFile) XmlPullParserException(org.xmlpull.v1.XmlPullParserException) KXmlParser(org.kxml2.io.KXmlParser) TreeSet(java.util.TreeSet) PsiElement(com.intellij.psi.PsiElement) XmlTag(com.intellij.psi.xml.XmlTag)

Example 62 with XmlAttribute

use of com.intellij.psi.xml.XmlAttribute in project android by JetBrains.

the class TagSnapshotTest method createAttribute.

private static XmlAttribute createAttribute(String namespace, String prefix, String localName, String value) {
    XmlAttribute attribute = mock(XmlAttribute.class);
    when(attribute.getLocalName()).thenReturn(localName);
    when(attribute.getNamespace()).thenReturn(namespace);
    when(attribute.getNamespacePrefix()).thenReturn(prefix);
    when(attribute.getValue()).thenReturn(value);
    return attribute;
}
Also used : XmlAttribute(com.intellij.psi.xml.XmlAttribute)

Example 63 with XmlAttribute

use of com.intellij.psi.xml.XmlAttribute in project android by JetBrains.

the class NlIdPropertyItem method setValue.

@Override
public void setValue(Object value) {
    String newId = value != null ? stripIdPrefix(value.toString()) : "";
    String oldId = getValue();
    XmlTag tag = getTag();
    if (ourRefactoringChoice != REFACTOR_NO && oldId != null && !oldId.isEmpty() && !newId.isEmpty() && !oldId.equals(newId) && tag != null && tag.isValid()) {
        // Offer rename refactoring?
        XmlAttribute attribute = tag.getAttribute(SdkConstants.ATTR_ID, SdkConstants.ANDROID_URI);
        if (attribute != null) {
            Module module = getModel().getModule();
            Project project = module.getProject();
            XmlAttributeValue valueElement = attribute.getValueElement();
            if (valueElement != null && valueElement.isValid()) {
                // Exact replace only, no comment/text occurrence changes since it is non-interactive
                ValueResourceElementWrapper wrapper = new ValueResourceElementWrapper(valueElement);
                RenameProcessor processor = new RenameProcessor(project, wrapper, NEW_ID_PREFIX + newId, false, /*comments*/
                false);
                processor.setPreviewUsages(false);
                // Do a quick usage search to see if we need to ask about renaming
                UsageInfo[] usages = processor.findUsages();
                if (usages.length > 0) {
                    int choice = ourRefactoringChoice;
                    if (choice == REFACTOR_ASK) {
                        DialogBuilder builder = createDialogBuilder(project);
                        builder.setTitle("Update Usages?");
                        // UGH!
                        JPanel panel = new JPanel(new BorderLayout());
                        JLabel label = new JLabel("<html>" + "Update usages as well?<br>" + "This will update all XML references and Java R field references.<br>" + "<br>" + "</html>");
                        panel.add(label, BorderLayout.CENTER);
                        JBCheckBox checkBox = new JBCheckBox("Don't ask again during this session");
                        panel.add(checkBox, BorderLayout.SOUTH);
                        builder.setCenterPanel(panel);
                        builder.setDimensionServiceKey("idPropertyDimension");
                        builder.removeAllActions();
                        DialogBuilder.CustomizableAction yesAction = builder.addOkAction();
                        yesAction.setText(Messages.YES_BUTTON);
                        builder.addActionDescriptor(dialogWrapper -> new AbstractAction(Messages.NO_BUTTON) {

                            @Override
                            public void actionPerformed(ActionEvent actionEvent) {
                                dialogWrapper.close(DialogWrapper.NEXT_USER_EXIT_CODE);
                            }
                        });
                        builder.addCancelAction();
                        int exitCode = builder.show();
                        choice = exitCode == DialogWrapper.OK_EXIT_CODE ? REFACTOR_YES : exitCode == DialogWrapper.NEXT_USER_EXIT_CODE ? REFACTOR_NO : ourRefactoringChoice;
                        //noinspection AssignmentToStaticFieldFromInstanceMethod
                        ourRefactoringChoice = checkBox.isSelected() ? choice : REFACTOR_ASK;
                        if (exitCode == DialogWrapper.CANCEL_EXIT_CODE) {
                            return;
                        }
                    }
                    if (choice == REFACTOR_YES) {
                        processor.run();
                        return;
                    }
                }
            }
        }
    }
    super.setValue(!StringUtil.isEmpty(newId) ? NEW_ID_PREFIX + newId : null);
}
Also used : XmlAttribute(com.intellij.psi.xml.XmlAttribute) RenameProcessor(com.intellij.refactoring.rename.RenameProcessor) ActionEvent(java.awt.event.ActionEvent) XmlAttributeValue(com.intellij.psi.xml.XmlAttributeValue) JBCheckBox(com.intellij.ui.components.JBCheckBox) Project(com.intellij.openapi.project.Project) Module(com.intellij.openapi.module.Module) DialogBuilder(com.intellij.openapi.ui.DialogBuilder) UsageInfo(com.intellij.usageView.UsageInfo) XmlTag(com.intellij.psi.xml.XmlTag) ValueResourceElementWrapper(org.jetbrains.android.dom.wrappers.ValueResourceElementWrapper)

Example 64 with XmlAttribute

use of com.intellij.psi.xml.XmlAttribute in project intellij-plugins by JetBrains.

the class AngularAttributeIndexer method map.

@NotNull
@Override
public Map<String, AngularNamedItemDefinition> map(@NotNull FileContent inputData) {
    final Map<String, AngularNamedItemDefinition> map = new HashMap<>();
    final PsiFile file = inputData.getPsiFile();
    if (file instanceof XmlFile) {
        file.accept(new XmlRecursiveElementWalkingVisitor() {

            @Override
            public void visitXmlAttribute(XmlAttribute attribute) {
                if (myAttributeName.equals(DirectiveUtil.normalizeAttributeName(attribute.getName()))) {
                    final XmlAttributeValue element = attribute.getValueElement();
                    if (element == null) {
                        map.put("", new AngularNamedItemDefinition("", attribute.getTextRange().getStartOffset()));
                    } else {
                        final String name = StringUtil.unquoteString(element.getText());
                        map.put(name, new AngularNamedItemDefinition(name, element.getTextRange().getStartOffset()));
                    }
                }
            }
        });
    }
    return map;
}
Also used : XmlAttribute(com.intellij.psi.xml.XmlAttribute) XmlFile(com.intellij.psi.xml.XmlFile) HashMap(java.util.HashMap) PsiFile(com.intellij.psi.PsiFile) XmlAttributeValue(com.intellij.psi.xml.XmlAttributeValue) XmlRecursiveElementWalkingVisitor(com.intellij.psi.XmlRecursiveElementWalkingVisitor) NotNull(org.jetbrains.annotations.NotNull)

Example 65 with XmlAttribute

use of com.intellij.psi.xml.XmlAttribute in project android by JetBrains.

the class AndroidXmlDocumentationProvider method getResourceDocumentation.

@Nullable
private static String getResourceDocumentation(PsiElement element, String value) {
    ResourceUrl url = ResourceUrl.parse(value);
    if (url != null) {
        return generateDoc(element, url);
    } else {
        XmlAttribute attribute = PsiTreeUtil.getParentOfType(element, XmlAttribute.class, false);
        XmlTag tag = null;
        // True if getting the documentation of the XML value (not the value of the name attribute)
        boolean isXmlValue = false;
        // get the XmlAttribute using the containing tag
        if (element instanceof XmlToken && XML_DATA_CHARACTERS.equals(((XmlToken) element).getTokenType())) {
            tag = PsiTreeUtil.getParentOfType(element, XmlTag.class);
            attribute = tag == null ? null : tag.getAttribute(ATTR_NAME);
            isXmlValue = true;
        }
        if (attribute == null) {
            return null;
        }
        if (ATTR_NAME.equals(attribute.getName())) {
            tag = tag != null ? tag : attribute.getParent();
            XmlTag parentTag = tag.getParentTag();
            if (parentTag == null) {
                return null;
            }
            if (TAG_RESOURCES.equals(parentTag.getName())) {
                // Handle ID definitions, http://developer.android.com/guide/topics/resources/more-resources.html#Id
                String typeName = tag.getName();
                if (TAG_ITEM.equals(typeName)) {
                    typeName = tag.getAttributeValue(ATTR_TYPE);
                }
                ResourceType type = ResourceType.getEnum(typeName);
                if (type != null) {
                    return generateDoc(element, type, value, false);
                }
            } else if (TAG_STYLE.equals(parentTag.getName())) {
                // String used to get attribute definitions
                String targetValue = value;
                if (isXmlValue && attribute.getValue() != null) {
                    // In this case, the target is the name attribute of the <item> tag, which contains the key of the attr enum
                    targetValue = attribute.getValue();
                }
                if (targetValue.startsWith(ANDROID_NS_NAME_PREFIX)) {
                    targetValue = targetValue.substring(ANDROID_NS_NAME_PREFIX.length());
                }
                // Handle style item definitions, http://developer.android.com/guide/topics/resources/style-resource.html
                AttributeDefinition attributeDefinition = getAttributeDefinitionForElement(element, targetValue);
                if (attributeDefinition == null) {
                    return null;
                }
                // Return the doc of the value if searching for an enum value, otherwise return the doc of the enum itself
                return StringUtil.trim(isXmlValue ? attributeDefinition.getValueDoc(value) : attributeDefinition.getDocValue(null));
            }
        }
        // Display documentation for enum values defined in attrs.xml file, if it's present
        if (ANDROID_URI.equals(attribute.getNamespace())) {
            AttributeDefinition attributeDefinition = getAttributeDefinitionForElement(element, attribute.getLocalName());
            if (attributeDefinition == null) {
                return null;
            }
            return StringUtil.trim(attributeDefinition.getValueDoc(value));
        }
    }
    return null;
}
Also used : XmlAttribute(com.intellij.psi.xml.XmlAttribute) AttributeDefinition(org.jetbrains.android.dom.attrs.AttributeDefinition) ResourceType(com.android.resources.ResourceType) ResourceUrl(com.android.ide.common.resources.ResourceUrl) XmlTag(com.intellij.psi.xml.XmlTag) XmlToken(com.intellij.psi.xml.XmlToken) Nullable(org.jetbrains.annotations.Nullable)

Aggregations

XmlAttribute (com.intellij.psi.xml.XmlAttribute)220 XmlTag (com.intellij.psi.xml.XmlTag)116 PsiElement (com.intellij.psi.PsiElement)60 XmlAttributeValue (com.intellij.psi.xml.XmlAttributeValue)57 NotNull (org.jetbrains.annotations.NotNull)44 XmlFile (com.intellij.psi.xml.XmlFile)37 Nullable (org.jetbrains.annotations.Nullable)27 Project (com.intellij.openapi.project.Project)25 VirtualFile (com.intellij.openapi.vfs.VirtualFile)20 TextRange (com.intellij.openapi.util.TextRange)18 XmlAttributeDescriptor (com.intellij.xml.XmlAttributeDescriptor)18 ArrayList (java.util.ArrayList)18 PsiFile (com.intellij.psi.PsiFile)17 PsiReference (com.intellij.psi.PsiReference)17 IncorrectOperationException (com.intellij.util.IncorrectOperationException)10 DomElement (com.intellij.util.xml.DomElement)10 Result (com.intellij.openapi.application.Result)9 XmlElementDescriptor (com.intellij.xml.XmlElementDescriptor)9 WriteCommandAction (com.intellij.openapi.command.WriteCommandAction)8 XmlElement (com.intellij.psi.xml.XmlElement)6