Example usage for com.intellij.openapi.fileTypes StdFileTypes XML

List of usage examples for com.intellij.openapi.fileTypes StdFileTypes XML

Introduction

In this page you can find the example usage for com.intellij.openapi.fileTypes StdFileTypes XML.

Prototype

LanguageFileType XML

To view the source code for com.intellij.openapi.fileTypes StdFileTypes XML.

Click Source Link

Usage

From source file:com.android.tools.idea.configurations.ConfigurationMatcher.java

License:Apache License

@NotNull
private ConfigMatch selectConfigMatch(@NotNull List<ConfigMatch> matches) {
    // API 11-13: look for a x-large device
    Comparator<ConfigMatch> comparator = null;
    IAndroidTarget projectTarget = myManager.getProjectTarget();
    if (projectTarget != null) {
        int apiLevel = projectTarget.getVersion().getApiLevel();
        if (apiLevel >= 11 && apiLevel < 14) {
            // TODO: Maybe check the compatible-screen tag in the manifest to figure out
            // what kind of device should be used for display.
            comparator = new TabletConfigComparator();
        }//from  w  ww .  j a  v  a2s.  co m
    }

    if (comparator == null) {
        // lets look for a high density device
        comparator = new PhoneConfigComparator();
    }
    Collections.sort(matches, comparator);

    // Look at the currently active editor to see if it's a layout editor, and if so,
    // look up its configuration and if the configuration is in our match list,
    // use it. This means we "preserve" the current configuration when you open
    // new layouts.
    // TODO: This is running too late for the layout preview; the new editor has
    // already taken over so getSelectedTextEditor() returns self. Perhaps we
    // need to fish in the open editors instead.

    //Editor activeEditor = ApplicationManager.getApplication().runReadAction(new Computable<Editor>() {
    //  @Override
    //  public Editor compute() {
    //    FileEditorManager editorManager = FileEditorManager.getInstance(myManager.getProject());
    //    return editorManager.getSelectedTextEditor();
    //  }
    //});

    // TODO: How do I redispatch without risking lock?
    //Editor activeEditor = AndroidUtils.getSelectedEditor(myManager.getProject());
    if (ApplicationManager.getApplication().isDispatchThread()) {
        FileEditorManager editorManager = FileEditorManager.getInstance(myManager.getProject());
        Editor activeEditor = editorManager.getSelectedTextEditor();
        if (activeEditor != null) {
            FileDocumentManager documentManager = FileDocumentManager.getInstance();
            VirtualFile file = documentManager.getFile(activeEditor.getDocument());
            if (file != null && file != myFile && file.getFileType() == StdFileTypes.XML
                    && ResourceFolderType.LAYOUT
                            .equals(ResourceFolderType.getFolderType(file.getParent().getName()))) {
                Configuration configuration = myManager.getConfiguration(file);
                FolderConfiguration fullConfig = configuration.getFullConfig();
                for (ConfigMatch match : matches) {
                    if (fullConfig.equals(match.testConfig)) {
                        return match;
                    }
                }
            }
        }
    }

    // the list has been sorted so that the first item is the best config
    return matches.get(0);
}

From source file:com.android.tools.idea.editors.AndroidEditorTitleProvider.java

License:Apache License

@Nullable
@Override/* w w  w  . j  a v a2 s .  com*/
public String getEditorTabTitle(Project project, VirtualFile file) {
    if (DumbService.isDumb(project)) {
        return null;
    }

    if (file.getFileType() != StdFileTypes.XML) {
        return null;
    }

    // Resource file?
    if (file.getName().equals(FN_ANDROID_MANIFEST_XML)) {
        return null;
    }

    VirtualFile parent = file.getParent();
    if (parent == null) {
        return null;
    }

    String parentName = parent.getName();
    int index = parentName.indexOf('-');
    if (index == -1 || index == parentName.length() - 1) {
        return null;
    }

    ResourceFolderType folderType = ResourceFolderType.getFolderType(parentName);
    if (folderType == null) {
        return null;
    }

    return parentName.substring(index + 1) + File.separator + file.getPresentableName();
}

From source file:com.android.tools.idea.lint.MigrateDrawableToMipmapFix.java

License:Apache License

