Search in sources :

Example 46 with com.codename1.rad.ui

use of com.codename1.rad.ui in project CodenameOne by codenameone.

the class CSSTheme method getBackgroundImage.

public Image getBackgroundImage(Map<String, LexicalUnit> styles, ScaledUnit bgImage) {
    try {
        // ScaledUnit bgImage = (ScaledUnit)styles.get("background-image");
        if (bgImage == null) {
            return null;
        }
        String url = bgImage.getStringValue();
        String fileName = url;
        if (fileName.indexOf("/") != -1) {
            fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
        }
        if (loadedImages.containsKey(url)) {
            return loadedImages.get(url);
        }
        LexicalUnit imageId = styles.get("cn1-image-id");
        String imageIdStr = fileName;
        if (imageId != null) {
            imageIdStr = imageId.getStringValue();
        } else {
        /*
                int i=1;
                while (res.getImage(imageIdStr) != null) {
                    
                    if (i == 1) {
                        imageIdStr += "_"+(++i);
                    } else {
                        imageIdStr = imageIdStr.substring(0, imageIdStr.lastIndexOf("_")) + "_"+(++i);
                    }
                }
                */
        }
        Image resimg = res.getImage(imageIdStr);
        Integer defaultSourceDpi = null;
        if (constants.containsKey("defaultSourceDPIInt")) {
            Object v = constants.get("defaultSourceDPIInt");
            if (v instanceof String) {
                defaultSourceDpi = Integer.parseInt((String) v);
            } else if (v instanceof Number) {
                defaultSourceDpi = ((Number) v).intValue();
            } else if (v instanceof ScaledUnit) {
                ScaledUnit su = (ScaledUnit) v;
                defaultSourceDpi = su.getIntegerValue();
            } else {
                throw new IllegalArgumentException("defaultSourceDPIInt constant should be a String or a number but found " + v.getClass());
            }
        }
        if (resimg != null) {
            ImageMetadata md = imagesMetadata.get(imageIdStr);
            int srcDpi = (int) currentDpi;
            if (defaultSourceDpi != null) {
                srcDpi = defaultSourceDpi;
            }
            if (styles.containsKey("cn1-source-dpi")) {
                srcDpi = (int) ((ScaledUnit) styles.get("cn1-source-dpi")).getNumericValue();
            }
            if (refreshImages || (md != null && md.sourceDpi != srcDpi)) {
                // 
                res.remove(imageIdStr);
            } else {
                loadedImages.put(imageIdStr, resimg);
                return res.getImage(imageIdStr);
            }
        }
        URL imgURL = null;
        if (url.startsWith("http://") || url.startsWith("https://")) {
            imgURL = new URL(url);
        } else {
            imgURL = new URL(baseURL, url);
        }
        if (false && isFileURL(imgURL)) {
            // This section is switched off because loading multi-images via url()
            // will cause unexpected results in cases where image borders are generated.
            // In order for this approach to work, we need take into account multi-images when
            // producing snapshots in the webview so that the correct size of image is used.
            // You can still load multi-images as theme constants.
            // See https://github.com/codenameone/CodenameOne/issues/2569#issuecomment-426730539
            File imgDir = new File(imgURL.toURI());
            if (imgDir.isDirectory()) {
                try {
                    Image im = getResourceImage(imgDir.getName(), imgDir.getParentFile());
                    if (im != null) {
                        loadedImages.put(url, im);
                        return im;
                    }
                } catch (Throwable t) {
                    System.err.println("Failed to load Multi-image from " + imgURL);
                    t.printStackTrace();
                    throw t;
                }
            }
        }
        InputStream is = imgURL.openStream();
        EncodedImage encImg = EncodedImage.create(is);
        is.close();
        ResourcesMutator resm = new ResourcesMutator(res, com.codename1.ui.Display.DENSITY_VERY_HIGH, minDpi, maxDpi);
        int[] dpis = getDpi(encImg);
        int sourceDpi = (int) Math.round(currentDpi);
        if (styles.containsKey("cn1-source-dpi")) {
            double densityVal = ((ScaledUnit) styles.get("cn1-source-dpi")).getNumericValue();
            sourceDpi = (int) Math.round(densityVal);
            if (Math.abs(densityVal) < 0.5) {
                resm.targetDensity = 0;
            } else {
                resm.targetDensity = getDensityForDpi(densityVal);
            }
        } else if (defaultSourceDpi != null) {
            sourceDpi = defaultSourceDpi;
            if (Math.abs(sourceDpi) < 0.5) {
                resm.targetDensity = 0;
            } else {
                resm.targetDensity = getDensityForDpi(sourceDpi);
            }
        } else if (dpis[0] > 0) {
            resm.targetDensity = getImageDensity(encImg);
        } else {
            resm.targetDensity = getDensityForDpi(bgImage.dpi);
        }
        if (styles.containsKey("cn1-densities")) {
            ScaledUnit densities = (ScaledUnit) styles.get("cn1-densities");
            if (densities.getLexicalUnitType() == LexicalUnit.SAC_IDENT && "none".equals(densities.getStringValue())) {
                // Not a multi-image
                resm.setMultiImage(false);
            }
        } else if (sourceDpi == 0) {
            resm.setMultiImage(false);
        }
        Image im = resm.storeImage(encImg, imageIdStr, false);
        im.setImageName(imageIdStr);
        loadedImages.put(url, im);
        ImageMetadata md = new ImageMetadata(imageIdStr, sourceDpi);
        imagesMetadata.addImageMetadata(md);
        return im;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
Also used : ObjectInputStream(java.io.ObjectInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) ImageInputStream(javax.imageio.stream.ImageInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) EncodedImage(com.codename1.ui.EncodedImage) Image(com.codename1.ui.Image) EncodedImage(com.codename1.ui.EncodedImage) URL(java.net.URL) URISyntaxException(java.net.URISyntaxException) CSSParseException(org.w3c.css.sac.CSSParseException) FileNotFoundException(java.io.FileNotFoundException) ParseException(org.w3c.flute.parser.ParseException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) CSSException(org.w3c.css.sac.CSSException) IOException(java.io.IOException) File(java.io.File) LexicalUnit(org.w3c.css.sac.LexicalUnit)

Example 47 with com.codename1.rad.ui

use of com.codename1.rad.ui in project CodenameOne by codenameone.

the class ResourcesMutator method scaleMultiImage.

public static EditableResources.MultiImage scaleMultiImage(int fromDPI, int toDPI, int scaledWidth, int scaledHeight, EditableResources.MultiImage multi) {
    // try {
    int[] dpis = multi.getDpi();
    com.codename1.ui.EncodedImage[] imgs = multi.getInternalImages();
    int fromOffset = -1;
    int toOffset = -1;
    for (int iter = 0; iter < dpis.length; iter++) {
        if (dpis[iter] == fromDPI) {
            fromOffset = iter;
        }
        if (dpis[iter] == toDPI) {
            toOffset = iter;
        }
    }
    if (fromOffset == -1) {
        return null;
    }
    EditableResources.MultiImage newImage = new EditableResources.MultiImage();
    if (toOffset == -1) {
        com.codename1.ui.EncodedImage[] newImages = new com.codename1.ui.EncodedImage[imgs.length + 1];
        System.arraycopy(imgs, 0, newImages, 0, imgs.length);
        toOffset = imgs.length;
        int[] newDpis = new int[dpis.length + 1];
        System.arraycopy(dpis, 0, newDpis, 0, dpis.length);
        newDpis[toOffset] = toDPI;
        newImage.setDpi(newDpis);
        newImage.setInternalImages(newImages);
    } else {
        com.codename1.ui.EncodedImage[] newImages = new com.codename1.ui.EncodedImage[imgs.length];
        System.arraycopy(multi.getInternalImages(), 0, newImages, 0, imgs.length);
        newImage.setDpi(dpis);
        newImage.setInternalImages(newImages);
    }
    com.codename1.ui.Image sourceImage = newImage.getInternalImages()[fromOffset];
    BufferedImage buffer = new BufferedImage(sourceImage.getWidth(), sourceImage.getHeight(), BufferedImage.TYPE_INT_ARGB);
    buffer.setRGB(0, 0, sourceImage.getWidth(), sourceImage.getHeight(), sourceImage.getRGB(), 0, sourceImage.getWidth());
    sourceImage.getRGB();
    sourceImage.getWidth();
    BufferedImage scaled = getScaledInstance(buffer, scaledWidth, scaledHeight);
    byte[] bytes = toPngOrJpeg(scaled);
    // ByteArrayOutputStream output = new ByteArrayOutputStream();
    // ImageIO.write(scaled, "png", output);
    // output.close();
    // byte[] bytes = output.toByteArray();
    com.codename1.ui.EncodedImage encoded = com.codename1.ui.EncodedImage.create(bytes);
    newImage.getInternalImages()[toOffset] = encoded;
    return newImage;
// } catch (IOException ex) {
// ex.printStackTrace();
// 
// }
// return null;
}
Also used : BufferedImage(java.awt.image.BufferedImage) EditableResources(com.codename1.ui.util.EditableResources)

Example 48 with com.codename1.rad.ui

use of com.codename1.rad.ui in project CodenameOne by codenameone.

the class EditorFont method getBitmapFont.

/**
 * @return the bitmapFont
 */
public Font getBitmapFont() {
    Font bitmapFont = Font.getBitmapFont(lookupFont);
    if (bitmapFont != null) {
        return bitmapFont;
    }
    BufferedImage image = new BufferedImage(5000, 50, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = (Graphics2D) image.getGraphics();
    g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
    g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);
    g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, bitmapAntialiasing);
    g2d.setColor(Color.BLACK);
    g2d.fillRect(0, 0, image.getWidth(), image.getHeight());
    g2d.setColor(new Color(0xff0000));
    g2d.setFont(java.awt.Font.decode(lookupFont.split(";")[0]));
    FontMetrics metrics = g2d.getFontMetrics();
    FontRenderContext context = g2d.getFontRenderContext();
    int height = (int) Math.ceil(metrics.getMaxDescent() + metrics.getMaxAscent());
    int baseline = (int) Math.ceil(metrics.getMaxAscent());
    String charsetStr = bitmapCharset;
    int[] offsets = new int[charsetStr.length()];
    int[] widths = new int[offsets.length];
    int currentOffset = 0;
    for (int iter = 0; iter < charsetStr.length(); iter++) {
        offsets[iter] = currentOffset;
        String currentChar = charsetStr.substring(iter, iter + 1);
        g2d.drawString(currentChar, currentOffset, baseline);
        Rectangle2D rect = g2d.getFont().getStringBounds(currentChar, context);
        widths[iter] = (int) Math.ceil(rect.getWidth());
        // occupies more ram
        if (g2d.getFont().isItalic()) {
            currentOffset += metrics.getMaxAdvance();
        } else {
            currentOffset += widths[iter] + 1;
        }
    }
    g2d.dispose();
    BufferedImage shrunk = new BufferedImage(currentOffset, height, BufferedImage.TYPE_INT_RGB);
    g2d = (Graphics2D) shrunk.getGraphics();
    g2d.drawImage(image, 0, 0, null);
    g2d.dispose();
    int[] rgb = new int[shrunk.getWidth() * shrunk.getHeight()];
    shrunk.getRGB(0, 0, shrunk.getWidth(), shrunk.getHeight(), rgb, 0, shrunk.getWidth());
    com.codename1.ui.Image bitmap = com.codename1.ui.Image.createImage(rgb, shrunk.getWidth(), shrunk.getHeight());
    return com.codename1.ui.Font.createBitmapFont(lookupFont, bitmap, offsets, widths, charsetStr);
}
Also used : Color(java.awt.Color) Rectangle2D(java.awt.geom.Rectangle2D) Font(com.codename1.ui.Font) BufferedImage(java.awt.image.BufferedImage) Graphics2D(java.awt.Graphics2D) com.codename1.ui(com.codename1.ui) FontMetrics(java.awt.FontMetrics) FontRenderContext(java.awt.font.FontRenderContext)

Example 49 with com.codename1.rad.ui

use of com.codename1.rad.ui in project CodenameOne by codenameone.

the class URITests method runTest.

@Override
public boolean runTest() throws Exception {
    FileSystemStorage fs = FileSystemStorage.getInstance();
    String home = fs.getAppHomePath();
    if (!home.endsWith(fs.getFileSystemSeparator() + "")) {
        home += fs.getFileSystemSeparator();
    }
    String homePath = home.substring(6);
    homePath = StringUtil.replaceAll(homePath, "\\", "/");
    while (homePath.startsWith("/")) {
        homePath = homePath.substring(1);
    }
    homePath = "/" + homePath;
    com.codename1.io.URL url = new com.codename1.io.File("hello world.txt").toURL();
    // https://en.wikipedia.org/wiki/File_URI_scheme
    assertTrue(url.toString().startsWith("file:/"), "URL should start with file:///");
    assertEqual("file:" + homePath + "hello%20world.txt", url.toString(), "URL failed to encode space in file name");
    URI uri = new com.codename1.io.File("hello world.txt").toURI();
    assertEqual("file:" + homePath + "hello%20world.txt", uri.toString(), "URI failed to encode space in file name");
    assertEqual(homePath + "hello world.txt", uri.getPath(), "Incorrect URI path");
    return true;
}
Also used : File(com.codename1.io.File) FileSystemStorage(com.codename1.io.FileSystemStorage) URL(com.codename1.io.URL) URI(java.net.URI)

Example 50 with com.codename1.rad.ui

use of com.codename1.rad.ui in project CodenameOne by codenameone.

the class RSSReader method updateComponentValues.

void updateComponentValues(Container root, Hashtable h) {
    int c = root.getComponentCount();
    for (int iter = 0; iter < c; iter++) {
        Component current = root.getComponentAt(iter);
        // subclasses
        if (current.getClass() == com.codename1.ui.Container.class || current.getClass() == com.codename1.ui.Tabs.class) {
            updateComponentValues((Container) current, h);
            continue;
        }
        String n = current.getName();
        if (n != null) {
            String val = (String) h.get(n);
            if (val != null) {
                if (current instanceof Button) {
                    final String url = (String) val;
                    ((Button) current).addActionListener(new Listener(url));
                    continue;
                }
                if (current instanceof Label) {
                    ((Label) current).setText(val);
                    continue;
                }
                if (current instanceof TextArea) {
                    ((TextArea) current).setText(val);
                    continue;
                }
                if (current instanceof WebBrowser) {
                    ((WebBrowser) current).setPage(val, null);
                    continue;
                }
            }
        }
    }
}
Also used : Container(com.codename1.ui.Container) ActionListener(com.codename1.ui.events.ActionListener) Button(com.codename1.ui.Button) TextArea(com.codename1.ui.TextArea) Label(com.codename1.ui.Label) Component(com.codename1.ui.Component)

Aggregations

IOException (java.io.IOException)34 EncodedImage (com.codename1.ui.EncodedImage)28 ArrayList (java.util.ArrayList)27 Point (java.awt.Point)25 File (java.io.File)24 AnimationObject (com.codename1.ui.animations.AnimationObject)22 BufferedImage (java.awt.image.BufferedImage)22 Hashtable (java.util.Hashtable)19 Component (com.codename1.ui.Component)18 Form (com.codename1.ui.Form)18 Image (com.codename1.ui.Image)16 EditableResources (com.codename1.ui.util.EditableResources)16 FileInputStream (java.io.FileInputStream)16 Timeline (com.codename1.ui.animations.Timeline)15 BorderLayout (com.codename1.ui.layouts.BorderLayout)14 InvocationTargetException (java.lang.reflect.InvocationTargetException)12 UIBuilderOverride (com.codename1.ui.util.UIBuilderOverride)11 FileOutputStream (java.io.FileOutputStream)10 AttributedString (java.text.AttributedString)10 EditorFont (com.codename1.ui.EditorFont)9