Search in sources :

Example 81 with ResourceType

use of com.android.resources.ResourceType in project android by JetBrains.

the class DynamicResourceValueRepository method addValues.

private void addValues(Map<String, ClassField> resValues) {
    for (Map.Entry<String, ClassField> entry : resValues.entrySet()) {
        ClassField field = entry.getValue();
        String name = field.getName();
        assert entry.getKey().equals(name) : entry.getKey() + " vs " + name;
        ResourceType type = ResourceType.getEnum(field.getType());
        if (type == null) {
            LOG.warn("Ignoring field " + name + "(" + field + "): unknown type " + field.getType());
            continue;
        }
        ListMultimap<String, ResourceItem> map = mItems.get(type);
        if (map == null) {
            map = ArrayListMultimap.create();
            mItems.put(type, map);
        } else if (map.containsKey(name)) {
            // Masked by higher priority source provider
            continue;
        }
        ResourceItem item = new DynamicResourceValueItem(type, field);
        map.put(name, item);
    }
}
Also used : ResourceType(com.android.resources.ResourceType) ResourceItem(com.android.ide.common.res2.ResourceItem) Map(java.util.Map) ClassField(com.android.builder.model.ClassField)

Example 82 with ResourceType

use of com.android.resources.ResourceType in project android by JetBrains.

the class ResourceResolverCache method getResourceResolver.

@NotNull
public ResourceResolver getResourceResolver(@Nullable IAndroidTarget target, @NotNull String themeStyle, @NotNull final FolderConfiguration fullConfiguration) {
    // Are caches up to date?
    final LocalResourceRepository resources = AppResourceRepository.getAppResources(myManager.getModule(), true);
    assert resources != null;
    if (myCachedGeneration != resources.getModificationCount()) {
        myResolverMap.clear();
        myAppResourceMap.clear();
    }
    // Store the modification count as soon as possible. This ensures that if there is any modification of resources while the
    // resolver is being created, it will be cleared subsequently.
    myCachedGeneration = resources.getModificationCount();
    // When looking up the configured project and framework resources, the theme doesn't matter, so we look up only
    // by the configuration qualifiers; for example, here's a sample key:
    // -ldltr-sw384dp-w384dp-h640dp-normal-notlong-port-notnight-xhdpi-finger-keyssoft-nokeys-navhidden-nonav-1280x768-v17
    // Note that the target version is already baked in via the -v qualifier.
    //
    // However, the resource resolver also depends on the theme, so we use a more specific key for the resolver map than
    // for the configured resource maps, by prepending the theme name:
    // @style/MyTheme-ldltr-sw384dp-w384dp-h640dp-normal-notlong-port-notnight-xhdpi-finger-keyssoft-nokeys-navhidden-nonav-1280x768-v17
    String configurationKey = fullConfiguration.getUniqueKey();
    String resolverKey = themeStyle + configurationKey;
    ResourceResolver resolver = myResolverMap.get(resolverKey);
    if (resolver == null) {
        Map<ResourceType, ResourceValueMap> configuredAppRes;
        Map<ResourceType, ResourceValueMap> frameworkResources;
        // Framework resources
        if (target == null) {
            target = myManager.getTarget();
        }
        if (target == null) {
            frameworkResources = Collections.emptyMap();
        } else {
            ResourceRepository frameworkRes = getFrameworkResources(fullConfiguration, target);
            if (frameworkRes == null) {
                frameworkResources = Collections.emptyMap();
            } else {
                // get the framework resource values based on the current config
                frameworkResources = myFrameworkResourceMap.get(configurationKey);
                if (frameworkResources == null) {
                    frameworkResources = frameworkRes.getConfiguredResources(fullConfiguration);
                    // assets replaced the look for the same theme; that doesn't happen to the same extend for Holo)
                    if (target instanceof CompatibilityRenderTarget && target.getVersion().getApiLevel() == 8) {
                        IAndroidTarget realTarget = ((CompatibilityRenderTarget) target).getRealTarget();
                        if (realTarget != null) {
                            replaceDrawableBitmaps(frameworkResources, target, realTarget);
                        }
                    }
                    myFrameworkResourceMap.put(configurationKey, frameworkResources);
                }
            }
        }
        // App resources
        configuredAppRes = myAppResourceMap.get(configurationKey);
        if (configuredAppRes == null) {
            // get the project resource values based on the current config
            Application application = ApplicationManager.getApplication();
            configuredAppRes = application.runReadAction(new Computable<Map<ResourceType, ResourceValueMap>>() {

                @Override
                public Map<ResourceType, ResourceValueMap> compute() {
                    return resources.getConfiguredResources(fullConfiguration);
                }
            });
            myAppResourceMap.put(configurationKey, configuredAppRes);
        }
        // Resource Resolver
        assert themeStyle.startsWith(PREFIX_RESOURCE_REF) : themeStyle;
        boolean isProjectTheme = ResourceHelper.isProjectStyle(themeStyle);
        String themeName = ResourceHelper.styleToTheme(themeStyle);
        resolver = ResourceResolver.create(configuredAppRes, frameworkResources, themeName, isProjectTheme);
        if (target instanceof CompatibilityRenderTarget) {
            int apiLevel = target.getVersion().getFeatureLevel();
            if (apiLevel >= 21) {
                resolver.setDeviceDefaults("Material");
            } else if (apiLevel >= 14) {
                resolver.setDeviceDefaults("Holo");
            } else {
                resolver.setDeviceDefaults(ResourceResolver.LEGACY_THEME);
            }
        }
        myResolverMap.put(resolverKey, resolver);
    }
    return resolver;
}
Also used : ResourceType(com.android.resources.ResourceType) IAndroidTarget(com.android.sdklib.IAndroidTarget) ResourceValueMap(com.android.ide.common.resources.ResourceValueMap) CompatibilityRenderTarget(com.android.tools.idea.rendering.multi.CompatibilityRenderTarget) LocalResourceRepository(com.android.tools.idea.res.LocalResourceRepository) ResourceResolver(com.android.ide.common.resources.ResourceResolver) AppResourceRepository(com.android.tools.idea.res.AppResourceRepository) ResourceRepository(com.android.ide.common.resources.ResourceRepository) LocalResourceRepository(com.android.tools.idea.res.LocalResourceRepository) Application(com.intellij.openapi.application.Application) Computable(com.intellij.openapi.util.Computable) NotNull(org.jetbrains.annotations.NotNull)

