Search in sources :

Example 26 with Density

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

the class DeviceDefinitionPreview method paintComponent.

@Override
protected void paintComponent(Graphics g) {
    GraphicsUtil.setupAntialiasing(g);
    GraphicsUtil.setupAAPainting(g);
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;
    g2d.setColor(JBColor.background());
    g2d.fillRect(0, 0, getWidth(), getHeight());
    g2d.setColor(JBColor.foreground());
    g2d.setFont(STANDARD_FONT);
    if (myDeviceData.name().get().equals(DO_NOT_DISPLAY)) {
        FontMetrics metrics = g2d.getFontMetrics();
        g2d.drawString(NO_DEVICE_SELECTED, (getWidth() - metrics.stringWidth(NO_DEVICE_SELECTED)) / 2, (getHeight() - metrics.getHeight()) / 2);
        return;
    }
    boolean isCircular = myDeviceData.isWear().get() && myDeviceData.isScreenRound().get();
    // Paint our icon
    Icon icon = getIcon(myDeviceData);
    icon.paintIcon(this, g, PADDING / 2, PADDING / 2);
    // Paint the device name
    g2d.setFont(TITLE_FONT);
    FontMetrics metrics = g.getFontMetrics(TITLE_FONT);
    g2d.drawString(myDeviceData.name().get(), JBUI.scale(50), PADDING + metrics.getHeight() / 2);
    g2d.drawLine(0, JBUI.scale(50), getWidth(), JBUI.scale(50));
    // Paint the device outline with dimensions labelled
    Dimension screenSize = getScaledDimension();
    Dimension pixelScreenSize = myDeviceData.getDeviceScreenDimension();
    if (screenSize != null) {
        if (screenSize.getHeight() <= 0) {
            screenSize.height = 1;
        }
        if (screenSize.getWidth() <= 0) {
            screenSize.width = 1;
        }
        RoundRectangle2D roundRect = new RoundRectangle2D.Double(PADDING, JBUI.scale(100), screenSize.width, screenSize.height, JBUI.scale(10), JBUI.scale(10));
        g2d.setStroke(new BasicStroke(DIMENSION_LINE_WIDTH));
        g2d.setColor(OUR_GRAY);
        g2d.setFont(FIGURE_FONT);
        metrics = g2d.getFontMetrics(FIGURE_FONT);
        int stringHeight = metrics.getHeight() - metrics.getDescent();
        // Paint the width dimension
        String widthString = Integer.toString(pixelScreenSize.width) + "px";
        int widthLineY = JBUI.scale(95) - (metrics.getHeight() - metrics.getDescent()) / 2;
        g2d.drawLine(PADDING, widthLineY, round(PADDING + screenSize.width), widthLineY);
        // Erase the part of the line that the text overlays
        g2d.setColor(JBColor.background());
        int widthStringWidth = metrics.stringWidth(widthString);
        int widthTextX = round(PADDING + (screenSize.width - widthStringWidth) / 2);
        g2d.drawLine(widthTextX - FIGURE_PADDING, widthLineY, widthTextX + widthStringWidth + FIGURE_PADDING, widthLineY);
        // Paint the width text
        g2d.setColor(JBColor.foreground());
        g2d.drawString(widthString, widthTextX, JBUI.scale(95));
        // Paint the height dimension
        g2d.setColor(OUR_GRAY);
        String heightString = Integer.toString(pixelScreenSize.height) + "px";
        int heightLineX = round(PADDING + screenSize.width + JBUI.scale(15));
        g2d.drawLine(heightLineX, JBUI.scale(100), heightLineX, round(JBUI.scale(100) + screenSize.height));
        // Erase the part of the line that the text overlays
        g2d.setColor(JBColor.background());
        int heightTextY = round(JBUI.scale(100) + (screenSize.height + stringHeight) / 2);
        g2d.drawLine(heightLineX, heightTextY + FIGURE_PADDING, heightLineX, heightTextY - stringHeight - FIGURE_PADDING);
        // Paint the height text
        g2d.setColor(JBColor.foreground());
        g2d.drawString(heightString, heightLineX - JBUI.scale(10), heightTextY);
        // Paint the diagonal dimension
        g2d.setColor(OUR_GRAY);
        String diagString = FORMAT.format(myDeviceData.diagonalScreenSize().get());
        int diagTextX = round(PADDING + (screenSize.width - metrics.stringWidth(diagString)) / 2);
        int diagTextY = round(JBUI.scale(100) + (screenSize.height + stringHeight) / 2);
        double chin = (double) myDeviceData.screenChinSize().get();
        chin *= screenSize.getWidth() / myDeviceData.getDeviceScreenDimension().getWidth();
        Line2D diagLine = new Line2D.Double(PADDING, JBUI.scale(100) + screenSize.height + chin, PADDING + screenSize.width, JBUI.scale(100));
        if (isCircular) {
            // Move the endpoints of the line to within the circle. Each endpoint must move towards the center axis of the circle by
            // 0.5 * (l - l/sqrt(2)) where l is the diameter of the circle.
            double dist = 0.5 * (screenSize.width - screenSize.width / Math.sqrt(2));
            diagLine.setLine(diagLine.getX1() + dist, diagLine.getY1() - dist, diagLine.getX2() - dist, diagLine.getY2() + dist);
        }
        g2d.draw(diagLine);
        // Erase the part of the line that the text overlays
        g2d.setColor(JBColor.background());
        Rectangle erasureRect = new Rectangle(diagTextX - FIGURE_PADDING, diagTextY - stringHeight - FIGURE_PADDING, metrics.stringWidth(diagString) + FIGURE_PADDING * 2, stringHeight + FIGURE_PADDING * 2);
        g2d.fill(erasureRect);
        // Paint the diagonal text
        g2d.setColor(JBColor.foreground());
        g2d.drawString(diagString, diagTextX, diagTextY);
        // Finally, paint the outline
        g2d.setStroke(new BasicStroke(OUTLINE_LINE_WIDTH));
        g2d.setColor(JBColor.foreground());
        if (isCircular) {
            double x = roundRect.getX();
            double y = roundRect.getY();
            Ellipse2D circle = new Ellipse2D.Double(x, y, screenSize.width, screenSize.height + chin);
            g2d.draw(circle);
            if (chin > 0) {
                erasureRect = new Rectangle((int) x, (int) (y + screenSize.height + OUTLINE_LINE_WIDTH / 2 + 1), screenSize.width, (int) chin + OUTLINE_LINE_WIDTH / 2 + 1);
                g2d.setColor(JBColor.background());
                g2d.fill(erasureRect);
                g2d.setColor(JBColor.foreground());
                double halfChinWidth = Math.sqrt(chin * (screenSize.width - chin)) - OUTLINE_LINE_WIDTH / 2;
                int chinX = (int) (x + screenSize.width / 2 - halfChinWidth);
                g2d.drawLine(chinX, (int) (y + screenSize.height), (int) (chinX + halfChinWidth * 2), (int) (y + screenSize.height));
            }
        } else {
            g2d.draw(roundRect);
        }
        // Paint the details. If it's a portrait phone, then paint to the right of the rect.
        // If it's a landscape tablet/tv, paint below.
        g2d.setFont(STANDARD_FONT);
        metrics = g2d.getFontMetrics(STANDARD_FONT);
        stringHeight = metrics.getHeight();
        int infoSegmentX;
        int infoSegmentY;
        if (myDeviceData.getDefaultDeviceOrientation().equals(ScreenOrientation.PORTRAIT)) {
            infoSegmentX = round(PADDING + screenSize.width + metrics.stringWidth(heightString) + PADDING);
            infoSegmentY = JBUI.scale(100);
        } else {
            infoSegmentX = PADDING;
            infoSegmentY = round(JBUI.scale(100) + screenSize.height + PADDING);
        }
        infoSegmentY += stringHeight;
        ScreenSize size = AvdScreenData.getScreenSize(myDeviceData.diagonalScreenSize().get());
        g2d.drawString("Size:      " + size.getResourceValue(), infoSegmentX, infoSegmentY);
        infoSegmentY += stringHeight;
        ScreenRatio ratio = AvdScreenData.getScreenRatio(myDeviceData.screenResolutionWidth().get(), myDeviceData.screenResolutionHeight().get());
        g2d.drawString("Ratio:    " + ratio.getResourceValue(), infoSegmentX, infoSegmentY);
        infoSegmentY += stringHeight;
        Density pixelDensity = myDeviceData.density().get();
        if (pixelDensity == Density.NODPI) {
            // We need to calculate the density
            pixelDensity = AvdScreenData.getScreenDensity(myDeviceData.isTv().get(), myDeviceData.screenDpi().get(), myDeviceData.screenResolutionHeight().get());
        }
        g2d.drawString("Density: " + pixelDensity.getResourceValue(), infoSegmentX, infoSegmentY);
    }
}
Also used : RoundRectangle2D(java.awt.geom.RoundRectangle2D) ScreenRatio(com.android.resources.ScreenRatio) Line2D(java.awt.geom.Line2D) Density(com.android.resources.Density) Ellipse2D(java.awt.geom.Ellipse2D) ScreenSize(com.android.resources.ScreenSize)

