Search in sources :

Example 6 with FileReferenceSet

use of com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReferenceSet in project intellij-community by JetBrains.

the class FileReferenceQuickFixProvider method registerQuickFix.

@NotNull
public static List<? extends LocalQuickFix> registerQuickFix(@NotNull FileReference reference) {
    final FileReferenceSet fileReferenceSet = reference.getFileReferenceSet();
    int index = reference.getIndex();
    if (index < 0)
        return Collections.emptyList();
    final String newFileName = reference.getFileNameToCreate();
    // check if we could create file
    if (newFileName.isEmpty() || newFileName.indexOf('\\') != -1 || newFileName.indexOf('*') != -1 || newFileName.indexOf('?') != -1 || SystemInfo.isWindows && newFileName.indexOf(':') != -1) {
        return Collections.emptyList();
    }
    PsiFileSystemItem context = null;
    PsiElement element = reference.getElement();
    PsiFile containingFile = element == null ? null : element.getContainingFile();
    if (index > 0) {
        context = fileReferenceSet.getReference(index - 1).resolve();
    } else {
        // index == 0
        final Collection<PsiFileSystemItem> defaultContexts = fileReferenceSet.getDefaultContexts();
        if (defaultContexts.isEmpty()) {
            return Collections.emptyList();
        }
        Module module = containingFile == null ? null : ModuleUtilCore.findModuleForPsiElement(containingFile);
        for (PsiFileSystemItem defaultContext : defaultContexts) {
            if (defaultContext != null) {
                final VirtualFile virtualFile = defaultContext.getVirtualFile();
                if (virtualFile != null && defaultContext.isDirectory() && virtualFile.isInLocalFileSystem()) {
                    if (context == null) {
                        context = defaultContext;
                    }
                    if (module != null && module == getModuleForContext(defaultContext)) {
                        // fixes IDEA-64156
                        // todo: fix it on PsiFileReferenceHelper level in 10.X
                        context = defaultContext;
                        break;
                    }
                }
            }
        }
        if (context == null && ApplicationManager.getApplication().isUnitTestMode()) {
            context = defaultContexts.iterator().next();
        }
    }
    if (context == null)
        return Collections.emptyList();
    final VirtualFile virtualFile = context.getVirtualFile();
    if (virtualFile == null || !virtualFile.isValid())
        return Collections.emptyList();
    final PsiDirectory directory = context.getManager().findDirectory(virtualFile);
    if (directory == null)
        return Collections.emptyList();
    if (fileReferenceSet.isCaseSensitive()) {
        final PsiElement psiElement = containingFile == null ? null : reference.innerSingleResolve(false, containingFile);
        if (psiElement != null) {
            final String existingElementName = ((PsiNamedElement) psiElement).getName();
            final RenameFileReferenceIntentionAction renameRefAction = new RenameFileReferenceIntentionAction(existingElementName, reference);
            final RenameFileFix renameFileFix = new RenameFileFix(newFileName);
            return Arrays.asList(renameRefAction, renameFileFix);
        }
    }
    final boolean isdirectory;
    if (!reference.isLast()) {
        // directory
        try {
            directory.checkCreateSubdirectory(newFileName);
        } catch (IncorrectOperationException ex) {
            return Collections.emptyList();
        }
        isdirectory = true;
    } else {
        FileType ft = FileTypeManager.getInstance().getFileTypeByFileName(newFileName);
        if (ft instanceof UnknownFileType)
            return Collections.emptyList();
        try {
            directory.checkCreateFile(newFileName);
        } catch (IncorrectOperationException ex) {
            return Collections.emptyList();
        }
        isdirectory = false;
    }
    final CreateFileFix action = new MyCreateFileFix(isdirectory, newFileName, directory, reference);
    return Collections.singletonList(action);
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) FileReferenceSet(com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReferenceSet) FileType(com.intellij.openapi.fileTypes.FileType) UnknownFileType(com.intellij.openapi.fileTypes.UnknownFileType) UnknownFileType(com.intellij.openapi.fileTypes.UnknownFileType) RenameFileFix(com.intellij.codeInsight.daemon.impl.quickfix.RenameFileFix) IncorrectOperationException(com.intellij.util.IncorrectOperationException) Module(com.intellij.openapi.module.Module) NotNull(org.jetbrains.annotations.NotNull)

