Search in sources :

Example 21 with LocalQuickFix

use of com.intellij.codeInspection.LocalQuickFix in project android by JetBrains.

the class ExternalAnnotationsSupport method checkAnnotationsJarAttached.

// Based on similar code in MagicConstantInspection
@SuppressWarnings("ALL")
private static void checkAnnotationsJarAttached(@NotNull PsiFile file, @NotNull ProblemsHolder holder) {
    // Not yet used
    if (false) {
        final Project project = file.getProject();
        PsiClass actionBar = JavaPsiFacade.getInstance(project).findClass("android.app.ActionBar", GlobalSearchScope.allScope(project));
        if (actionBar == null) {
            // no sdk to attach
            return;
        }
        PsiMethod[] methods = actionBar.findMethodsByName("getNavigationMode", false);
        if (methods.length != 1) {
            // no sdk to attach
            return;
        }
        PsiMethod getModifiers = methods[0];
        ExternalAnnotationsManager annotationsManager = ExternalAnnotationsManager.getInstance(project);
        PsiAnnotation annotation = annotationsManager.findExternalAnnotation(getModifiers, MagicConstant.class.getName());
        if (annotation != null) {
            return;
        }
        final VirtualFile virtualFile = PsiUtilCore.getVirtualFile(getModifiers);
        if (virtualFile == null) {
            // no sdk to attach
            return;
        }
        final List<OrderEntry> entries = ProjectRootManager.getInstance(project).getFileIndex().getOrderEntriesForFile(virtualFile);
        Sdk sdk = null;
        for (OrderEntry orderEntry : entries) {
            if (orderEntry instanceof JdkOrderEntry) {
                sdk = ((JdkOrderEntry) orderEntry).getJdk();
                if (sdk != null) {
                    break;
                }
            }
        }
        if (sdk == null) {
            // no sdk to attach
            return;
        }
        final Sdk finalSdk = sdk;
        String path = finalSdk.getHomePath();
        String text = "No IDEA annotations attached to the Android SDK " + finalSdk.getName() + (path == null ? "" : " (" + FileUtil.toSystemDependentName(path) + ")") + ", some issues will not be found";
        holder.registerProblem(file, text, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, new LocalQuickFix() {

            @NotNull
            @Override
            public String getName() {
                return "Attach annotations";
            }

            @NotNull
            @Override
            public String getFamilyName() {
                return getName();
            }

            @Override
            public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
                ApplicationManager.getApplication().runWriteAction(new Runnable() {

                    @Override
                    public void run() {
                        SdkModificator modifier = finalSdk.getSdkModificator();
                        attachJdkAnnotations(modifier);
                        modifier.commitChanges();
                    }
                });
            }
        });
    }
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) MagicConstant(org.intellij.lang.annotations.MagicConstant) ProblemDescriptor(com.intellij.codeInspection.ProblemDescriptor) LocalQuickFix(com.intellij.codeInspection.LocalQuickFix) SdkModificator(com.intellij.openapi.projectRoots.SdkModificator) NotNull(org.jetbrains.annotations.NotNull) Project(com.intellij.openapi.project.Project) Sdk(com.intellij.openapi.projectRoots.Sdk) ExternalAnnotationsManager(com.intellij.codeInsight.ExternalAnnotationsManager)

Example 22 with LocalQuickFix

use of com.intellij.codeInspection.LocalQuickFix in project intellij-plugins by JetBrains.

the class CfmlFileReferenceInspection method buildVisitor.

@NotNull
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, final boolean isOnTheFly) {
    return new PsiElementVisitor() {

        public void visitElement(final PsiElement element) {
            PsiElement tagParent = PsiTreeUtil.getParentOfType((element), CfmlTag.class);
            if ((element.getNode().getElementType() == CfmlTokenTypes.STRING_TEXT)) {
                if ((tagParent == null || (!((CfmlTag) tagParent).getTagName().equalsIgnoreCase("cfinclude") && !((CfmlTag) tagParent).getTagName().equalsIgnoreCase("cfmodule")))) {
                    PsiElement superParent = element.getParent() != null ? element.getParent().getParent() : null;
                    ASTNode superParentNode = superParent != null ? superParent.getNode() : null;
                    if ((superParentNode == null || superParentNode.getElementType() != CfmlElementTypes.INCLUDEEXPRESSION)) {
                        return;
                    }
                }
                final PsiReference[] refs = element.getParent().getReferences();
                for (int i = 0, refsLength = refs.length; i < refsLength; i++) {
                    PsiReference ref = refs[i];
                    if (!(ref instanceof FileReference))
                        continue;
                    if (ref.resolve() == null) {
                        PsiDirectory dir;
                        if (i > 0) {
                            final PsiElement target = refs[i - 1].resolve();
                            dir = target instanceof PsiDirectory ? (PsiDirectory) target : null;
                        } else {
                            dir = element.getContainingFile().getParent();
                        }
                        holder.registerProblem(ref.getElement(), ref.getRangeInElement(), isOnTheFly ? "Path '" + ref.getCanonicalText() + "' not found" : "Path not found", isOnTheFly && dir != null ? new LocalQuickFix[] { new CreateFileFix(i < refs.length - 1, ref.getCanonicalText(), dir) } : LocalQuickFix.EMPTY_ARRAY);
                        //                       ProblemHighlightType.ERROR);
                        break;
                    }
                }
            }
        }
    };
}
Also used : CreateFileFix(com.intellij.codeInsight.daemon.quickFix.CreateFileFix) PsiDirectory(com.intellij.psi.PsiDirectory) ASTNode(com.intellij.lang.ASTNode) PsiReference(com.intellij.psi.PsiReference) LocalQuickFix(com.intellij.codeInspection.LocalQuickFix) CfmlTag(com.intellij.coldFusion.model.psi.CfmlTag) PsiElementVisitor(com.intellij.psi.PsiElementVisitor) FileReference(com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReference) PsiElement(com.intellij.psi.PsiElement) NotNull(org.jetbrains.annotations.NotNull)

