Search in sources :

Example 16 with Density

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

the class ConvertToDpQuickFix method apply.

@Override
public void apply(@NotNull PsiElement startElement, @NotNull PsiElement endElement, @NotNull AndroidQuickfixContexts.Context context) {
    if (context instanceof AndroidQuickfixContexts.BatchContext) {
        return;
    }
    final XmlTag tag = PsiTreeUtil.getParentOfType(startElement, XmlTag.class);
    final List<Density> densities = new ArrayList<Density>();
    for (Density density : Density.values()) {
        if (density.getDpiValue() > 0) {
            densities.add(density);
        }
    }
    final String[] densityPresentableNames = new String[densities.size()];
    String defaultValue = null;
    String initialValue = null;
    for (int i = 0; i < densities.size(); i++) {
        final Density density = densities.get(i);
        densityPresentableNames[i] = getLabelForDensity(density);
        final int dpi = density.getDpiValue();
        if (dpi == 0) {
            continue;
        }
        if (dpi == ourPrevDpi) {
            initialValue = densityPresentableNames[i];
        } else if (dpi == Density.DEFAULT_DENSITY) {
            defaultValue = densityPresentableNames[i];
        }
    }
    if (initialValue == null) {
        initialValue = defaultValue;
    }
    if (initialValue == null) {
        return;
    }
    final int dpi;
    if (ApplicationManager.getApplication().isUnitTestMode()) {
        dpi = Density.DEFAULT_DENSITY;
    } else {
        final int selectedIndex = Messages.showChooseDialog("What is the screen density the current px value works with?", "Choose density", densityPresentableNames, initialValue, null);
        if (selectedIndex < 0) {
            return;
        }
        dpi = densities.get(selectedIndex).getDpiValue();
    }
    //noinspection AssignmentToStaticFieldFromInstanceMethod
    ourPrevDpi = dpi;
    for (XmlAttribute attribute : tag.getAttributes()) {
        final String value = attribute.getValue();
        if (value != null && value.endsWith("px")) {
            final String newValue = convertToDp(value, dpi);
            if (newValue != null) {
                attribute.setValue(newValue);
            }
        }
    }
    final XmlTagValue tagValueElement = tag.getValue();
    final String tagValue = tagValueElement.getText();
    if (tagValue.endsWith("px")) {
        final String newValue = convertToDp(tagValue, dpi);
        if (newValue != null) {
            tagValueElement.setText(newValue);
        }
    }
}
Also used : XmlAttribute(com.intellij.psi.xml.XmlAttribute) XmlTagValue(com.intellij.psi.xml.XmlTagValue) ArrayList(java.util.ArrayList) Density(com.android.resources.Density) XmlTag(com.intellij.psi.xml.XmlTag)

Example 17 with Density

use of com.android.resources.Density in project android_frameworks_base by crdroidandroid.

the class ResourceHelper method getDrawable.

/**
     * Returns a drawable from the given value.
     * @param value The value that contains a path to a 9 patch, a bitmap or a xml based drawable,
     * or an hexadecimal color
     * @param context the current context
     * @param theme the theme to be used to inflate the drawable.
     */