Example 83 with ResourceType

use of com.android.resources.ResourceType in project android by JetBrains.

the class AndroidResourceRenameResourceProcessor method prepareValueResourceRenaming.

private static void prepareValueResourceRenaming(PsiElement element, String newName, Map<PsiElement, String> allRenames, final AndroidFacet facet) {
    ResourceManager manager = facet.getLocalResourceManager();
    XmlTag tag = PsiTreeUtil.getParentOfType(element, XmlTag.class);
    assert tag != null;
    String type = manager.getValueResourceType(tag);
    assert type != null;
    Project project = tag.getProject();
    DomElement domElement = DomManager.getDomManager(project).getDomElement(tag);
    assert domElement instanceof ResourceElement;
    String name = ((ResourceElement) domElement).getName().getValue();
    assert name != null;
    List<ResourceElement> resources = manager.findValueResources(type, name);
    for (ResourceElement resource : resources) {
        XmlElement xmlElement = resource.getName().getXmlAttributeValue();
        if (!element.getManager().areElementsEquivalent(element, xmlElement)) {
            allRenames.put(xmlElement, newName);
        }
    }
    if (getResourceType(element) == ResourceType.STYLE) {
        // For styles, try also to find child styles defined by name (i.e. "ParentName.StyleName") and add them
        // to the rename list. This will allow the rename processor to also handle the references to those. For example,
        // If you rename "MyTheme" and your manifest theme is "MyTheme.NoActionBar", this will make sure that
        // the reference from the manifest is also updated by adding "MyTheme.NoActionBar" to the rename list.
        // We iterate the styles in order to cascade any changes to children down the hierarchy.
        // List of styles that will be renamed.
        HashSet<String> renamedStyles = Sets.newHashSet();
        renamedStyles.add(name);
        final String stylePrefix = name + ".";
        Collection<String> renameCandidates;
        ResourceType resourceType = ResourceType.getEnum(type);
        if (resourceType == null) {
            renameCandidates = Collections.emptyList();
        } else {
            renameCandidates = Collections2.filter(manager.getResourceNames(resourceType), new Predicate<String>() {

                @Override
                public boolean apply(String input) {
                    return input.startsWith(stylePrefix);
                }
            });
        }
        for (String resourceName : ORDER_BY_LENGTH.sortedCopy(renameCandidates)) {
            // resourceName.lastIndexOf will never return -1 because we've filtered all names that
            // do not contain stylePrefix
            String parentName = resourceName.substring(0, resourceName.lastIndexOf('.'));
            if (!renamedStyles.contains(parentName)) {
                // This resource's parent wasn't affected by the rename
                continue;
            }
            for (ResourceElement resource : manager.findValueResources(type, resourceName)) {
                if (!(resource instanceof Style) || ((Style) resource).getParentStyle().getXmlAttributeValue() != null) {
                    // This element is not a style or does have an explicit parent so we do not rename it.
                    continue;
                }
                XmlAttributeValue xmlElement = resource.getName().getXmlAttributeValue();
                if (xmlElement != null) {
                    String newStyleName = newName + StringUtil.trimStart(resourceName, name);
                    allRenames.put(new ValueResourceElementWrapper(xmlElement), newStyleName);
                    renamedStyles.add(resourceName);
                }
            }
        }
    }
    PsiField[] resFields = AndroidResourceUtil.findResourceFieldsForValueResource(tag, false);
    for (PsiField resField : resFields) {
        String escaped = AndroidResourceUtil.getFieldNameByResourceName(newName);
        allRenames.put(resField, escaped);
    }
    // Also rename the dependent fields, e.g. if you rename <declare-styleable name="Foo">,
    // we have to rename not just R.styleable.Foo but the also R.styleable.Foo_* attributes
    PsiField[] styleableFields = AndroidResourceUtil.findStyleableAttributeFields(tag, false);
    if (styleableFields.length > 0) {
        String tagName = tag.getName();
        boolean isDeclareStyleable = tagName.equals(TAG_DECLARE_STYLEABLE);
        boolean isAttr = !isDeclareStyleable && tagName.equals(TAG_ATTR) && tag.getParentTag() != null;
        assert isDeclareStyleable || isAttr;
        String style = isAttr ? tag.getParentTag().getAttributeValue(ATTR_NAME) : null;
        for (PsiField resField : styleableFields) {
            String fieldName = resField.getName();
            String newAttributeName;
            if (isDeclareStyleable && fieldName.startsWith(name)) {
                newAttributeName = newName + fieldName.substring(name.length());
            } else if (isAttr && style != null) {
                newAttributeName = style + '_' + newName;
            } else {
                newAttributeName = name;
            }
            String escaped = AndroidResourceUtil.getFieldNameByResourceName(newAttributeName);
            allRenames.put(resField, escaped);
        }
    }
}
Also used : ResourceElement(org.jetbrains.android.dom.resources.ResourceElement) ResourceType(com.android.resources.ResourceType) ResourceManager(org.jetbrains.android.resourceManagers.ResourceManager) LocalResourceManager(org.jetbrains.android.resourceManagers.LocalResourceManager) XmlAttributeValue(com.intellij.psi.xml.XmlAttributeValue) Predicate(com.google.common.base.Predicate) Project(com.intellij.openapi.project.Project) DomElement(com.intellij.util.xml.DomElement) XmlElement(com.intellij.psi.xml.XmlElement) Style(org.jetbrains.android.dom.resources.Style) XmlTag(com.intellij.psi.xml.XmlTag) LazyValueResourceElementWrapper(org.jetbrains.android.dom.wrappers.LazyValueResourceElementWrapper) ValueResourceElementWrapper(org.jetbrains.android.dom.wrappers.ValueResourceElementWrapper)