Example 23 with LocalQuickFix

use of com.intellij.codeInspection.LocalQuickFix in project intellij-plugins by JetBrains.

the class MxmlReferenceContributor method registerReferenceProviders.

@Override
public void registerReferenceProviders(@NotNull final PsiReferenceRegistrar registrar) {
    registrar.registerReferenceProvider(XmlPatterns.xmlAttributeValue().withLocalName(or(string().endsWith(STYLE_NAME_ATTR_SUFFIX), string().equalTo(STYLE_NAME_ATTR))).and(new FilterPattern(new ElementFilter() {

        public boolean isAcceptable(final Object element, final PsiElement context) {
            return !((PsiElement) element).textContains('{');
        }

        public boolean isClassAcceptable(final Class hintClass) {
            return true;
        }
    })), CssReferenceProviderUtil.CSS_CLASS_OR_ID_KEY_PROVIDER.getProvider());
    XmlUtil.registerXmlAttributeValueReferenceProvider(registrar, null, new ElementFilter() {

        @Override
        public boolean isAcceptable(Object element, PsiElement context) {
            PsiElement parent = ((PsiElement) element).getParent();
            if (parent instanceof XmlAttribute) {
                XmlAttributeDescriptor descriptor = ((XmlAttribute) parent).getDescriptor();
                if (descriptor instanceof AnnotationBackedDescriptorImpl) {
                    String format = ((AnnotationBackedDescriptor) descriptor).getFormat();
                    return FlexCssPropertyDescriptor.COLOR_FORMAT.equals(format);
                }
            }
            return false;
        }

        @Override
        public boolean isClassAcceptable(Class hintClass) {
            return true;
        }
    }, true, new PsiReferenceProvider() {

        @NotNull
        @Override
        public PsiReference[] getReferencesByElement(@NotNull final PsiElement element, @NotNull ProcessingContext context) {
            XmlAttributeValue value = (XmlAttributeValue) element;
            XmlAttribute parent = (XmlAttribute) value.getParent();
            int length = value.getTextLength();
            if (length >= 2) {
                AnnotationBackedDescriptor descriptor = (AnnotationBackedDescriptor) parent.getDescriptor();
                assert descriptor != null;
                if (JSCommonTypeNames.ARRAY_CLASS_NAME.equals(descriptor.getType())) {
                    // drop quotes
                    String text = element.getText().substring(1, length - 1);
                    final List<PsiReference> references = new ArrayList<>();
                    new ArrayAttributeValueProcessor() {

                        @Override
                        protected void processElement(int start, int end) {
                            references.add(new FlexColorReference(element, new TextRange(start + 1, end + 1)));
                        }
                    }.process(text);
                    return references.toArray(new PsiReference[references.size()]);
                } else {
                    // inside quotes
                    return new PsiReference[] { new FlexColorReference(element, new TextRange(1, length - 1)) };
                }
            }
            return PsiReference.EMPTY_ARRAY;
        }
    });
    XmlUtil.registerXmlAttributeValueReferenceProvider(registrar, null, new ElementFilter() {

        public boolean isAcceptable(final Object element, final PsiElement context) {
            PsiElement parent = ((PsiElement) element).getParent();
            if (!(parent instanceof XmlAttribute) || !((XmlAttribute) parent).isNamespaceDeclaration()) {
                return false;
            }
            final PsiElement parentParent = parent.getParent();
            if (parentParent instanceof XmlTag && MxmlJSClass.isInsideTagThatAllowsAnyXmlContent((XmlTag) parentParent)) {
                return false;
            }
            return true;
        }

        public boolean isClassAcceptable(final Class hintClass) {
            return true;
        }
    }, true, new PsiReferenceProvider() {

        @NotNull
        public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) {
            final String trimmedText = StringUtil.unquoteString(element.getText());
            if (CodeContext.isPackageBackedNamespace(trimmedText)) {
                final JSReferenceSet referenceSet = new JSReferenceSet(element, trimmedText, 1, false, false) {

                    @Override
                    protected JSTextReference createTextReference(String s, int offset, boolean methodRef) {
                        return new JSTextReference(this, s, offset, methodRef) {

                            @Override
                            protected ResolveResult[] doResolve(@NotNull PsiFile psiFile) {
                                if ("*".equals(getCanonicalText())) {
                                    return new ResolveResult[] { new JSResolveResult(mySet.getElement()) };
                                }
                                return super.doResolve(psiFile);
                            }

                            @Override
                            protected MyResolveProcessor createResolveProcessor(String name, PsiElement place, ResultSink resultSink) {
                                return new MyResolveProcessor(name, place, resultSink) {

                                    @Override
                                    public boolean execute(@NotNull PsiElement element, @NotNull ResolveState state) {
                                        if (!(element instanceof JSPackageWrapper))
                                            return true;
                                        return super.execute(element, state);
                                    }
                                };
                            }
                        };
                    }
                };
                return referenceSet.getReferences();
            } else {
                return PsiReference.EMPTY_ARRAY;
            }
        }
    });
    // source attribute of Binding tag is handled in JSLanguageInjector
    XmlUtil.registerXmlAttributeValueReferenceProvider(registrar, new String[] { FlexReferenceContributor.DESTINATION_ATTR_NAME }, new ScopeFilter(new ParentElementFilter(new AndFilter(XmlTagFilter.INSTANCE, new TagNameFilter(BINDING_TAG_NAME), new NamespaceFilter(JavaScriptSupportLoader.LANGUAGE_NAMESPACES)), 2)), new PsiReferenceProvider() {

        @NotNull
        public PsiReference[] getReferencesByElement(@NotNull final PsiElement element, @NotNull final ProcessingContext context) {
            final String trimmedText = StringUtil.unquoteString(element.getText());
            final JSReferenceSet referenceSet = new JSReferenceSet(element, trimmedText, 1, false);
            return referenceSet.getReferences();
        }
    });
    XmlUtil.registerXmlAttributeValueReferenceProvider(registrar, new String[] { FlexReferenceContributor.SOURCE_ATTR_NAME }, new ScopeFilter(new ParentElementFilter(new AndFilter(XmlTagFilter.INSTANCE, new ElementFilterBase<PsiElement>(PsiElement.class) {

        protected boolean isElementAcceptable(final PsiElement element, final PsiElement context) {
            return true;
        }
    }), 2)), new PsiReferenceProvider() {

        @NotNull
        public PsiReference[] getReferencesByElement(@NotNull final PsiElement element, @NotNull final ProcessingContext context) {
            final XmlAttribute attribute = (XmlAttribute) element.getParent();
            final XmlTag tag = attribute.getParent();
            final String tagName = tag.getLocalName();
            final String trimmedText = StringUtil.unquoteString(element.getText());
            if (JavaScriptSupportLoader.isLanguageNamespace(tag.getNamespace())) {
                if (FlexPredefinedTagNames.SCRIPT.equals(tagName)) {
                    return ReferenceSupport.getFileRefs(element, element, 1, ReferenceSupport.LookupOptions.SCRIPT_SOURCE);
                }
                final String[] tagsWithSourceAttr = { MxmlJSClass.XML_TAG_NAME, FlexPredefinedTagNames.MODEL, JSCommonTypeNames.STRING_CLASS_NAME, JSCommonTypeNames.BOOLEAN_CLASS_NAME, JSCommonTypeNames.INT_TYPE_NAME, JSCommonTypeNames.UINT_TYPE_NAME, JSCommonTypeNames.NUMBER_CLASS_NAME };
                if (ArrayUtil.contains(tagName, tagsWithSourceAttr)) {
                    return ReferenceSupport.getFileRefs(element, element, 1, ReferenceSupport.LookupOptions.XML_AND_MODEL_SOURCE);
                }
                if (FlexPredefinedTagNames.STYLE.equals(tagName)) {
                    if (trimmedText.startsWith("http:")) {
                        return PsiReference.EMPTY_ARRAY;
                    } else {
                        return ReferenceSupport.getFileRefs(element, element, 1, ReferenceSupport.LookupOptions.STYLE_SOURCE);
                    }
                }
            }
            if (element.textContains('{') || element.textContains('@')) {
                return PsiReference.EMPTY_ARRAY;
            }
            final XmlAttributeDescriptor descriptor = attribute.getDescriptor();
            final PsiElement psiElement = descriptor == null ? null : descriptor.getDeclaration();
            if (psiElement instanceof JSFunction) {
                final JSAttribute inspectableAttr = AnnotationBackedDescriptorImpl.findInspectableAttr(psiElement);
                if (inspectableAttr != null) {
                    final JSAttributeNameValuePair attributeNameValuePair = inspectableAttr.getValueByName(FORMAT_ATTR_NAME);
                    if (attributeNameValuePair != null && FILE_ATTR_VALUE.equals(attributeNameValuePair.getSimpleValue())) {
                        return ReferenceSupport.getFileRefs(element, element, 1, ReferenceSupport.LookupOptions.NON_EMBEDDED_ASSET);
                    }
                }
            }
            return PsiReference.EMPTY_ARRAY;
        }
    });
    final Function<PsiReference, LocalQuickFix[]> quickFixProvider = reference -> {
        final PsiElement element = reference.getElement();
        final String classFqn = getTrimmedValueAndRange((XmlElement) element).first;
        final String tagOrAttrName = element instanceof XmlAttributeValue ? ((XmlAttribute) element.getParent()).getName() : ((XmlTag) element).getLocalName();
        final CreateClassIntentionWithCallback[] intentions;
        if (SKIN_CLASS_ATTR_NAME.equals(tagOrAttrName)) {
            intentions = new CreateClassIntentionWithCallback[] { new CreateFlexSkinIntention(classFqn, element) };
        } else if ("firstView".equals(tagOrAttrName)) {
            intentions = new CreateClassIntentionWithCallback[] { new CreateFlexMobileViewIntentionAndFix(classFqn, element, false) };
        } else {
            intentions = new CreateClassIntentionWithCallback[] { new ActionScriptCreateClassOrInterfaceFix(classFqn, null, element), new CreateFlexComponentFix(classFqn, element) };
        }
        for (CreateClassIntentionWithCallback intention : intentions) {
            intention.setCreatedClassFqnConsumer(fqn -> {
                if (!element.isValid())
                    return;
                if (element instanceof XmlAttributeValue) {
                    ((XmlAttribute) element.getParent()).setValue(fqn);
                } else {
                    ((XmlTag) element).getValue().setText(fqn);
                }
            });
        }
        return intentions;
    };
    XmlUtil.registerXmlTagReferenceProvider(registrar, null, TrueFilter.INSTANCE, true, createReferenceProviderForTagOrAttributeExpectingJSClass(quickFixProvider));
    XmlUtil.registerXmlAttributeValueReferenceProvider(registrar, null, TrueFilter.INSTANCE, createReferenceProviderForTagOrAttributeExpectingJSClass(quickFixProvider));
    registrar.registerReferenceProvider(xmlAttribute().withParent(XmlTag.class).with(new PatternCondition<XmlAttribute>("") {

        @Override
        public boolean accepts(@NotNull XmlAttribute xmlAttribute, ProcessingContext context) {
            String attrName = xmlAttribute.getLocalName();
            int dotPos = attrName.indexOf('.');
            if (dotPos == -1)
                return false;
            return JavaScriptSupportLoader.isFlexMxmFile(xmlAttribute.getContainingFile());
        }
    }), new PsiReferenceProvider() {

        @NotNull
        public PsiReference[] getReferencesByElement(@NotNull final PsiElement element, @NotNull final ProcessingContext context) {
            String attrName = ((XmlAttribute) element).getLocalName();
            int dotPos = attrName.indexOf('.');
            if (dotPos == -1)
                return PsiReference.EMPTY_ARRAY;
            return new PsiReference[] { new FlexReferenceContributor.StateReference(element, new TextRange(dotPos + 1, attrName.length())) };
        }
    });
    XmlUtil.registerXmlTagReferenceProvider(registrar, null, new ElementFilterBase<XmlTag>(XmlTag.class) {

        protected boolean isElementAcceptable(final XmlTag element, final PsiElement context) {
            return element.getName().indexOf('.') != -1;
        }
    }, false, new PsiReferenceProvider() {

        @NotNull
        public PsiReference[] getReferencesByElement(@NotNull final PsiElement element, @NotNull final ProcessingContext context) {
            final String name = ((XmlTag) element).getName();
            int dotIndex = name.indexOf('.');
            if (dotIndex == -1)
                return PsiReference.EMPTY_ARRAY;
            final int tagOffset = element.getTextRange().getStartOffset();
            final XmlToken startTagElement = XmlTagUtil.getStartTagNameElement((XmlTag) element);
            final XmlToken endTagElement = XmlTagUtil.getEndTagNameElement((XmlTag) element);
            if (startTagElement != null) {
                if (endTagElement != null && endTagElement.getText().equals(startTagElement.getText())) {
                    final int start1 = startTagElement.getTextRange().getStartOffset() - tagOffset;
                    final int start2 = endTagElement.getTextRange().getStartOffset() - tagOffset;
                    return new PsiReference[] { new FlexReferenceContributor.StateReference(element, new TextRange(start1 + dotIndex + 1, startTagElement.getTextRange().getEndOffset() - tagOffset)), new FlexReferenceContributor.StateReference(element, new TextRange(start2 + dotIndex + 1, endTagElement.getTextRange().getEndOffset() - tagOffset)) };
                } else {
                    final int start = startTagElement.getTextRange().getStartOffset() - tagOffset;
                    return new PsiReference[] { new FlexReferenceContributor.StateReference(element, new TextRange(start + dotIndex + 1, startTagElement.getTextRange().getEndOffset() - tagOffset)) };
                }
            }
            return PsiReference.EMPTY_ARRAY;
        }
    });
    XmlUtil.registerXmlAttributeValueReferenceProvider(registrar, new String[] { "basedOn", "fromState", "toState", FlexStateElementNames.NAME, FlexStateElementNames.STATE_GROUPS }, new ScopeFilter(new ParentElementFilter(new AndFilter(XmlTagFilter.INSTANCE, new NamespaceFilter(MxmlJSClass.MXML_URIS)), 2)), new PsiReferenceProvider() {

        @NotNull
        public PsiReference[] getReferencesByElement(@NotNull final PsiElement element, @NotNull final ProcessingContext context) {
            final PsiElement parent = element.getParent();
            final PsiElement tag = parent.getParent();
            PsiReference ref = null;
            String tagName = ((XmlTag) tag).getLocalName();
            String attrName = ((XmlAttribute) parent).getName();
            String attrValue = ((XmlAttribute) parent).getValue();
            if (attrValue != null && attrValue.contains("{"))
                return PsiReference.EMPTY_ARRAY;
            if (FlexStateElementNames.NAME.equals(attrName)) {
                if ("State".equals(tagName)) {
                    ref = new AttributeValueSelfReference(element);
                } else {
                    return PsiReference.EMPTY_ARRAY;
                }
            } else if ("basedOn".equals(attrName) && element.getTextLength() == 2) {
                return PsiReference.EMPTY_ARRAY;
            } else if (FlexStateElementNames.STATE_GROUPS.equals(attrName)) {
                if ("State".equals(tagName)) {
                    return buildStateRefs(element, true);
                } else {
                    return PsiReference.EMPTY_ARRAY;
                }
            }
            if (FlexReferenceContributor.TRANSITION_TAG_NAME.equals(tagName)) {
                if ((element.textContains('*') && "*".equals(StringUtil.unquoteString(element.getText()))) || // empty value for attr, current state
                element.getTextLength() == 2) {
                    return PsiReference.EMPTY_ARRAY;
                }
            }
            if (ref == null) {
                ref = new FlexReferenceContributor.StateReference(element);
            }
            return new PsiReference[] { ref };
        }
    });
    XmlUtil.registerXmlAttributeValueReferenceProvider(registrar, new String[] { FlexStateElementNames.EXCLUDE_FROM, FlexStateElementNames.INCLUDE_IN }, new ScopeFilter(new ParentElementFilter(XmlTagFilter.INSTANCE, 2)), new PsiReferenceProvider() {

        @NotNull
        public PsiReference[] getReferencesByElement(@NotNull final PsiElement element, @NotNull final ProcessingContext context) {
            return buildStateRefs(element, false);
        }
    });
    XmlUtil.registerXmlAttributeValueReferenceProvider(registrar, new String[] { CodeContext.TARGET_ATTR_NAME }, new ScopeFilter(new ParentElementFilter(new AndFilter(XmlTagFilter.INSTANCE, new TagNameFilter(CodeContext.REPARENT_TAG_NAME), new NamespaceFilter(JavaScriptSupportLoader.MXML_URI3)), 2)), new PsiReferenceProvider() {

        @NotNull
        public PsiReference[] getReferencesByElement(@NotNull final PsiElement element, @NotNull final ProcessingContext context) {
            return new PsiReference[] { new XmlIdValueReference(element) };
        }
    });
}
Also used : JavaScriptSupportLoader(com.intellij.lang.javascript.JavaScriptSupportLoader) PsiMetaData(com.intellij.psi.meta.PsiMetaData) com.intellij.psi.filters(com.intellij.psi.filters) AnnotationBackedDescriptor(com.intellij.lang.javascript.flex.AnnotationBackedDescriptor) CreateClassIntentionWithCallback(com.intellij.lang.javascript.validation.fixes.CreateClassIntentionWithCallback) CreateFlexComponentFix(com.intellij.lang.javascript.flex.actions.newfile.CreateFlexComponentFix) CssReferenceProviderUtil(com.intellij.psi.css.resolve.CssReferenceProviderUtil) PsiTreeUtil(com.intellij.psi.util.PsiTreeUtil) LocalQuickFixProvider(com.intellij.codeInspection.LocalQuickFixProvider) JSAttribute(com.intellij.lang.javascript.psi.ecmal4.JSAttribute) JSReferenceSet(com.intellij.lang.javascript.psi.impl.JSReferenceSet) FlexCssPropertyDescriptor(com.intellij.javascript.flex.css.FlexCssPropertyDescriptor) PatternCondition(com.intellij.patterns.PatternCondition) FilterPattern(com.intellij.psi.filters.position.FilterPattern) XmlTagUtil(com.intellij.xml.util.XmlTagUtil) ResultSink(com.intellij.lang.javascript.psi.resolve.ResultSink) TextRange(com.intellij.openapi.util.TextRange) JSResolveResult(com.intellij.lang.javascript.psi.resolve.JSResolveResult) XmlPatterns.xmlAttribute(com.intellij.patterns.XmlPatterns.xmlAttribute) StandardPatterns.string(com.intellij.patterns.StandardPatterns.string) AttributeValueSelfReference(com.intellij.psi.impl.source.resolve.reference.impl.providers.AttributeValueSelfReference) JSFunction(com.intellij.lang.javascript.psi.JSFunction) List(java.util.List) AnnotationBackedDescriptorImpl(com.intellij.javascript.flex.mxml.schema.AnnotationBackedDescriptorImpl) XmlPatterns(com.intellij.patterns.XmlPatterns) com.intellij.psi(com.intellij.psi) com.intellij.util(com.intellij.util) NotNull(org.jetbrains.annotations.NotNull) CreateFlexSkinIntention(com.intellij.lang.javascript.flex.actions.newfile.CreateFlexSkinIntention) CodeContext(com.intellij.javascript.flex.mxml.schema.CodeContext) StringTokenizer(com.intellij.util.text.StringTokenizer) CreateFlexMobileViewIntentionAndFix(com.intellij.lang.javascript.validation.fixes.CreateFlexMobileViewIntentionAndFix) ActionScriptCreateClassOrInterfaceFix(com.intellij.lang.javascript.validation.fixes.ActionScriptCreateClassOrInterfaceFix) ParentElementFilter(com.intellij.psi.filters.position.ParentElementFilter) JSTextReference(com.intellij.lang.javascript.psi.impl.JSTextReference) ArrayList(java.util.ArrayList) NamespaceFilter(com.intellij.psi.filters.position.NamespaceFilter) com.intellij.psi.xml(com.intellij.psi.xml) XmlUtil(com.intellij.xml.util.XmlUtil) MxmlJSClass(com.intellij.javascript.flex.mxml.MxmlJSClass) JSPackageWrapper(com.intellij.lang.javascript.psi.ecmal4.impl.JSPackageWrapper) LocalQuickFix(com.intellij.codeInspection.LocalQuickFix) StandardPatterns.or(com.intellij.patterns.StandardPatterns.or) StringUtil(com.intellij.openapi.util.text.StringUtil) ReferenceSupport(com.intellij.lang.javascript.flex.ReferenceSupport) JSAttributeNameValuePair(com.intellij.lang.javascript.psi.ecmal4.JSAttributeNameValuePair) JSCommonTypeNames(com.intellij.lang.javascript.psi.JSCommonTypeNames) Pair(com.intellij.openapi.util.Pair) XmlAttributeDescriptor(com.intellij.xml.XmlAttributeDescriptor) Collections(java.util.Collections) JSPackageWrapper(com.intellij.lang.javascript.psi.ecmal4.impl.JSPackageWrapper) FilterPattern(com.intellij.psi.filters.position.FilterPattern) CreateFlexMobileViewIntentionAndFix(com.intellij.lang.javascript.validation.fixes.CreateFlexMobileViewIntentionAndFix) List(java.util.List) ArrayList(java.util.ArrayList) CreateFlexComponentFix(com.intellij.lang.javascript.flex.actions.newfile.CreateFlexComponentFix) PatternCondition(com.intellij.patterns.PatternCondition) TextRange(com.intellij.openapi.util.TextRange) ParentElementFilter(com.intellij.psi.filters.position.ParentElementFilter) ParentElementFilter(com.intellij.psi.filters.position.ParentElementFilter) CreateClassIntentionWithCallback(com.intellij.lang.javascript.validation.fixes.CreateClassIntentionWithCallback) MxmlJSClass(com.intellij.javascript.flex.mxml.MxmlJSClass) JSResolveResult(com.intellij.lang.javascript.psi.resolve.JSResolveResult) ResultSink(com.intellij.lang.javascript.psi.resolve.ResultSink) NotNull(org.jetbrains.annotations.NotNull) AnnotationBackedDescriptor(com.intellij.lang.javascript.flex.AnnotationBackedDescriptor) XmlAttributeDescriptor(com.intellij.xml.XmlAttributeDescriptor) JSFunction(com.intellij.lang.javascript.psi.JSFunction) ActionScriptCreateClassOrInterfaceFix(com.intellij.lang.javascript.validation.fixes.ActionScriptCreateClassOrInterfaceFix) JSAttributeNameValuePair(com.intellij.lang.javascript.psi.ecmal4.JSAttributeNameValuePair) JSTextReference(com.intellij.lang.javascript.psi.impl.JSTextReference) AnnotationBackedDescriptorImpl(com.intellij.javascript.flex.mxml.schema.AnnotationBackedDescriptorImpl) JSReferenceSet(com.intellij.lang.javascript.psi.impl.JSReferenceSet) NamespaceFilter(com.intellij.psi.filters.position.NamespaceFilter) JSAttribute(com.intellij.lang.javascript.psi.ecmal4.JSAttribute) AttributeValueSelfReference(com.intellij.psi.impl.source.resolve.reference.impl.providers.AttributeValueSelfReference) CreateFlexSkinIntention(com.intellij.lang.javascript.flex.actions.newfile.CreateFlexSkinIntention)