public static Drawable getDrawable(ResourceValue value, BridgeContext context, Theme theme) {
    if (value == null) {
        return null;
    }
    String stringValue = value.getValue();
    if (RenderResources.REFERENCE_NULL.equals(stringValue)) {
        return null;
    }
    String lowerCaseValue = stringValue.toLowerCase();
    Density density = Density.MEDIUM;
    if (value instanceof DensityBasedResourceValue) {
        density = ((DensityBasedResourceValue) value).getResourceDensity();
    }
    if (lowerCaseValue.endsWith(NinePatch.EXTENSION_9PATCH)) {
        File file = new File(stringValue);
        if (file.isFile()) {
            try {
                return getNinePatchDrawable(new FileInputStream(file), density, value.isFramework(), stringValue, context);
            } catch (IOException e) {
                // failed to read the file, we'll return null below.
                Bridge.getLog().error(LayoutLog.TAG_RESOURCES_READ, "Failed lot load " + file.getAbsolutePath(), e, null);
            }
        }
        return null;
    } else if (lowerCaseValue.endsWith(".xml")) {
        // create a block parser for the file
        File f = new File(stringValue);
        if (f.isFile()) {
            try {
                // let the framework inflate the Drawable from the XML file.
                XmlPullParser parser = ParserFactory.create(f);
                BridgeXmlBlockParser blockParser = new BridgeXmlBlockParser(parser, context, value.isFramework());
                try {
                    return Drawable.createFromXml(context.getResources(), blockParser, theme);
                } finally {
                    blockParser.ensurePopped();
                }
            } catch (Exception e) {
                // this is an error and not warning since the file existence is checked before
                // attempting to parse it.
                Bridge.getLog().error(null, "Failed to parse file " + stringValue, e, null);
            }
        } else {
            Bridge.getLog().error(LayoutLog.TAG_BROKEN, String.format("File %s does not exist (or is not a file)", stringValue), null);
        }
        return null;
    } else {
        File bmpFile = new File(stringValue);
        if (bmpFile.isFile()) {
            try {
                Bitmap bitmap = Bridge.getCachedBitmap(stringValue, value.isFramework() ? null : context.getProjectKey());
                if (bitmap == null) {
                    bitmap = Bitmap_Delegate.createBitmap(bmpFile, false, /*isMutable*/
                    density);
                    Bridge.setCachedBitmap(stringValue, bitmap, value.isFramework() ? null : context.getProjectKey());
                }
                return new BitmapDrawable(context.getResources(), bitmap);
            } catch (IOException e) {
                // we'll return null below
                Bridge.getLog().error(LayoutLog.TAG_RESOURCES_READ, "Failed lot load " + bmpFile.getAbsolutePath(), e, null);
            }
        } else {
            // attempt to get a color from the value
            try {
                int color = getColor(stringValue);
                return new ColorDrawable(color);
            } catch (NumberFormatException e) {
                // we'll return null below.
                Bridge.getLog().error(LayoutLog.TAG_RESOURCES_FORMAT, "Failed to convert " + stringValue + " into a drawable", e, null);
            }
        }
    }
    return null;
}
Also used : DensityBasedResourceValue(com.android.ide.common.rendering.api.DensityBasedResourceValue) XmlPullParser(org.xmlpull.v1.XmlPullParser) IOException(java.io.IOException) BitmapDrawable(android.graphics.drawable.BitmapDrawable) Density(com.android.resources.Density) FileInputStream(java.io.FileInputStream) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) XmlPullParserException(org.xmlpull.v1.XmlPullParserException) Bitmap(android.graphics.Bitmap) ColorDrawable(android.graphics.drawable.ColorDrawable) File(java.io.File) BridgeXmlBlockParser(com.android.layoutlib.bridge.android.BridgeXmlBlockParser)

Example 18 with Density

use of com.android.resources.Density in project android_frameworks_base by crdroidandroid.

the class RenderAction method getConfiguration.