@Override
public void apply(@NotNull PsiElement startElement, @NotNull PsiElement endElement,
        @NotNull AndroidQuickfixContexts.Context context) {
    Project project = startElement.getProject();
    AndroidFacet facet = AndroidFacet.getInstance(startElement);
    if (facet == null) {
        return;/*from  w  w w .  ja  v  a2s. c om*/
    }

    final List<PsiFile> bitmaps = Lists.newArrayList();
    final Set<PsiElement> references = Sets.newHashSet();

    GlobalSearchScope useScope = GlobalSearchScope.projectScope(project);
    ProjectResourceRepository projectResources = facet.getProjectResources(true);
    List<ResourceItem> resourceItems = projectResources.getResourceItem(myUrl.type, myUrl.name);
    if (resourceItems != null) {
        for (ResourceItem item : resourceItems) {
            PsiFile file = LocalResourceRepository.getItemPsiFile(project, item);
            if (file == null) {
                continue;
            }
            bitmaps.add(file);

            Iterable<PsiReference> allReferences = SearchUtils.findAllReferences(file, useScope);
            for (PsiReference next : allReferences) {
                PsiElement element = next.getElement();
                if (element != null) {
                    references.add(element);
                }
            }
        }
    }

    PsiField[] resourceFields = AndroidResourceUtil.findResourceFields(facet, ResourceType.DRAWABLE.getName(),
            myUrl.name, true);
    if (resourceFields.length == 1) {
        Iterable<PsiReference> allReferences = SearchUtils.findAllReferences(resourceFields[0], useScope);
        for (PsiReference next : allReferences) {
            PsiElement element = next.getElement();
            if (element != null) {
                references.add(element);
            }
        }
    }

    Set<PsiFile> applicableFiles = Sets.newHashSet();
    applicableFiles.addAll(bitmaps);
    for (PsiElement element : references) {
        PsiFile containingFile = element.getContainingFile();
        if (containingFile != null) {
            applicableFiles.add(containingFile);
        }
    }

    WriteCommandAction<Void> action = new WriteCommandAction<Void>(project, "Migrate Drawable to Bitmap",
            applicableFiles.toArray(new PsiFile[applicableFiles.size()])) {
        @Override
        protected void run(@NotNull Result<Void> result) throws Throwable {
            // Move each drawable bitmap from drawable-my-qualifiers to bitmap-my-qualifiers
            for (PsiFile bitmap : bitmaps) {
                VirtualFile file = bitmap.getVirtualFile();
                if (file == null) {
                    continue;
                }
                VirtualFile parent = file.getParent();
                if (parent == null) { // shouldn't happen for bitmaps found in the resource repository
                    continue;
                }

                if (file.getFileType() == StdFileTypes.XML && parent.getName().startsWith(FD_RES_VALUES)) {
                    // Resource alias rather than an actual drawable XML file: update the type reference instead
                    XmlFile xmlFile = (XmlFile) bitmap;
                    XmlTag root = xmlFile.getRootTag();
                    if (root != null) {
                        for (XmlTag item : root.getSubTags()) {
                            String name = item.getAttributeValue(ATTR_NAME);
                            if (myUrl.name.equals(name)) {
                                if (ResourceType.DRAWABLE.getName().equals(item.getName())) {
                                    item.setName(ResourceType.MIPMAP.getName());
                                } else if (ResourceType.DRAWABLE.getName()
                                        .equals(item.getAttributeValue(ATTR_TYPE))) {
                                    item.setAttribute(ATTR_TYPE, ResourceType.MIPMAP.getName());
                                }
                            }
                        }
                    }
                    continue; // Don't move the file
                }

                VirtualFile res = parent.getParent();
                if (res == null) { // shouldn't happen for bitmaps found in the resource repository
                    continue;
                }

                FolderConfiguration configuration = FolderConfiguration.getConfigForFolder(parent.getName());
                if (configuration == null) {
                    continue;
                }
                String targetFolderName = configuration.getFolderName(ResourceFolderType.MIPMAP);
                VirtualFile targetFolder = res.findChild(targetFolderName);
                if (targetFolder == null) {
                    targetFolder = res.createChildDirectory(this, targetFolderName);
                }
                file.move(this, targetFolder);
            }

            // Update references
            for (PsiElement reference : references) {
                if (reference instanceof XmlAttributeValue) {
                    // Convert @drawable/foo references to @mipmap/foo
                    XmlAttributeValue value = (XmlAttributeValue) reference;
                    XmlAttribute attribute = (XmlAttribute) value.getParent();
                    attribute.setValue(
                            ResourceUrl.create(ResourceType.MIPMAP, myUrl.name, false, false).toString());
                } else if (reference instanceof PsiReferenceExpression) {
                    // Convert R.drawable.foo references to R.mipmap.foo
                    PsiReferenceExpression inner = (PsiReferenceExpression) reference;
                    PsiExpression qualifier = inner.getQualifierExpression();
                    if (qualifier instanceof PsiReferenceExpression) {
                        PsiReferenceExpression outer = (PsiReferenceExpression) qualifier;
                        if (outer.getReferenceNameElement() instanceof PsiIdentifier) {
                            PsiIdentifier identifier = (PsiIdentifier) outer.getReferenceNameElement();
                            if (ResourceType.DRAWABLE.getName().equals(identifier.getText())) {
                                Project project = reference.getProject();
                                final PsiElementFactory elementFactory = JavaPsiFacade
                                        .getElementFactory(project);
                                PsiIdentifier newIdentifier = elementFactory
                                        .createIdentifier(ResourceType.MIPMAP.getName());
                                identifier.replace(newIdentifier);
                            }
                        }
                    }
                }
            }

        }
    };
    action.execute();
}