Example 24 with LocalQuickFix

use of com.intellij.codeInspection.LocalQuickFix in project intellij-plugins by JetBrains.

the class FlexCssReferenceContributor method registerReferenceProviders.

@Override
public void registerReferenceProviders(@NotNull final PsiReferenceRegistrar registrar) {
    registrar.registerReferenceProvider(PlatformPatterns.psiElement(CssString.class).and(new FilterPattern(new ElementFilter() {

        public boolean isAcceptable(Object element, PsiElement context) {
            CssFunction fun = PsiTreeUtil.getParentOfType((PsiElement) element, CssFunction.class);
            String funName;
            return fun != null && (FlexReferenceContributor.CLASS_REFERENCE.equals(funName = fun.getName()) || "Embed".equals(funName));
        }

        public boolean isClassAcceptable(Class hintClass) {
            return true;
        }
    })), new PsiReferenceProvider() {

        @NotNull
        @Override
        public PsiReference[] getReferencesByElement(@NotNull final PsiElement element, @NotNull ProcessingContext context) {
            CssFunction fun = PsiTreeUtil.getParentOfType(element, CssFunction.class);
            if (fun != null && "Embed".equals(fun.getName())) {
                // TODO: remove this stuff once css function will have proper psi
                PsiElement prev = PsiTreeUtil.prevLeaf(element);
                if (prev instanceof PsiWhiteSpace)
                    prev = PsiTreeUtil.prevLeaf(prev);
                if (prev != null)
                    prev = PsiTreeUtil.prevLeaf(prev);
                if (prev instanceof PsiWhiteSpace)
                    prev = PsiTreeUtil.prevLeaf(prev);
                // prev.getText() == Embed if element is the first parameter and the name not specified
                if (prev != null && !FlexReferenceContributor.SOURCE_ATTR_NAME.equals(prev.getText()) && !"Embed".equals(prev.getText())) {
                    return PsiReference.EMPTY_ARRAY;
                }
                return ReferenceSupport.getFileRefs(element, element, 1, ReferenceSupport.LookupOptions.EMBEDDED_ASSET);
            }
            final String value = StringUtil.unquoteString(element.getText());
            JSReferenceSet refSet = new JSReferenceSet(element, value, 1, false, true);
            if (fun != null && element instanceof CssString) {
                assert FlexReferenceContributor.CLASS_REFERENCE.equals(fun.getName());
                refSet.setLocalQuickFixProvider(new LocalQuickFixProvider() {

                    @Nullable
                    @Override
                    public LocalQuickFix[] getQuickFixes() {
                        if (!JSUtils.isValidClassName(value, true)) {
                            return LocalQuickFix.EMPTY_ARRAY;
                        }
                        ActionScriptCreateClassOrInterfaceFix[] fixes = new ActionScriptCreateClassOrInterfaceFix[] { new ActionScriptCreateClassOrInterfaceFix(value, null, element), new CreateFlexComponentFix(value, element) };
                        for (ActionScriptCreateClassOrInterfaceFix fix : fixes) {
                            fix.setCreatedClassFqnConsumer(newFqn -> ElementManipulators.getManipulator(element).handleContentChange(element, newFqn));
                        }
                        return fixes;
                    }
                });
            }
            return refSet.getReferences();
        }
    });
    registrar.registerReferenceProvider(PlatformPatterns.psiElement().and(new FilterPattern(new ElementFilter() {

        public boolean isAcceptable(Object element, PsiElement context) {
            if (element instanceof CssTokenImpl || element instanceof CssString) {
                CssTermList cssTermList = PsiTreeUtil.getParentOfType((PsiElement) element, CssTermList.class);
                if (cssTermList != null) {
                    CssDeclaration cssDeclaration = PsiTreeUtil.getParentOfType(cssTermList, CssDeclaration.class);
                    if (cssDeclaration != null && cssDeclaration.getValue() == cssTermList) {
                        if (FlexCssUtil.isStyleNameProperty(cssDeclaration.getPropertyName())) {
                            PsiFile file = cssDeclaration.getContainingFile();
                            if (file != null) {
                                if (file.getFileType() == CssFileType.INSTANCE) {
                                    Module module = findModuleForPsiElement(cssDeclaration);
                                    return module != null && ModuleType.get(module) == FlexModuleType.getInstance();
                                }
                                return JavaScriptSupportLoader.isFlexMxmFile(file);
                            }
                        }
                    }
                }
            }
            return false;
        }

        public boolean isClassAcceptable(Class hintClass) {
            return true;
        }
    })), new PsiReferenceProvider() {

        @NotNull
        @Override
        public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) {
            String styleName = CssClassValueReference.getValue(element);
            if (styleName.length() > 0) {
                return new PsiReference[] { new CssClassValueReference(element) };
            }
            return PsiReference.EMPTY_ARRAY;
        }
    });
}
Also used : ProcessingContext(com.intellij.util.ProcessingContext) CssTokenImpl(com.intellij.psi.css.impl.CssTokenImpl) LocalQuickFix(com.intellij.codeInspection.LocalQuickFix) NotNull(org.jetbrains.annotations.NotNull) LocalQuickFixProvider(com.intellij.codeInspection.LocalQuickFixProvider) FilterPattern(com.intellij.psi.filters.position.FilterPattern) ActionScriptCreateClassOrInterfaceFix(com.intellij.lang.javascript.validation.fixes.ActionScriptCreateClassOrInterfaceFix) ModuleUtilCore.findModuleForPsiElement(com.intellij.openapi.module.ModuleUtilCore.findModuleForPsiElement) CreateFlexComponentFix(com.intellij.lang.javascript.flex.actions.newfile.CreateFlexComponentFix) CssClassValueReference(com.intellij.javascript.flex.css.CssClassValueReference) JSReferenceSet(com.intellij.lang.javascript.psi.impl.JSReferenceSet) ElementFilter(com.intellij.psi.filters.ElementFilter) Module(com.intellij.openapi.module.Module)