// VisibleForTesting
public static Configuration getConfiguration(RenderParams params) {
    Configuration config = new Configuration();
    HardwareConfig hardwareConfig = params.getHardwareConfig();
    ScreenSize screenSize = hardwareConfig.getScreenSize();
    if (screenSize != null) {
        switch(screenSize) {
            case SMALL:
                config.screenLayout |= Configuration.SCREENLAYOUT_SIZE_SMALL;
                break;
            case NORMAL:
                config.screenLayout |= Configuration.SCREENLAYOUT_SIZE_NORMAL;
                break;
            case LARGE:
                config.screenLayout |= Configuration.SCREENLAYOUT_SIZE_LARGE;
                break;
            case XLARGE:
                config.screenLayout |= Configuration.SCREENLAYOUT_SIZE_XLARGE;
                break;
        }
    }
    Density density = hardwareConfig.getDensity();
    if (density == null) {
        density = Density.MEDIUM;
    }
    config.screenWidthDp = hardwareConfig.getScreenWidth() / density.getDpiValue();
    config.screenHeightDp = hardwareConfig.getScreenHeight() / density.getDpiValue();
    if (config.screenHeightDp < config.screenWidthDp) {
        //noinspection SuspiciousNameCombination
        config.smallestScreenWidthDp = config.screenHeightDp;
    } else {
        config.smallestScreenWidthDp = config.screenWidthDp;
    }
    config.densityDpi = density.getDpiValue();
    // never run in compat mode:
    config.compatScreenWidthDp = config.screenWidthDp;
    config.compatScreenHeightDp = config.screenHeightDp;
    ScreenOrientation orientation = hardwareConfig.getOrientation();
    if (orientation != null) {
        switch(orientation) {
            case PORTRAIT:
                config.orientation = Configuration.ORIENTATION_PORTRAIT;
                break;
            case LANDSCAPE:
                config.orientation = Configuration.ORIENTATION_LANDSCAPE;
                break;
            case SQUARE:
                //noinspection deprecation
                config.orientation = Configuration.ORIENTATION_SQUARE;
                break;
        }
    } else {
        config.orientation = Configuration.ORIENTATION_UNDEFINED;
    }
    ScreenRound roundness = hardwareConfig.getScreenRoundness();
    if (roundness != null) {
        switch(roundness) {
            case ROUND:
                config.screenLayout |= Configuration.SCREENLAYOUT_ROUND_YES;
                break;
            case NOTROUND:
                config.screenLayout |= Configuration.SCREENLAYOUT_ROUND_NO;
        }
    } else {
        config.screenLayout |= Configuration.SCREENLAYOUT_ROUND_UNDEFINED;
    }
    String locale = params.getLocale();
    if (locale != null && !locale.isEmpty())
        config.locale = new Locale(locale);
    return config;
}
Also used : ScreenOrientation(com.android.resources.ScreenOrientation) Locale(java.util.Locale) HardwareConfig(com.android.ide.common.rendering.api.HardwareConfig) Configuration(android.content.res.Configuration) ScreenSize(com.android.resources.ScreenSize) Density(com.android.resources.Density) ScreenRound(com.android.resources.ScreenRound)

Example 19 with Density

use of com.android.resources.Density in project android_frameworks_base by crdroidandroid.

the class BitmapFactory_Delegate method nativeDecodeStream.

// ------ Native Delegates ------
@LayoutlibDelegate
static /*package*/
Bitmap nativeDecodeStream(InputStream is, byte[] storage, @Nullable Rect padding, @Nullable Options opts) {
    Bitmap bm = null;
    Density density = Density.MEDIUM;
    Set<BitmapCreateFlags> bitmapCreateFlags = EnumSet.of(BitmapCreateFlags.MUTABLE);
    if (opts != null) {
        density = Density.getEnum(opts.inDensity);
        if (opts.inPremultiplied) {
            bitmapCreateFlags.add(BitmapCreateFlags.PREMULTIPLIED);
        }
        opts.inScaled = false;
    }
    try {
        if (is instanceof NinePatchInputStream) {
            NinePatchInputStream npis = (NinePatchInputStream) is;
            npis.disableFakeMarkSupport();
            // load the bitmap as a nine patch
            com.android.ninepatch.NinePatch ninePatch = com.android.ninepatch.NinePatch.load(npis, true, /*is9Patch*/
            false);
            // get the bitmap and chunk objects.
            bm = Bitmap_Delegate.createBitmap(ninePatch.getImage(), bitmapCreateFlags, density);
            NinePatchChunk chunk = ninePatch.getChunk();
            // put the chunk in the bitmap
            bm.setNinePatchChunk(NinePatch_Delegate.serialize(chunk));
            if (padding != null) {
                // read the padding
                int[] paddingArray = chunk.getPadding();
                padding.left = paddingArray[0];
                padding.top = paddingArray[1];
                padding.right = paddingArray[2];
                padding.bottom = paddingArray[3];
            }
        } else {
            // load the bitmap directly.
            bm = Bitmap_Delegate.createBitmap(is, bitmapCreateFlags, density);
        }
    } catch (IOException e) {
        Bridge.getLog().error(null, "Failed to load image", e, null);
    }
    return bm;
}
Also used : NinePatchInputStream(com.android.layoutlib.bridge.util.NinePatchInputStream) NinePatchChunk(com.android.ninepatch.NinePatchChunk) IOException(java.io.IOException) Density(com.android.resources.Density) BitmapCreateFlags(android.graphics.Bitmap_Delegate.BitmapCreateFlags) LayoutlibDelegate(com.android.tools.layoutlib.annotations.LayoutlibDelegate)