Example 84 with ResourceType

use of com.android.resources.ResourceType in project android by JetBrains.

the class ResourceReferenceConverter method getResourceTypesInCurrentModule.

@NotNull
public static Set<ResourceType> getResourceTypesInCurrentModule(@NotNull AndroidFacet facet) {
    Set<ResourceType> result = EnumSet.noneOf(ResourceType.class);
    AppResourceRepository resourceRepository = facet.getAppResources(true);
    for (ResourceType type : ResourceType.values()) {
        if (resourceRepository.hasResourcesOfType(type)) {
            if (type == ResourceType.DECLARE_STYLEABLE) {
                // The ResourceRepository maps tend to hold DECLARE_STYLEABLE, but not STYLEABLE. However, these types are
                // used for R inner classes, and declare-styleable isn't a valid inner class name, so convert to styleable.
                result.add(ResourceType.STYLEABLE);
            } else {
                result.add(type);
            }
        }
    }
    return result;
}
Also used : ResourceType(com.android.resources.ResourceType) AndroidResourceType(org.jetbrains.android.dom.AndroidResourceType) AppResourceRepository(com.android.tools.idea.res.AppResourceRepository) NotNull(org.jetbrains.annotations.NotNull)

Example 85 with ResourceType

use of com.android.resources.ResourceType in project android by JetBrains.