Example 25 with LocalQuickFix

use of com.intellij.codeInspection.LocalQuickFix in project intellij-plugins by JetBrains.

the class FlexCssElementDescriptorProvider method getQuickFixesForUnknownProperty.

@NotNull
@Override
public LocalQuickFix[] getQuickFixesForUnknownProperty(@NotNull String propertyName, @NotNull PsiElement context, boolean isOnTheFly) {
    if (!isOnTheFly) {
        return LocalQuickFix.EMPTY_ARRAY;
    }
    final VirtualFile vFile = checkForQuickFixAndGetVFile(context);
    if (vFile == null) {
        return LocalQuickFix.EMPTY_ARRAY;
    }
    final CssDialect dialect = CssDialectMappings.getInstance(context.getProject()).getMapping(vFile);
    if (dialect == CssDialect.CLASSIC) {
        final Collection<? extends CssPropertyDescriptor> flexDescriptor = findPropertyDescriptors(propertyName, context);
        if (!flexDescriptor.isEmpty()) {
            return new LocalQuickFix[] { new SwitchToCssDialectQuickFix(FlexCSSDialect.getInstance()) };
        }
    } else {
        final CssElementDescriptorProviderImpl classicCssDescriptorProvider = CssElementDescriptorProvider.EP_NAME.findExtension(CssElementDescriptorProviderImpl.class);
        if (classicCssDescriptorProvider != null) {
            Collection<? extends CssPropertyDescriptor> classicDescriptors = classicCssDescriptorProvider.findPropertyDescriptors(propertyName, context);
            if (!classicDescriptors.isEmpty()) {
                return new LocalQuickFix[] { new SwitchToCssDialectQuickFix(CssDialect.CLASSIC) };
            }
        }
    }
    return LocalQuickFix.EMPTY_ARRAY;
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) CssDialect(com.intellij.lang.css.CssDialect) LocalQuickFix(com.intellij.codeInspection.LocalQuickFix) CssElementDescriptorProviderImpl(com.intellij.psi.css.impl.util.scheme.CssElementDescriptorProviderImpl) NotNull(org.jetbrains.annotations.NotNull)