Example 7 with FileReferenceSet

use of com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReferenceSet in project intellij-community by JetBrains.

the class ConvertAbsolutePathToRelativeIntentionAction method isAvailable.

@Override
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
    final int offset = editor.getCaretModel().getOffset();
    final PsiElement element = file.findElementAt(offset);
    if (element == null || element instanceof PsiWhiteSpace) {
        return false;
    }
    final PsiReference reference = file.findReferenceAt(offset);
    final FileReference fileReference = reference == null ? null : FileReference.findFileReference(reference);
    if (fileReference != null) {
        final FileReferenceSet set = fileReference.getFileReferenceSet();
        final FileReference lastReference = set.getLastReference();
        return set.couldBeConvertedTo(isConvertToRelative()) && lastReference != null && (!isConvertToRelative() && !set.isAbsolutePathReference() || isConvertToRelative() && set.isAbsolutePathReference()) && lastReference.resolve() != null;
    }
    return false;
}
Also used : PsiReference(com.intellij.psi.PsiReference) FileReferenceSet(com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReferenceSet) FileReference(com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReference) PsiElement(com.intellij.psi.PsiElement) PsiWhiteSpace(com.intellij.psi.PsiWhiteSpace)

Example 8 with FileReferenceSet

use of com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReferenceSet in project intellij-community by JetBrains.

the class IconsReferencesContributor method registerReferenceProviders.