Example 27 with Density

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

the class AndroidColorAnnotator method pickBitmapFromXml.

@Nullable
private static File pickBitmapFromXml(@NotNull File file, @NotNull ResourceResolver resourceResolver, @NotNull Project project, @NonNull AndroidFacet facet, @NonNull ResourceValue resourceValue) {
    try {
        String xml = Files.toString(file, Charsets.UTF_8);
        Document document = XmlUtils.parseDocumentSilently(xml, true);
        if (document != null && document.getDocumentElement() != null) {
            Element root = document.getDocumentElement();
            String tag = root.getTagName();
            Element target = null;
            String attribute = null;
            if ("vector".equals(tag)) {
                // Take a look and see if we have a bitmap we can fall back to
                AppResourceRepository resourceRepository = AppResourceRepository.getAppResources(facet, true);
                List<com.android.ide.common.res2.ResourceItem> items = resourceRepository.getResourceItem(resourceValue.getResourceType(), resourceValue.getName());
                if (items != null) {
                    for (com.android.ide.common.res2.ResourceItem item : items) {
                        FolderConfiguration configuration = item.getConfiguration();
                        DensityQualifier densityQualifier = configuration.getDensityQualifier();
                        if (densityQualifier != null) {
                            Density density = densityQualifier.getValue();
                            if (density != null && density.isValidValueForDevice()) {
                                File bitmap = item.getFile();
                                if (bitmap != null && bitmap.isFile()) {
                                    return bitmap;
                                }
                            }
                        }
                    }
                }
                // Vectors are handled in the icon cache
                return file;
            } else if ("bitmap".equals(tag) || "nine-patch".equals(tag)) {
                target = root;
                attribute = ATTR_SRC;
            } else if ("selector".equals(tag) || "level-list".equals(tag) || "layer-list".equals(tag) || "transition".equals(tag)) {
                NodeList children = root.getChildNodes();
                for (int i = children.getLength() - 1; i >= 0; i--) {
                    Node item = children.item(i);
                    if (item.getNodeType() == Node.ELEMENT_NODE && TAG_ITEM.equals(item.getNodeName())) {
                        target = (Element) item;
                        if (target.hasAttributeNS(ANDROID_URI, ATTR_DRAWABLE)) {
                            attribute = ATTR_DRAWABLE;
                            break;
                        }
                    }
                }
            } else if ("clip".equals(tag) || "inset".equals(tag) || "scale".equals(tag)) {
                target = root;
                attribute = ATTR_DRAWABLE;
            } else {
                // <shape> etc - no bitmap to be found
                return null;
            }
            if (attribute != null && target.hasAttributeNS(ANDROID_URI, attribute)) {
                String src = target.getAttributeNS(ANDROID_URI, attribute);
                ResourceValue value = resourceResolver.findResValue(src, false);
                if (value != null) {
                    return ResourceHelper.resolveDrawable(resourceResolver, value, project);
                }
            }
        }
    } catch (Throwable ignore) {
    // Not logging for now; afraid to risk unexpected crashes in upcoming preview. TODO: Re-enable.
    //Logger.getInstance(AndroidColorAnnotator.class).warn(String.format("Could not read/render icon image %1$s", file), e);
    }
    return null;
}
Also used : DomElement(com.intellij.util.xml.DomElement) ResourceElement(org.jetbrains.android.dom.resources.ResourceElement) PsiElement(com.intellij.psi.PsiElement) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) AppResourceRepository(com.android.tools.idea.res.AppResourceRepository) FolderConfiguration(com.android.ide.common.resources.configuration.FolderConfiguration) Document(org.w3c.dom.Document) Density(com.android.resources.Density) ResourceValue(com.android.ide.common.rendering.api.ResourceValue) ResourceItem(com.android.ide.common.resources.ResourceItem) VirtualFile(com.intellij.openapi.vfs.VirtualFile) PsiFile(com.intellij.psi.PsiFile) File(java.io.File) DensityQualifier(com.android.ide.common.resources.configuration.DensityQualifier) Nullable(org.jetbrains.annotations.Nullable)