From source file:com.android.tools.idea.rendering.PsiProjectListener.java

License:Apache License

static boolean isRelevantFileType(@NotNull FileType fileType) {
    if (fileType == StdFileTypes.JAVA) { // fail fast for vital file type
        return false;
    }//from  w  w  w  . j ava  2 s.  com
    return fileType == StdFileTypes.XML || (fileType.isBinary()
            && fileType == FileTypeManager.getInstance().getFileTypeByExtension(EXT_PNG));
}

From source file:com.android.tools.idea.rendering.RenderErrorContributor.java

License:Apache License

private void reportRelevantCompilationErrors(@NotNull RenderLogger logger, @NotNull RenderTask renderTask) {
    Module module = logger.getModule();// www  .  ja va2 s . co  m
    if (module == null) {
        return;
    }

    Project project = module.getProject();
    WolfTheProblemSolver wolfgang = WolfTheProblemSolver.getInstance(project);

    if (!wolfgang.hasProblemFilesBeneath(module)) {
        return;
    }

    HtmlBuilder builder = new HtmlBuilder();
    String summary = null;
    if (logger.seenTagPrefix(TAG_RESOURCES_PREFIX)) {
        // Do we have errors in the res/ files?
        // See if it looks like we have aapt problems
        boolean haveResourceErrors = wolfgang
                .hasProblemFilesBeneath(virtualFile -> virtualFile.getFileType() == StdFileTypes.XML);
        if (haveResourceErrors) {
            summary = "Resource errors";
            builder.addBold("This project contains resource errors, so aapt did not succeed, "
                    + "which can cause rendering failures. Fix resource problems first.").newline().newline();
        }
    } else if (renderTask.getLayoutlibCallback().isUsed()) {
        boolean hasJavaErrors = wolfgang
                .hasProblemFilesBeneath(virtualFile -> virtualFile.getFileType() == StdFileTypes.JAVA);
        if (hasJavaErrors) {
            summary = "Compilation errors";
            builder.addBold("This project contains Java compilation errors, "
                    + "which can cause rendering failures for custom views. "
                    + "Fix compilation problems first.").newline().newline();
        }
    }

    if (summary == null) {
        return;
    }
    addIssue().setSeverity(HighlightSeverity.ERROR).setSummary(summary).setHtmlContent(builder).build();
}

From source file:com.android.tools.idea.rendering.RenderErrorPanel.java

License:Apache License