Example 20 with Density

use of com.android.resources.Density in project platform_frameworks_base by android.

the class BitmapFactory_Delegate method nativeDecodeStream.

// ------ Native Delegates ------
@LayoutlibDelegate
static /*package*/
Bitmap nativeDecodeStream(InputStream is, byte[] storage, @Nullable Rect padding, @Nullable Options opts) {
    Bitmap bm = null;
    Density density = Density.MEDIUM;
    Set<BitmapCreateFlags> bitmapCreateFlags = EnumSet.of(BitmapCreateFlags.MUTABLE);
    if (opts != null) {
        density = Density.getEnum(opts.inDensity);
        if (opts.inPremultiplied) {
            bitmapCreateFlags.add(BitmapCreateFlags.PREMULTIPLIED);
        }
        opts.inScaled = false;
    }
    try {
        if (is instanceof NinePatchInputStream) {
            NinePatchInputStream npis = (NinePatchInputStream) is;
            npis.disableFakeMarkSupport();
            // load the bitmap as a nine patch
            com.android.ninepatch.NinePatch ninePatch = com.android.ninepatch.NinePatch.load(npis, true, /*is9Patch*/
            false);
            // get the bitmap and chunk objects.
            bm = Bitmap_Delegate.createBitmap(ninePatch.getImage(), bitmapCreateFlags, density);
            NinePatchChunk chunk = ninePatch.getChunk();
            // put the chunk in the bitmap
            bm.setNinePatchChunk(NinePatch_Delegate.serialize(chunk));
            if (padding != null) {
                // read the padding
                int[] paddingArray = chunk.getPadding();
                padding.left = paddingArray[0];
                padding.top = paddingArray[1];
                padding.right = paddingArray[2];
                padding.bottom = paddingArray[3];
            }
        } else {
            // load the bitmap directly.
            bm = Bitmap_Delegate.createBitmap(is, bitmapCreateFlags, density);
        }
    } catch (IOException e) {
        Bridge.getLog().error(null, "Failed to load image", e, null);
    }
    return bm;
}
Also used : NinePatchInputStream(com.android.layoutlib.bridge.util.NinePatchInputStream) NinePatchChunk(com.android.ninepatch.NinePatchChunk) IOException(java.io.IOException) Density(com.android.resources.Density) BitmapCreateFlags(android.graphics.Bitmap_Delegate.BitmapCreateFlags) LayoutlibDelegate(com.android.tools.layoutlib.annotations.LayoutlibDelegate)

Aggregations

Density (com.android.resources.Density)34 IOException (java.io.IOException)12 File (java.io.File)10 ScreenSize (com.android.resources.ScreenSize)8 Bitmap (android.graphics.Bitmap)7 BitmapDrawable (android.graphics.drawable.BitmapDrawable)7 Configuration (android.content.res.Configuration)6 ColorDrawable (android.graphics.drawable.ColorDrawable)6 DensityBasedResourceValue (com.android.ide.common.rendering.api.DensityBasedResourceValue)6 HardwareConfig (com.android.ide.common.rendering.api.HardwareConfig)6 BridgeXmlBlockParser (com.android.layoutlib.bridge.android.BridgeXmlBlockParser)6 ScreenOrientation (com.android.resources.ScreenOrientation)6 FileInputStream (java.io.FileInputStream)6 MalformedURLException (java.net.MalformedURLException)6 XmlPullParser (org.xmlpull.v1.XmlPullParser)6 XmlPullParserException (org.xmlpull.v1.XmlPullParserException)6 NinePatchChunk (com.android.ninepatch.NinePatchChunk)5 ScreenRound (com.android.resources.ScreenRound)5 LayoutlibDelegate (com.android.tools.layoutlib.annotations.LayoutlibDelegate)5 FileNotFoundException (java.io.FileNotFoundException)5