@Override
public void registerReferenceProviders(@NotNull PsiReferenceRegistrar registrar) {
    final PsiJavaElementPattern.Capture<PsiLiteralExpression> presentationAnno = literalExpression().annotationParam("com.intellij.ide.presentation.Presentation", "icon");
    registrar.registerReferenceProvider(presentationAnno, new PsiReferenceProvider() {

        @NotNull
        @Override
        public PsiReference[] getReferencesByElement(@NotNull final PsiElement element, @NotNull ProcessingContext context) {
            if (!PsiUtil.isPluginProject(element.getProject()))
                return PsiReference.EMPTY_ARRAY;
            return new PsiReference[] { new PsiReferenceBase<PsiElement>(element, true) {

                @Override
                public PsiElement resolve() {
                    String value = (String) ((PsiLiteralExpression) element).getValue();
                    if (value != null) {
                        List<String> path = StringUtil.split(value, ".");
                        if (path.size() > 1 && path.get(0).endsWith("Icons")) {
                            Project project = element.getProject();
                            PsiClass cur = findIconClass(project, path.get(0));
                            if (cur == null) {
                                return null;
                            }
                            for (int i = 1; i < path.size() - 1; i++) {
                                cur = cur.findInnerClassByName(path.get(i), false);
                                if (cur == null) {
                                    return null;
                                }
                            }
                            return cur.findFieldByName(path.get(path.size() - 1), false);
                        }
                    }
                    return null;
                }

                @Override
                public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException {
                    PsiElement field = resolve();
                    if (field instanceof PsiField) {
                        String fqn = ((PsiField) field).getContainingClass().getQualifiedName();
                        if (fqn.startsWith("com.intellij.icons.")) {
                            return replace(newElementName, fqn, "com.intellij.icons.", element);
                        }
                        if (fqn.startsWith("icons.")) {
                            return replace(newElementName, fqn, "icons.", element);
                        }
                    }
                    return super.handleElementRename(newElementName);
                }

                @Override
                public PsiElement bindToElement(@NotNull PsiElement element) throws IncorrectOperationException {
                    if (element instanceof PsiField) {
                        String fqn = ((PsiField) element).getContainingClass().getQualifiedName();
                        String newElementName = ((PsiField) element).getName();
                        if (fqn.startsWith("com.intellij.icons.")) {
                            return replace(newElementName, fqn, "com.intellij.icons.", getElement());
                        }
                        if (fqn.startsWith("icons.")) {
                            return replace(newElementName, fqn, "icons.", getElement());
                        }
                    }
                    return super.bindToElement(element);
                }

                private PsiElement replace(String newElementName, String fqn, String pckg, PsiElement container) {
                    String newValue = "\"" + fqn.substring(pckg.length()) + "." + newElementName + "\"";
                    return getElement().replace(JavaPsiFacade.getElementFactory(container.getProject()).createExpressionFromText(newValue, container.getParent()));
                }

                @NotNull
                @Override
                public Object[] getVariants() {
                    return EMPTY_ARRAY;
                }
            } };
        }
    });
    final PsiMethodPattern method = psiMethod().withName("findIcon", "getIcon").definedInClass(IconLoader.class.getName());
    final PsiJavaElementPattern.Capture<PsiLiteralExpression> findGetIconPattern = literalExpression().and(psiExpression().methodCallParameter(0, method));
    registrar.registerReferenceProvider(findGetIconPattern, new PsiReferenceProvider() {

        @NotNull
        @Override
        public PsiReference[] getReferencesByElement(@NotNull final PsiElement element, @NotNull ProcessingContext context) {
            if (!PsiUtil.isIdeaProject(element.getProject()))
                return PsiReference.EMPTY_ARRAY;
            return new FileReferenceSet(element) {

                @Override
                protected Collection<PsiFileSystemItem> getExtraContexts() {
                    final Module icons = ModuleManager.getInstance(element.getProject()).findModuleByName("icons");
                    if (icons != null) {
                        final ArrayList<PsiFileSystemItem> result = new ArrayList<>();
                        final VirtualFile[] roots = ModuleRootManager.getInstance(icons).getSourceRoots();
                        final PsiManager psiManager = element.getManager();
                        for (VirtualFile root : roots) {
                            final PsiDirectory directory = psiManager.findDirectory(root);
                            if (directory != null) {
                                result.add(directory);
                            }
                        }
                        return result;
                    }
                    return super.getExtraContexts();
                }
            }.getAllReferences();
        }
    });
    registrar.registerReferenceProvider(XmlPatterns.xmlAttributeValue().withLocalName("icon"), new PsiReferenceProvider() {

        @NotNull
        @Override
        public PsiReference[] getReferencesByElement(@NotNull final PsiElement element, @NotNull ProcessingContext context) {
            if (!PsiUtil.isPluginProject(element.getProject()) || !DescriptorUtil.isPluginXml(element.getContainingFile())) {
                return PsiReference.EMPTY_ARRAY;
            }
            return new PsiReference[] { new PsiReferenceBase<PsiElement>(element, true) {

                @Override
                public PsiElement resolve() {
                    String value = ((XmlAttributeValue) element).getValue();
                    if (value.startsWith("/")) {
                        FileReference lastRef = new FileReferenceSet(element).getLastReference();
                        return lastRef != null ? lastRef.resolve() : null;
                    }
                    List<String> path = StringUtil.split(value, ".");
                    if (path.size() > 1 && path.get(0).endsWith("Icons")) {
                        Project project = element.getProject();
                        PsiClass cur = findIconClass(project, path.get(0));
                        if (cur == null)
                            return null;
                        for (int i = 1; i < path.size() - 1; i++) {
                            cur = cur.findInnerClassByName(path.get(i), false);
                            if (cur == null)
                                return null;
                        }
                        return cur.findFieldByName(path.get(path.size() - 1), false);
                    }
                    return null;
                }

                @Override
                public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException {
                    PsiElement element = resolve();
                    if (element instanceof PsiFile) {
                        FileReference lastRef = new FileReferenceSet(element).getLastReference();
                        return lastRef.handleElementRename(newElementName);
                    }
                    if (element instanceof PsiField) {
                        String fqn = ((PsiField) element).getContainingClass().getQualifiedName();
                        if (fqn.startsWith("com.intellij.icons.")) {
                            return replace(fqn, newElementName, "com.intellij.icons.");
                        }
                        if (fqn.startsWith("icons.")) {
                            return replace(fqn, newElementName, "icons.");
                        }
                    }
                    return super.handleElementRename(newElementName);
                }

                @Override
                public PsiElement bindToElement(@NotNull PsiElement element) throws IncorrectOperationException {
                    if (element instanceof PsiFile) {
                        FileReference lastRef = new FileReferenceSet(element).getLastReference();
                        return lastRef.bindToElement(element);
                    }
                    if (element instanceof PsiField) {
                        String fqn = ((PsiField) element).getContainingClass().getQualifiedName();
                        String newName = ((PsiField) element).getName();
                        if (fqn.startsWith("com.intellij.icons.")) {
                            return replace(fqn, newName, "com.intellij.icons.");
                        }
                        if (fqn.startsWith("icons.")) {
                            return replace(fqn, newName, "icons.");
                        }
                    }
                    return super.bindToElement(element);
                }

                private PsiElement replace(String fqn, String newName, String pckg) {
                    XmlAttribute parent = (XmlAttribute) getElement().getParent();
                    parent.setValue(fqn.substring(pckg.length()) + "." + newName);
                    return parent.getValueElement();
                }

                @NotNull
                @Override
                public Object[] getVariants() {
                    return EMPTY_ARRAY;
                }
            } };
        }
    });
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) ProcessingContext(com.intellij.util.ProcessingContext) XmlAttribute(com.intellij.psi.xml.XmlAttribute) ArrayList(java.util.ArrayList) NotNull(org.jetbrains.annotations.NotNull) ArrayList(java.util.ArrayList) List(java.util.List) FileReferenceSet(com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReferenceSet) PsiMethodPattern(com.intellij.patterns.PsiMethodPattern) Project(com.intellij.openapi.project.Project) PsiJavaElementPattern(com.intellij.patterns.PsiJavaElementPattern) IncorrectOperationException(com.intellij.util.IncorrectOperationException) Module(com.intellij.openapi.module.Module) FileReference(com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReference) PsiFileReference(com.intellij.psi.impl.source.resolve.reference.impl.providers.PsiFileReference) IconLoader(com.intellij.openapi.util.IconLoader)