Aggregations

LocalQuickFix (com.intellij.codeInspection.LocalQuickFix)59 NotNull (org.jetbrains.annotations.NotNull)20 PsiElement (com.intellij.psi.PsiElement)16 Nullable (org.jetbrains.annotations.Nullable)11 IntentionAction (com.intellij.codeInsight.intention.IntentionAction)10 ProblemDescriptor (com.intellij.codeInspection.ProblemDescriptor)10 ASTNode (com.intellij.lang.ASTNode)6 Project (com.intellij.openapi.project.Project)6 VirtualFile (com.intellij.openapi.vfs.VirtualFile)6 XmlTag (com.intellij.psi.xml.XmlTag)6 PsiFile (com.intellij.psi.PsiFile)5 PsiReference (com.intellij.psi.PsiReference)5 ArrayList (java.util.ArrayList)5 PsiTreeUtil (com.intellij.psi.util.PsiTreeUtil)4 LocalQuickFixProvider (com.intellij.codeInspection.LocalQuickFixProvider)3 QuickFixWrapper (com.intellij.codeInspection.ex.QuickFixWrapper)3 Pair (com.intellij.openapi.util.Pair)3 TextRange (com.intellij.openapi.util.TextRange)3 XmlAttributeDescriptor (com.intellij.xml.XmlAttributeDescriptor)3 XmlElementDescriptor (com.intellij.xml.XmlElementDescriptor)3