private static void reportRelevantCompilationErrors(RenderLogger logger, HtmlBuilder builder,
        RenderService renderService) {/*from   ww w.j ava 2  s.  c  o m*/
    Module module = logger.getModule();
    Project project = module.getProject();
    WolfTheProblemSolver wolfgang = WolfTheProblemSolver.getInstance(project);
    if (wolfgang.hasProblemFilesBeneath(module)) {
        if (logger.seenTagPrefix(TAG_RESOURCES_PREFIX)) {
            // Do we have errors in the res/ files?
            // See if it looks like we have aapt problems
            boolean haveResourceErrors = wolfgang.hasProblemFilesBeneath(new Condition<VirtualFile>() {
                @Override
                public boolean value(VirtualFile virtualFile) {
                    return virtualFile.getFileType() == StdFileTypes.XML;
                }
            });
            if (haveResourceErrors) {
                builder.addBold("NOTE: This project contains resource errors, so aapt did not succeed, "
                        + "which can cause rendering failures. Fix resource problems first.");
                builder.newline().newline();
            }
        } else if (renderService.getProjectCallback() != null && renderService.getProjectCallback().isUsed()) {
            boolean hasJavaErrors = wolfgang.hasProblemFilesBeneath(new Condition<VirtualFile>() {
                @Override
                public boolean value(VirtualFile virtualFile) {
                    return virtualFile.getFileType() == StdFileTypes.JAVA;
                }
            });
            if (hasJavaErrors) {
                builder.addBold("NOTE: This project contains Java compilation errors, "
                        + "which can cause rendering failures for custom views. "
                        + "Fix compilation problems first.");
                builder.newline().newline();
            }
        }
    }
}

From source file:com.android.tools.idea.rendering.ResourceFolderRepository.java

License:Apache License