Example 9 with FileReferenceSet

use of com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReferenceSet in project intellij-plugins by JetBrains.

the class ReferenceSupport method getFileRefs.

public static PsiReference[] getFileRefs(@NotNull PsiElement elt, final int offset, String str, final LookupOptions lookupOptions) {
    if (lookupOptions.IGNORE_TEXT_AFTER_HASH) {
        int hashIndex = str.indexOf('#');
        if (hashIndex != -1)
            str = str.substring(0, hashIndex);
    }
    final RelativeToWhat relativeToWhat = relativeToWhat(str, elt, lookupOptions);
    final boolean startsWithSlash = str.startsWith("/");
    final FileReferenceSet base = new FileReferenceSet(str, elt, offset, null, SystemInfo.isFileSystemCaseSensitive) {

        @Override
        public boolean isAbsolutePathReference() {
            return relativeToWhat == RelativeToWhat.Absolute;
        }

        @Override
        public boolean couldBeConvertedTo(final boolean relative) {
            return ((relative && lookupOptions.RELATIVE_TO_FILE) || (!relative && lookupOptions.ABSOLUTE)) && super.couldBeConvertedTo(relative);
        }

        @Override
        public FileReference createFileReference(final TextRange range, final int index, final String text) {
            return new JSFlexFileReference(this, range, index, text, relativeToWhat);
        }

        @NotNull
        @Override
        public Collection<PsiFileSystemItem> computeDefaultContexts() {
            PsiFile psiFile = getContainingFile();
            if (psiFile == null)
                return Collections.emptyList();
            PsiElement context = psiFile.getContext();
            if (context instanceof PsiLanguageInjectionHost) {
                psiFile = context.getContainingFile();
            }
            psiFile = psiFile.getOriginalFile();
            final List<VirtualFile> dirs = new ArrayList<>();
            // paths relative to file should not start with slash
            if (lookupOptions.RELATIVE_TO_FILE && !startsWithSlash) {
                appendFileLocation(dirs, psiFile);
            }
            if ((lookupOptions.RELATIVE_TO_SOURCE_ROOTS_START_WITH_SLASH && startsWithSlash) || (lookupOptions.RELATIVE_TO_SOURCE_ROOTS_START_WITHOUT_SLASH && !startsWithSlash)) {
                appendSourceRoots(dirs, psiFile);
            }
            if (lookupOptions.ABSOLUTE) {
                appendFileSystemRoots(dirs);
            }
            if (lookupOptions.RELATIVE_TO_PROJECT_BASE_DIR) {
                dirs.add(psiFile.getProject().getBaseDir());
            }
            if (lookupOptions.IN_ROOTS_OF_MODULE_DEPENDENCIES) {
                appendRootsOfModuleDependencies(dirs, ModuleUtilCore.findModuleForPsiElement(psiFile));
            }
            return toFileSystemItems(dirs);
        }
    };
    return base.getAllReferences();
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) ArrayList(java.util.ArrayList) FileReferenceSet(com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReferenceSet) TextRange(com.intellij.openapi.util.TextRange)