the class ResourceReferenceConverter method getQuickFixes.

@Override
public LocalQuickFix[] getQuickFixes(ConvertContext context) {
    AndroidFacet facet = AndroidFacet.getInstance(context);
    if (facet != null) {
        final DomElement domElement = context.getInvocationElement();
        if (domElement instanceof GenericDomValue) {
            final String value = ((GenericDomValue) domElement).getStringValue();
            if (value != null) {
                ResourceValue resourceValue = ResourceValue.parse(value, false, myWithPrefix, true);
                if (resourceValue != null) {
                    String aPackage = resourceValue.getNamespace();
                    ResourceType resType = resourceValue.getType();
                    if (resType == null && myResourceTypes.size() == 1) {
                        resType = myResourceTypes.iterator().next();
                    }
                    final String resourceName = resourceValue.getResourceName();
                    if (aPackage == null && resType != null && resourceName != null && AndroidResourceUtil.isCorrectAndroidResourceName(resourceName)) {
                        final List<LocalQuickFix> fixes = new ArrayList<>();
                        ResourceFolderType folderType = AndroidResourceUtil.XML_FILE_RESOURCE_TYPES.get(resType);
                        if (folderType != null) {
                            fixes.add(new CreateFileResourceQuickFix(facet, folderType, resourceName, context.getFile(), false));
                        }
                        if (VALUE_RESOURCE_TYPES.contains(resType) && resType != ResourceType.LAYOUT) {
                            // layouts: aliases only
                            fixes.add(new CreateValueResourceQuickFix(facet, resType, resourceName, context.getFile(), false));
                        }
                        return fixes.toArray(new LocalQuickFix[fixes.size()]);
                    }
                }
            }
        }
    }
    return LocalQuickFix.EMPTY_ARRAY;
}
Also used : CreateValueResourceQuickFix(org.jetbrains.android.inspections.CreateValueResourceQuickFix) ResourceFolderType(com.android.resources.ResourceFolderType) ResourceValue(org.jetbrains.android.dom.resources.ResourceValue) LocalQuickFix(com.intellij.codeInspection.LocalQuickFix) ResourceType(com.android.resources.ResourceType) AndroidResourceType(org.jetbrains.android.dom.AndroidResourceType) CreateFileResourceQuickFix(org.jetbrains.android.inspections.CreateFileResourceQuickFix) AndroidFacet(org.jetbrains.android.facet.AndroidFacet)

Aggregations

ResourceType (com.android.resources.ResourceType)137 ResourceValue (com.android.ide.common.rendering.api.ResourceValue)31 NotNull (org.jetbrains.annotations.NotNull)16 Field (java.lang.reflect.Field)13 StyleResourceValue (com.android.ide.common.rendering.api.StyleResourceValue)12 BridgeContext (com.android.layoutlib.bridge.android.BridgeContext)11 VirtualFile (com.intellij.openapi.vfs.VirtualFile)10 Map (java.util.Map)10 Nullable (org.jetbrains.annotations.Nullable)10 Nullable (com.android.annotations.Nullable)8 ResourceFolderType (com.android.resources.ResourceFolderType)8 File (java.io.File)8 EnumMap (java.util.EnumMap)7 AndroidFacet (org.jetbrains.android.facet.AndroidFacet)7 Context (android.content.Context)6 View (android.view.View)6 AbsListView (android.widget.AbsListView)6 AdapterView (android.widget.AdapterView)6 ExpandableListView (android.widget.ExpandableListView)6 FrameLayout (android.widget.FrameLayout)6