Example 28 with Density

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

the class AndroidColorAnnotator method findSmallestDpiVersion.

@Nullable
private static File findSmallestDpiVersion(@NonNull File bitmap) {
    File parentFile = bitmap.getParentFile();
    if (parentFile == null) {
        return null;
    }
    File resFolder = parentFile.getParentFile();
    if (resFolder == null) {
        return null;
    }
    String parentName = parentFile.getName();
    FolderConfiguration config = FolderConfiguration.getConfigForFolder(parentName);
    if (config == null) {
        return null;
    }
    DensityQualifier qualifier = config.getDensityQualifier();
    if (qualifier == null) {
        return null;
    }
    Density density = qualifier.getValue();
    if (density != null && density.isValidValueForDevice()) {
        String fileName = bitmap.getName();
        Density[] densities = Density.values();
        // Iterate in reverse, since the Density enum is in descending order
        for (int i = densities.length - 1; i >= 0; i--) {
            Density d = densities[i];
            if (d.isValidValueForDevice()) {
                String folder = parentName.replace(density.getResourceValue(), d.getResourceValue());
                bitmap = new File(resFolder, folder + File.separator + fileName);
                if (bitmap.exists()) {
                    if (bitmap.length() > MAX_ICON_SIZE) {
                        // No point continuing the loop; the other densities will be too big too
                        return null;
                    }
                    return bitmap;
                }
            }
        }
    }
    return null;
}
Also used : FolderConfiguration(com.android.ide.common.resources.configuration.FolderConfiguration) VirtualFile(com.intellij.openapi.vfs.VirtualFile) PsiFile(com.intellij.psi.PsiFile) File(java.io.File) Density(com.android.resources.Density) DensityQualifier(com.android.ide.common.resources.configuration.DensityQualifier) Nullable(org.jetbrains.annotations.Nullable)