private boolean scanValueFile(String qualifiers, PsiFile file, FolderConfiguration folderConfiguration) {
    boolean added = false;
    FileType fileType = file.getFileType();
    if (fileType == StdFileTypes.XML) {
        XmlFile xmlFile = (XmlFile) file;
        assert xmlFile.isValid();
        XmlDocument document = xmlFile.getDocument();
        if (document != null) {
            XmlTag root = document.getRootTag();
            if (root == null) {
                return false;
            }/*from   w w w  . ja va  2s .c o  m*/
            if (!root.getName().equals(TAG_RESOURCES)) {
                return false;
            }
            XmlTag[] subTags = root.getSubTags(); // Not recursive, right?
            List<ResourceItem> items = Lists.newArrayListWithExpectedSize(subTags.length);
            for (XmlTag tag : subTags) {
                String name = tag.getAttributeValue(ATTR_NAME);
                if (name != null) {
                    ResourceType type = getType(tag);
                    if (type != null) {
                        ListMultimap<String, ResourceItem> map = myItems.get(type);
                        if (map == null) {
                            map = ArrayListMultimap.create();
                            myItems.put(type, map);
                        }

                        ResourceItem item = new PsiResourceItem(name, type, tag, file);
                        map.put(name, item);
                        items.add(item);
                        added = true;

                        if (type == ResourceType.DECLARE_STYLEABLE) {
                            // for declare styleables we also need to create attr items for its children
                            XmlTag[] attrs = tag.getSubTags();
                            if (attrs.length > 0) {
                                map = myItems.get(ResourceType.ATTR);
                                if (map == null) {
                                    map = ArrayListMultimap.create();
                                    myItems.put(ResourceType.ATTR, map);
                                }

                                for (XmlTag child : attrs) {
                                    String attrName = child.getAttributeValue(ATTR_NAME);
                                    if (attrName != null && !attrName.startsWith(ANDROID_NS_NAME_PREFIX)
                                    // Only add attr nodes for elements that specify a format; otherwise
                                    // it's just a reference to an existing attr
                                            && child.getAttribute(ATTR_FORMAT) != null) {
                                        ResourceItem attrItem = new PsiResourceItem(attrName, ResourceType.ATTR,
                                                child, file);
                                        items.add(attrItem);
                                        map.put(attrName, attrItem);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            if (items != null) {
                PsiResourceFile resourceFile = new PsiResourceFile(file, items, qualifiers,
                        ResourceFolderType.VALUES, folderConfiguration);
                myResourceFiles.put(file, resourceFile);
            }
        }
    }

    return added;
}

From source file:com.android.tools.idea.res.PsiProjectListener.java

License:Apache License

static boolean isRelevantFileType(@NotNull FileType fileType) {
    if (fileType == StdFileTypes.JAVA) { // fail fast for vital file type
        return false;
    }//from  ww w .j a v  a  2  s.c o m
    // TODO: ensure that only android compatible images are recognized.
    return fileType == StdFileTypes.XML
            || fileType.isBinary() && fileType == ImageFileTypeManager.getInstance().getImageFileType();
}

From source file:com.android.tools.idea.res.ResourceFolderRepository.java

License:Apache License

private void scanFileResourceFolder(@NotNull VirtualFile directory, ResourceFolderType folderType,
        String qualifiers, FolderConfiguration folderConfiguration) {
    List<ResourceType> resourceTypes = FolderTypeRelationship.getRelatedResourceTypes(folderType);
    assert resourceTypes.size() >= 1 : folderType;
    ResourceType type = resourceTypes.get(0);

    boolean idGeneratingFolder = FolderTypeRelationship.isIdGeneratingFolderType(folderType);

    ListMultimap<String, ResourceItem> map = getMap(type, true);

    for (VirtualFile file : directory.getChildren()) {
        if (file.isValid() && !file.isDirectory()) {
            FileType fileType = file.getFileType();
            boolean idGeneratingFile = idGeneratingFolder && fileType == StdFileTypes.XML;
            if (PsiProjectListener.isRelevantFileType(fileType) || folderType == ResourceFolderType.RAW) {
                scanFileResourceFile(qualifiers, folderType, folderConfiguration, type, idGeneratingFile, map,
                        file);/* w  w  w . j  a  va2  s  .  co  m*/
            } // TODO: Else warn about files that aren't expected to be found here?
        }
    }
}

From source file:com.android.tools.idea.res.ResourceFolderRepository.java

License:Apache License

private boolean scanValueFileAsPsi(String qualifiers, PsiFile file, FolderConfiguration folderConfiguration) {
    boolean added = false;
    FileType fileType = file.getFileType();
    if (fileType == StdFileTypes.XML) {
        XmlFile xmlFile = (XmlFile) file;
        assert xmlFile.isValid();
        XmlDocument document = xmlFile.getDocument();
        if (document != null) {
            XmlTag root = document.getRootTag();
            if (root == null) {
                return false;
            }/*from   w  ww. j a  va  2 s.c  om*/
            if (!root.getName().equals(TAG_RESOURCES)) {
                return false;
            }
            XmlTag[] subTags = root.getSubTags(); // Not recursive, right?
            List<ResourceItem> items = Lists.newArrayListWithExpectedSize(subTags.length);
            for (XmlTag tag : subTags) {
                String name = tag.getAttributeValue(ATTR_NAME);
                if (name != null) {
                    ResourceType type = AndroidResourceUtil.getType(tag);
                    if (type != null) {
                        ListMultimap<String, ResourceItem> map = getMap(type, true);
                        ResourceItem item = new PsiResourceItem(name, type, tag, file);
                        map.put(name, item);
                        items.add(item);
                        added = true;

                        if (type == ResourceType.DECLARE_STYLEABLE) {
                            // for declare styleables we also need to create attr items for its children
                            XmlTag[] attrs = tag.getSubTags();
                            if (attrs.length > 0) {
                                map = getMap(ResourceType.ATTR, true);

                                for (XmlTag child : attrs) {
                                    String attrName = child.getAttributeValue(ATTR_NAME);
                                    if (attrName != null && !attrName.startsWith(ANDROID_NS_NAME_PREFIX)
                                    // Only add attr nodes for elements that specify a format or have flag/enum children; otherwise
                                    // it's just a reference to an existing attr
                                            && (child.getAttribute(ATTR_FORMAT) != null
                                                    || child.getSubTags().length > 0)) {
                                        ResourceItem attrItem = new PsiResourceItem(attrName, ResourceType.ATTR,
                                                child, file);
                                        items.add(attrItem);
                                        map.put(attrName, attrItem);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            PsiResourceFile resourceFile = new PsiResourceFile(file, items, qualifiers,
                    ResourceFolderType.VALUES, folderConfiguration);
            myResourceFiles.put(file.getVirtualFile(), resourceFile);
        }
    }

    return added;
}