Example 10 with FileReferenceSet

use of com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReferenceSet in project intellij-plugins by JetBrains.

the class DispatchPathResultContributor method createReferences.

public boolean createReferences(@NotNull final PsiElement psiElement, @NotNull final List<PsiReference> references, final boolean soft) {
    final String packageNamespace = getNamespace(psiElement);
    if (packageNamespace == null) {
        // XML error
        return false;
    }
    final WebFacet webFacet = WebUtil.getWebFacet(psiElement);
    if (webFacet == null) {
        // setup error, web-facet must be present in current or dependent module
        return false;
    }
    final FileReferenceSet fileReferenceSet = FileReferenceSet.createSet(psiElement, soft, false, true);
    FileReferenceSetHelper.addWebDirectoryAndCurrentNamespaceAsRoots(psiElement, packageNamespace, webFacet, fileReferenceSet);
    fileReferenceSet.setEmptyPathAllowed(false);
    Collections.addAll(references, fileReferenceSet.getAllReferences());
    return false;
}
Also used : FileReferenceSet(com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReferenceSet) WebFacet(com.intellij.javaee.web.facet.WebFacet)

Aggregations

FileReferenceSet (com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReferenceSet)16 NotNull (org.jetbrains.annotations.NotNull)8 VirtualFile (com.intellij.openapi.vfs.VirtualFile)6 WebFacet (com.intellij.javaee.web.facet.WebFacet)3 TextRange (com.intellij.openapi.util.TextRange)3 FileReference (com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReference)3 IncorrectOperationException (com.intellij.util.IncorrectOperationException)3 ProcessingContext (com.intellij.util.ProcessingContext)3 ArrayList (java.util.ArrayList)3 FileType (com.intellij.openapi.fileTypes.FileType)2 Module (com.intellij.openapi.module.Module)2 Condition (com.intellij.openapi.util.Condition)2 com.intellij.psi (com.intellij.psi)2 Collection (java.util.Collection)2 Collections (java.util.Collections)2 List (java.util.List)2 GoGetPackageFix (com.goide.codeInsight.imports.GoGetPackageFix)1 GoDeleteImportQuickFix (com.goide.quickfix.GoDeleteImportQuickFix)1 RenameFileFix (com.intellij.codeInsight.daemon.impl.quickfix.RenameFileFix)1 CreateFileFix (com.intellij.codeInsight.daemon.quickFix.CreateFileFix)1