Example 29 with Density

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

the class CategoryIconMap method toDensityMap.

/**
   * Like {@link #toDensityMap()} but with a filter for stripping out unwanted categories. This is
   * useful for icon sets organized by API.
   */
@NotNull
public Map<Density, BufferedImage> toDensityMap(@NotNull Filter filter) {
    Map<Density, BufferedImage> densityImageMap = Maps.newHashMap();
    for (String category : myCategoryMap.keySet()) {
        if (filter.accept(category)) {
            Map<String, BufferedImage> pathImageMap = myCategoryMap.get(category);
            for (String path : pathImageMap.keySet()) {
                Density density = pathToDensity(path);
                if (density != null) {
                    BufferedImage image = pathImageMap.get(path);
                    densityImageMap.put(density, image);
                }
            }
        }
    }
    return densityImageMap;
}
Also used : Density(com.android.resources.Density) BufferedImage(java.awt.image.BufferedImage) NotNull(org.jetbrains.annotations.NotNull)

Example 30 with Density

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

the class NlOldPalettePanel method updateConfiguration.

private void updateConfiguration() {
    myConfiguration = null;
    if (myDesignSurface == null) {
        return;
    }
    Configuration designConfiguration = myDesignSurface.getConfiguration();
    if (designConfiguration == null) {
        return;
    }
    State designState = designConfiguration.getDeviceState();
    Configuration configuration = designConfiguration.clone();
    Device device = configuration.getDevice();
    if (device == null) {
        return;
    }
    // Override to a predefined density that closest matches the screens resolution
    Density override = null;
    int monitorResolution = Toolkit.getDefaultToolkit().getScreenResolution();
    for (Density density : Density.values()) {
        if (density.getDpiValue() > 0) {
            if (override == null || Math.abs(density.getDpiValue() - monitorResolution) < Math.abs(override.getDpiValue() - monitorResolution)) {
                override = density;
            }
        }
    }
    if (override != null) {
        device = new Device.Builder(device).build();
        for (State state : device.getAllStates()) {
            Screen screen = state.getHardware().getScreen();
            screen.setXDimension((int) (screen.getXDimension() * override.getDpiValue() / screen.getXdpi()));
            screen.setYDimension((int) (screen.getYDimension() * override.getDpiValue() / screen.getYdpi()));
            screen.setXdpi(override.getDpiValue());
            screen.setYdpi(override.getDpiValue());
            screen.setPixelDensity(override);
        }
        configuration.setDevice(device, false);
        if (designState != null) {
            configuration.setDeviceStateName(designState.getName());
        }
        myConfiguration = configuration;
    }
}
Also used : Configuration(com.android.tools.idea.configurations.Configuration) GradleSyncState(com.android.tools.idea.gradle.project.sync.GradleSyncState) State(com.android.sdklib.devices.State) Device(com.android.sdklib.devices.Device) Screen(com.android.sdklib.devices.Screen) Density(com.android.resources.Density)

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