Search in sources :

Example 6 with L10n

use of com.codename1.ui.util.xml.L10n in project CodenameOne by codenameone.

the class EditableResources method openFileWithXMLSupport.

public void openFileWithXMLSupport(File f) throws IOException {
    if (xmlEnabled && f.getParentFile().getName().equals("src")) {
        File res = new File(f.getParentFile().getParentFile(), "res");
        if (res.exists()) {
            File xml = new File(res, f.getName().substring(0, f.getName().length() - 3) + "xml");
            if (xml.exists()) {
                loadingMode = true;
                com.codename1.ui.Font.clearBitmapCache();
                clear();
                try {
                    File resDir = new File(res, f.getName().substring(0, f.getName().length() - 4));
                    // open the XML file...
                    JAXBContext ctx = JAXBContext.newInstance(ResourceFileXML.class);
                    ResourceFileXML xmlData = (ResourceFileXML) ctx.createUnmarshaller().unmarshal(xml);
                    boolean normalize = xmlData.getMajorVersion() > 1 || xmlData.getMinorVersion() > 5;
                    majorVersion = (short) xmlData.getMajorVersion();
                    minorVersion = (short) xmlData.getMinorVersion();
                    xmlUI = xmlData.isUseXmlUI();
                    if (xmlData.getData() != null) {
                        for (Data d : xmlData.getData()) {
                            setResource(d.getName(), MAGIC_DATA, readFile(resDir, d.getName(), normalize));
                        }
                    }
                    if (xmlData.getLegacyFont() != null) {
                        for (LegacyFont d : xmlData.getLegacyFont()) {
                            String name = d.getName();
                            if (normalize) {
                                name = normalizeFileName(name);
                            }
                            DataInputStream fi = new DataInputStream(new FileInputStream(new File(resDir, name)));
                            setResource(d.getName(), MAGIC_FONT, loadFont(fi, d.getName(), false));
                            fi.close();
                        }
                    }
                    if (xmlData.getImage() != null) {
                        for (com.codename1.ui.util.xml.Image d : xmlData.getImage()) {
                            if (d.getType() == null) {
                                // standara JPG or PNG
                                String name = d.getName();
                                if (normalize) {
                                    name = normalizeFileName(name);
                                }
                                FileInputStream fi = new FileInputStream(new File(resDir, name));
                                EncodedImage e = EncodedImage.create(fi);
                                fi.close();
                                setResource(d.getName(), MAGIC_IMAGE, e);
                                continue;
                            }
                            if ("svg".equals(d.getType())) {
                                setResource(d.getName(), MAGIC_IMAGE, Image.createSVG(d.getType(), false, readFile(resDir, d.getName(), normalize)));
                                continue;
                            }
                            if ("timeline".equals(d.getType())) {
                                String name = d.getName();
                                if (normalize) {
                                    name = normalizeFileName(name);
                                }
                                DataInputStream fi = new DataInputStream(new FileInputStream(new File(resDir, name)));
                                setResource(d.getName(), MAGIC_IMAGE, readTimeline(fi));
                                fi.close();
                                continue;
                            }
                            if ("multi".equals(d.getType())) {
                                String name = d.getName();
                                if (normalize) {
                                    name = normalizeFileName(name);
                                }
                                File multiImageDir = new File(resDir, name);
                                File hd4k = new File(multiImageDir, "4k.png");
                                File hd2 = new File(multiImageDir, "2hd.png");
                                File hd560 = new File(multiImageDir, "560.png");
                                File hd = new File(multiImageDir, "hd.png");
                                File veryhigh = new File(multiImageDir, "veryhigh.png");
                                File high = new File(multiImageDir, "high.png");
                                File medium = new File(multiImageDir, "medium.png");
                                File low = new File(multiImageDir, "low.png");
                                File veryLow = new File(multiImageDir, "verylow.png");
                                Map<Integer, EncodedImage> images = new HashMap<Integer, EncodedImage>();
                                if (hd4k.exists()) {
                                    images.put(new Integer(Display.DENSITY_4K), EncodedImage.create(readFileNoNormal(hd4k)));
                                }
                                if (hd2.exists()) {
                                    images.put(new Integer(Display.DENSITY_2HD), EncodedImage.create(readFileNoNormal(hd2)));
                                }
                                if (hd560.exists()) {
                                    images.put(new Integer(Display.DENSITY_560), EncodedImage.create(readFileNoNormal(hd560)));
                                }
                                if (hd.exists()) {
                                    images.put(new Integer(Display.DENSITY_HD), EncodedImage.create(readFileNoNormal(hd)));
                                }
                                if (veryhigh.exists()) {
                                    images.put(new Integer(Display.DENSITY_VERY_HIGH), EncodedImage.create(readFileNoNormal(veryhigh)));
                                }
                                if (high.exists()) {
                                    images.put(new Integer(Display.DENSITY_HIGH), EncodedImage.create(readFileNoNormal(high)));
                                }
                                if (medium.exists()) {
                                    images.put(new Integer(Display.DENSITY_MEDIUM), EncodedImage.create(readFileNoNormal(medium)));
                                }
                                if (low.exists()) {
                                    images.put(new Integer(Display.DENSITY_LOW), EncodedImage.create(readFileNoNormal(low)));
                                }
                                if (veryLow.exists()) {
                                    images.put(new Integer(Display.DENSITY_VERY_LOW), EncodedImage.create(readFileNoNormal(veryLow)));
                                }
                                int[] dpis = new int[images.size()];
                                EncodedImage[] imageArray = new EncodedImage[images.size()];
                                int count = 0;
                                for (Map.Entry<Integer, EncodedImage> m : images.entrySet()) {
                                    dpis[count] = m.getKey().intValue();
                                    imageArray[count] = m.getValue();
                                    count++;
                                }
                                MultiImage result = new MultiImage();
                                result.setDpi(dpis);
                                result.setInternalImages(imageArray);
                                setResource(d.getName(), MAGIC_IMAGE, result);
                                continue;
                            }
                        }
                    }
                    if (xmlData.getL10n() != null) {
                        for (L10n d : xmlData.getL10n()) {
                            Hashtable<String, Hashtable<String, String>> l10n = new Hashtable<String, Hashtable<String, String>>();
                            for (Lang l : d.getLang()) {
                                Hashtable<String, String> language = new Hashtable<String, String>();
                                if (l != null && l.getEntry() != null) {
                                    for (Entry e : l.getEntry()) {
                                        language.put(e.getKey(), e.getValue());
                                    }
                                }
                                l10n.put(l.getName(), language);
                            }
                            setResource(d.getName(), MAGIC_L10N, l10n);
                        }
                    }
                    if (xmlData.getTheme() != null) {
                        for (Theme d : xmlData.getTheme()) {
                            Hashtable<String, Object> theme = new Hashtable<String, Object>();
                            theme.put("uninitialized", Boolean.TRUE);
                            if (d.getVal() != null) {
                                for (Val v : d.getVal()) {
                                    String key = v.getKey();
                                    if (key.endsWith("align") || key.endsWith("textDecoration")) {
                                        theme.put(key, Integer.valueOf(v.getValue()));
                                        continue;
                                    }
                                    if (key.endsWith(Style.BACKGROUND_TYPE) || key.endsWith(Style.BACKGROUND_ALIGNMENT)) {
                                        theme.put(key, Byte.valueOf(v.getValue()));
                                        continue;
                                    }
                                    // padding and or margin type
                                    if (key.endsWith("Unit")) {
                                        String[] s = v.getValue().split(",");
                                        theme.put(key, new byte[] { Byte.parseByte(s[0]), Byte.parseByte(s[1]), Byte.parseByte(s[2]), Byte.parseByte(s[3]) });
                                        continue;
                                    }
                                    theme.put(key, v.getValue());
                                }
                            }
                            if (d.getBorder() != null) {
                                for (com.codename1.ui.util.xml.Border b : d.getBorder()) {
                                    if ("empty".equals(b.getType())) {
                                        theme.put(b.getKey(), Border.createEmpty());
                                        continue;
                                    }
                                    if ("round".equals(b.getType())) {
                                        RoundBorder rb = RoundBorder.create();
                                        rb = rb.color(b.getRoundBorderColor());
                                        rb = rb.rectangle(b.isRectangle());
                                        rb = rb.shadowBlur(b.getShadowBlur());
                                        rb = rb.shadowOpacity(b.getShadowOpacity());
                                        rb = rb.shadowSpread((int) b.getShadowSpread(), b.isShadowMM());
                                        rb = rb.shadowX(b.getShadowX());
                                        rb = rb.shadowY(b.getShadowY());
                                        rb = rb.stroke(b.getStrokeThickness(), b.isStrokeMM());
                                        rb = rb.strokeColor(b.getStrokeColor());
                                        rb = rb.strokeOpacity(b.getStrokeOpacity());
                                        theme.put(b.getKey(), rb);
                                        continue;
                                    }
                                    if ("roundRect".equals(b.getType())) {
                                        RoundRectBorder rb = RoundRectBorder.create();
                                        rb = rb.shadowBlur(b.getShadowBlur());
                                        rb = rb.shadowOpacity(b.getShadowOpacity());
                                        rb = rb.shadowSpread(b.getShadowSpread());
                                        rb = rb.shadowX(b.getShadowX());
                                        rb = rb.shadowY(b.getShadowY());
                                        rb = rb.stroke(b.getStrokeThickness(), b.isStrokeMM());
                                        rb = rb.strokeColor(b.getStrokeColor());
                                        rb = rb.strokeOpacity(b.getStrokeOpacity());
                                        rb = rb.bezierCorners(b.isBezierCorners());
                                        rb = rb.bottomOnlyMode(b.isBottomOnlyMode());
                                        rb = rb.topOnlyMode(b.isTopOnlyMode());
                                        rb = rb.cornerRadius(b.getCornerRadius());
                                        theme.put(b.getKey(), rb);
                                        continue;
                                    }
                                    if ("line".equals(b.getType())) {
                                        if (b.getColor() == null) {
                                            if (b.isMillimeters()) {
                                                theme.put(b.getKey(), Border.createLineBorder(b.getThickness().floatValue()));
                                            } else {
                                                theme.put(b.getKey(), Border.createLineBorder(b.getThickness().intValue()));
                                            }
                                        } else {
                                            if (b.isMillimeters()) {
                                                theme.put(b.getKey(), Border.createLineBorder(b.getThickness().floatValue(), b.getColor().intValue()));
                                            } else {
                                                theme.put(b.getKey(), Border.createLineBorder(b.getThickness().intValue(), b.getColor().intValue()));
                                            }
                                        }
                                        continue;
                                    }
                                    if ("underline".equals(b.getType())) {
                                        if (b.getColor() == null) {
                                            theme.put(b.getKey(), Border.createUndelineBorder(b.getThickness().intValue()));
                                        } else {
                                            theme.put(b.getKey(), Border.createUnderlineBorder(b.getThickness().intValue(), b.getColor().intValue()));
                                        }
                                        continue;
                                    }
                                    if ("rounded".equals(b.getType())) {
                                        if (b.getColor() == null) {
                                            theme.put(b.getKey(), Border.createRoundBorder(b.getArcW().intValue(), b.getArcH().intValue()));
                                        } else {
                                            theme.put(b.getKey(), Border.createRoundBorder(b.getArcW().intValue(), b.getArcH().intValue(), b.getColor().intValue()));
                                        }
                                        continue;
                                    }
                                    if ("etchedRaised".equals(b.getType())) {
                                        if (b.getColor() == null) {
                                            theme.put(b.getKey(), Border.createEtchedRaised());
                                        } else {
                                            theme.put(b.getKey(), Border.createEtchedRaised(b.getColor().intValue(), b.getColorB().intValue()));
                                        }
                                        continue;
                                    }
                                    if ("etchedLowered".equals(b.getType())) {
                                        if (b.getColor() == null) {
                                            theme.put(b.getKey(), Border.createEtchedLowered());
                                        } else {
                                            theme.put(b.getKey(), Border.createEtchedLowered(b.getColor().intValue(), b.getColorB().intValue()));
                                        }
                                        continue;
                                    }
                                    if ("bevelLowered".equals(b.getType())) {
                                        if (b.getColor() == null) {
                                            theme.put(b.getKey(), Border.createBevelLowered());
                                        } else {
                                            theme.put(b.getKey(), Border.createBevelLowered(b.getColor().intValue(), b.getColorB().intValue(), b.getColorC().intValue(), b.getColorD().intValue()));
                                        }
                                        continue;
                                    }
                                    if ("bevelRaised".equals(b.getType())) {
                                        if (b.getColor() == null) {
                                            theme.put(b.getKey(), Border.createBevelRaised());
                                        } else {
                                            theme.put(b.getKey(), Border.createBevelRaised(b.getColor().intValue(), b.getColorB().intValue(), b.getColorC().intValue(), b.getColorD().intValue()));
                                        }
                                        continue;
                                    }
                                    if ("image".equals(b.getType())) {
                                        int imageCount = 2;
                                        if (b.getI9() != null) {
                                            imageCount = 9;
                                        } else {
                                            if (b.getI8() != null) {
                                                imageCount = 8;
                                            } else {
                                                if (b.getI3() != null) {
                                                    imageCount = 3;
                                                }
                                            }
                                        }
                                        String[] borderInstance;
                                        switch(imageCount) {
                                            case 2:
                                                borderInstance = new String[] { b.getI1(), b.getI2() };
                                                break;
                                            case 3:
                                                borderInstance = new String[] { b.getI1(), b.getI2(), b.getI3() };
                                                break;
                                            case 8:
                                                borderInstance = new String[] { b.getI1(), b.getI2(), b.getI3(), b.getI4(), b.getI5(), b.getI6(), b.getI7(), b.getI8() };
                                                break;
                                            default:
                                                borderInstance = new String[] { b.getI1(), b.getI2(), b.getI3(), b.getI4(), b.getI5(), b.getI6(), b.getI7(), b.getI8(), b.getI9() };
                                                break;
                                        }
                                        theme.put(b.getKey(), borderInstance);
                                        continue;
                                    }
                                    if ("imageH".equals(b.getType())) {
                                        theme.put(b.getKey(), new String[] { "h", b.getI1(), b.getI2(), b.getI3() });
                                        continue;
                                    }
                                    if ("imageV".equals(b.getType())) {
                                        theme.put(b.getKey(), new String[] { "v", b.getI1(), b.getI2(), b.getI3() });
                                        continue;
                                    }
                                }
                            }
                            if (d.getFont() != null) {
                                for (com.codename1.ui.util.xml.Font b : d.getFont()) {
                                    if ("ttf".equals(b.getType())) {
                                        com.codename1.ui.Font system = com.codename1.ui.Font.createSystemFont(b.getFace().intValue(), b.getStyle().intValue(), b.getSize().intValue());
                                        EditorTTFFont t;
                                        if (b.getName().startsWith("native:")) {
                                            t = new EditorTTFFont(b.getName(), b.getSizeSettings().intValue(), b.getActualSize().floatValue(), system);
                                        } else {
                                            t = new EditorTTFFont(new File(f.getParentFile(), b.getName()), b.getSizeSettings().intValue(), b.getActualSize().floatValue(), system);
                                        }
                                        theme.put(b.getKey(), t);
                                        continue;
                                    }
                                    if ("system".equals(b.getType())) {
                                        com.codename1.ui.Font system = com.codename1.ui.Font.createSystemFont(b.getFace().intValue(), b.getStyle().intValue(), b.getSize().intValue());
                                        theme.put(b.getKey(), system);
                                        continue;
                                    }
                                // bitmap fonts aren't supported right now
                                }
                            }
                            if (d.getGradient() != null) {
                                for (com.codename1.ui.util.xml.Gradient b : d.getGradient()) {
                                    theme.put(b.getKey(), new Object[] { b.getColor1(), b.getColor2(), b.getPosX(), b.getPosY(), b.getRadius() });
                                }
                            }
                            setResource(d.getName(), MAGIC_THEME, theme);
                        }
                    }
                    // we load the UI last since it might depend on images or other elements in the future
                    if (xmlData.getUi() != null) {
                        if (xmlData.isUseXmlUI()) {
                            ArrayList<ComponentEntry> guiElements = new ArrayList<ComponentEntry>();
                            // place renderers first
                            final ArrayList<String> renderers = new ArrayList<String>();
                            for (Ui d : xmlData.getUi()) {
                                JAXBContext componentContext = JAXBContext.newInstance(ComponentEntry.class);
                                File uiFile = new File(resDir, normalizeFileName(d.getName()) + ".ui");
                                ComponentEntry uiXMLData = (ComponentEntry) componentContext.createUnmarshaller().unmarshal(uiFile);
                                guiElements.add(uiXMLData);
                                uiXMLData.findRendererers(renderers);
                            }
                            Collections.sort(guiElements, new Comparator<ComponentEntry>() {

                                private final ArrayList<String> entries1 = new ArrayList<String>();

                                private final ArrayList<String> entries2 = new ArrayList<String>();

                                @Override
                                public int compare(ComponentEntry o1, ComponentEntry o2) {
                                    if (renderers.contains(o1.getName())) {
                                        return -1;
                                    }
                                    if (renderers.contains(o2.getName())) {
                                        return 1;
                                    }
                                    entries1.clear();
                                    entries2.clear();
                                    o1.findEmbeddedDependencies(entries1);
                                    o2.findEmbeddedDependencies(entries2);
                                    if (entries1.size() == 0) {
                                        if (entries2.size() == 0) {
                                            return 0;
                                        }
                                        return -1;
                                    } else {
                                        if (entries2.size() == 0) {
                                            return 1;
                                        }
                                    }
                                    for (String e : entries1) {
                                        if (e.equals(o2.getName())) {
                                            return 1;
                                        }
                                    }
                                    for (String e : entries2) {
                                        if (e.equals(o1.getName())) {
                                            return -1;
                                        }
                                    }
                                    return 0;
                                }
                            });
                            for (ComponentEntry uiXMLData : guiElements) {
                                UIBuilderOverride uib = new UIBuilderOverride();
                                com.codename1.ui.Container cnt = uib.createInstance(uiXMLData, this);
                                // encountered an error loading the component fallback to loading with the binary types
                                if (cnt == null) {
                                    for (Ui ui : xmlData.getUi()) {
                                        setResource(uiXMLData.getName(), MAGIC_UI, readFile(resDir, ui.getName(), normalize));
                                    }
                                    break;
                                } else {
                                    byte[] data = UserInterfaceEditor.persistContainer(cnt, this);
                                    setResource(uiXMLData.getName(), MAGIC_UI, data);
                                }
                            }
                        } else {
                            for (Ui d : xmlData.getUi()) {
                                setResource(d.getName(), MAGIC_UI, readFile(resDir, d.getName(), normalize));
                            }
                        }
                    }
                    loadingMode = false;
                    modified = false;
                    updateModified();
                    // can occure when a resource file is opened via the constructor
                    if (undoQueue != null) {
                        undoQueue.clear();
                        redoQueue.clear();
                    }
                    return;
                } catch (JAXBException err) {
                    err.printStackTrace();
                }
            }
        }
    }
    openFile(new FileInputStream(f));
}
Also used : Val(com.codename1.ui.util.xml.Val) LegacyFont(com.codename1.ui.util.xml.LegacyFont) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) EditorTTFFont(com.codename1.ui.EditorTTFFont) ComponentEntry(com.codename1.ui.util.xml.comps.ComponentEntry) ResourceFileXML(com.codename1.ui.util.xml.ResourceFileXML) JAXBException(javax.xml.bind.JAXBException) Lang(com.codename1.ui.util.xml.Lang) FileInputStream(java.io.FileInputStream) Ui(com.codename1.ui.util.xml.Ui) AnimationObject(com.codename1.ui.animations.AnimationObject) RoundBorder(com.codename1.ui.plaf.RoundBorder) File(java.io.File) Map(java.util.Map) HashMap(java.util.HashMap) L10n(com.codename1.ui.util.xml.L10n) JAXBContext(javax.xml.bind.JAXBContext) Entry(com.codename1.ui.util.xml.Entry) ComponentEntry(com.codename1.ui.util.xml.comps.ComponentEntry) RoundRectBorder(com.codename1.ui.plaf.RoundRectBorder) Hashtable(java.util.Hashtable) Data(com.codename1.ui.util.xml.Data) DataInputStream(java.io.DataInputStream) EncodedImage(com.codename1.ui.EncodedImage) Theme(com.codename1.ui.util.xml.Theme)

Example 7 with L10n

use of com.codename1.ui.util.xml.L10n in project CodenameOne by codenameone.

the class EditableResources method save.

/**
 * Allows us to store a modified resource file
 */
public void save(OutputStream out) throws IOException {
    if (overrideFile != null) {
        overrideResource.save(new FileOutputStream(overrideFile));
    }
    // disable override for the duration of the save so stuff from the override doesn't
    // get into the main resource file
    File overrideFileBackup = overrideFile;
    EditableResources overrideResourceBackup = overrideResource;
    overrideResource = null;
    overrideFile = null;
    try {
        DataOutputStream output = new DataOutputStream(out);
        String[] resourceNames = getResourceNames();
        keyOffset = 0;
        if (currentPassword != null) {
            output.writeShort(resourceNames.length + 2);
            output.writeByte(MAGIC_PASSWORD);
            output.writeUTF("" + ((char) encode('l')) + ((char) encode('w')));
            output.writeByte(encode(MAGIC_HEADER & 0xff));
        } else {
            output.writeShort(resourceNames.length + 1);
            // write the header of the resource file
            output.writeByte(MAGIC_HEADER);
        }
        output.writeUTF("");
        // the size of the header
        output.writeShort(6);
        output.writeShort(MAJOR_VERSION);
        output.writeShort(MINOR_VERSION);
        // currently resource file meta-data isn't supported
        output.writeShort(0);
        for (int iter = 0; iter < resourceNames.length; iter++) {
            // write the magic number
            byte magic = getResourceType(resourceNames[iter]);
            switch(magic) {
                case MAGIC_TIMELINE:
                case MAGIC_ANIMATION_LEGACY:
                case MAGIC_IMAGE_LEGACY:
                case MAGIC_INDEXED_IMAGE_LEGACY:
                    magic = MAGIC_IMAGE;
                    break;
                case MAGIC_THEME_LEGACY:
                    magic = MAGIC_THEME;
                    break;
                case MAGIC_FONT_LEGACY:
                    magic = MAGIC_FONT;
                    break;
            }
            if (currentPassword != null) {
                output.writeByte(encode(magic & 0xff));
                char[] chars = resourceNames[iter].toCharArray();
                for (int i = 0; i < chars.length; i++) {
                    chars[i] = (char) encode(chars[i] & 0xffff);
                }
                output.writeUTF(new String(chars));
            } else {
                output.writeByte(magic);
                output.writeUTF(resourceNames[iter]);
            }
            switch(magic) {
                case MAGIC_IMAGE:
                    Object o = getResourceObject(resourceNames[iter]);
                    if (!(o instanceof MultiImage)) {
                        o = null;
                    }
                    saveImage(output, getImage(resourceNames[iter]), (MultiImage) o, BufferedImage.TYPE_INT_ARGB);
                    continue;
                case MAGIC_THEME:
                    saveTheme(output, getTheme(resourceNames[iter]), magic == MAGIC_THEME_LEGACY);
                    continue;
                case MAGIC_FONT:
                    saveFont(output, false, resourceNames[iter]);
                    continue;
                case MAGIC_DATA:
                    {
                        InputStream i = getData(resourceNames[iter]);
                        ByteArrayOutputStream outArray = new ByteArrayOutputStream();
                        int val = i.read();
                        while (val != -1) {
                            outArray.write(val);
                            val = i.read();
                        }
                        byte[] data = outArray.toByteArray();
                        output.writeInt(data.length);
                        output.write(data);
                        continue;
                    }
                case MAGIC_UI:
                    {
                        InputStream i = getUi(resourceNames[iter]);
                        ByteArrayOutputStream outArray = new ByteArrayOutputStream();
                        int val = i.read();
                        while (val != -1) {
                            outArray.write(val);
                            val = i.read();
                        }
                        byte[] data = outArray.toByteArray();
                        output.writeInt(data.length);
                        output.write(data);
                        continue;
                    }
                case MAGIC_L10N:
                    // we are getting the theme which allows us to acces the l10n data
                    saveL10N(output, getTheme(resourceNames[iter]));
                    continue;
                default:
                    throw new IOException("Corrupt theme file unrecognized magic number: " + Integer.toHexString(magic & 0xff));
            }
        }
        modified = false;
        updateModified();
        undoQueue.clear();
        redoQueue.clear();
    } finally {
        overrideFile = overrideFileBackup;
        overrideResource = overrideResourceBackup;
    }
}
Also used : DataOutputStream(java.io.DataOutputStream) DataInputStream(java.io.DataInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) FileOutputStream(java.io.FileOutputStream) AnimationObject(com.codename1.ui.animations.AnimationObject) File(java.io.File)

Example 8 with L10n

use of com.codename1.ui.util.xml.L10n in project CodenameOne by codenameone.

the class EditableResources method saveL10N.

private void saveL10N(DataOutputStream output, Hashtable l10n) throws IOException {
    List keys = new ArrayList();
    for (Object locale : l10n.keySet()) {
        Hashtable current = (Hashtable) l10n.get(locale);
        for (Object key : current.keySet()) {
            if (!keys.contains(key)) {
                keys.add(key);
            }
        }
    }
    output.writeShort(keys.size());
    output.writeShort(l10n.size());
    for (Object key : keys) {
        output.writeUTF((String) key);
    }
    for (Object locale : l10n.keySet()) {
        Hashtable currentLanguage = (Hashtable) l10n.get(locale);
        output.writeUTF((String) locale);
        for (Object key : keys) {
            String k = (String) currentLanguage.get(key);
            if (k != null) {
                output.writeUTF(k);
            } else {
                output.writeUTF("");
            }
        }
    }
}
Also used : Hashtable(java.util.Hashtable) ArrayList(java.util.ArrayList) List(java.util.List) ArrayList(java.util.ArrayList) AnimationObject(com.codename1.ui.animations.AnimationObject)

Example 9 with L10n

use of com.codename1.ui.util.xml.L10n in project CodenameOne by codenameone.

the class L10nEditor method importResourceActionPerformed.

// GEN-LAST:event_exportResourceActionPerformed
private void importResourceActionPerformed(java.awt.event.ActionEvent evt) {
    // GEN-FIRST:event_importResourceActionPerformed
    final String locale = (String) locales.getSelectedItem();
    int val = JOptionPane.showConfirmDialog(this, "This will overwrite existing values for " + locale + "\nAre you sure?", "Import", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
    if (val == JOptionPane.YES_OPTION) {
        File[] files = ResourceEditorView.showOpenFileChooser("Properties, XML, CSV", "prop", "properties", "l10n", "locale", "xml", "csv");
        if (files != null) {
            FileInputStream f = null;
            try {
                f = new FileInputStream(files[0]);
                if (files[0].getName().toLowerCase().endsWith("xml")) {
                    SAXParserFactory spf = SAXParserFactory.newInstance();
                    SAXParser saxParser = spf.newSAXParser();
                    XMLReader xmlReader = saxParser.getXMLReader();
                    xmlReader.setErrorHandler(new ErrorHandler() {

                        public void warning(SAXParseException exception) throws SAXException {
                            exception.printStackTrace();
                        }

                        public void error(SAXParseException exception) throws SAXException {
                            exception.printStackTrace();
                        }

                        public void fatalError(SAXParseException exception) throws SAXException {
                            exception.printStackTrace();
                        }
                    });
                    xmlReader.setContentHandler(new ContentHandler() {

                        private String currentName;

                        private StringBuilder chars = new StringBuilder();

                        @Override
                        public void setDocumentLocator(Locator locator) {
                        }

                        @Override
                        public void startDocument() throws SAXException {
                        }

                        @Override
                        public void endDocument() throws SAXException {
                        }

                        @Override
                        public void startPrefixMapping(String prefix, String uri) throws SAXException {
                        }

                        @Override
                        public void endPrefixMapping(String prefix) throws SAXException {
                        }

                        @Override
                        public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
                            if ("string".equals(localName) || "string".equals(qName)) {
                                currentName = atts.getValue("name");
                                chars.setLength(0);
                            }
                        }

                        @Override
                        public void endElement(String uri, String localName, String qName) throws SAXException {
                            if ("string".equals(localName) || "string".equals(qName)) {
                                String str = chars.toString();
                                if (str.startsWith("\"") && str.endsWith("\"")) {
                                    str = str.substring(1);
                                    str = str.substring(0, str.length() - 1);
                                    res.setLocaleProperty(localeName, locale, currentName, str);
                                    return;
                                }
                                str = str.replace("\\'", "'");
                                res.setLocaleProperty(localeName, locale, currentName, str);
                            }
                        }

                        @Override
                        public void characters(char[] ch, int start, int length) throws SAXException {
                            chars.append(ch, start, length);
                        }

                        @Override
                        public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
                        }

                        @Override
                        public void processingInstruction(String target, String data) throws SAXException {
                        }

                        @Override
                        public void skippedEntity(String name) throws SAXException {
                        }
                    });
                    xmlReader.parse(new InputSource(new InputStreamReader(f, "UTF-8")));
                } else {
                    if (files[0].getName().toLowerCase().endsWith("csv")) {
                        CSVParserOptions po = new CSVParserOptions(this);
                        if (po.isCanceled()) {
                            f.close();
                            return;
                        }
                        CSVParser p = new CSVParser(po.getDelimiter());
                        String[][] data = p.parse(new InputStreamReader(f, po.getEncoding()));
                        for (int iter = 1; iter < data.length; iter++) {
                            if (data[iter].length > 0) {
                                String key = data[iter][0];
                                for (int col = 1; col < data[iter].length; col++) {
                                    if (res.getL10N(localeName, data[0][col]) == null) {
                                        res.addLocale(localeName, data[0][col]);
                                    }
                                    res.setLocaleProperty(localeName, data[0][col], key, data[iter][col]);
                                }
                            }
                        }
                    } else {
                        Properties prop = new Properties();
                        prop.load(f);
                        for (Object key : prop.keySet()) {
                            res.setLocaleProperty(localeName, locale, (String) key, prop.getProperty((String) key));
                        }
                    }
                }
                f.close();
                initLocaleList();
                for (Object localeObj : localeList) {
                    Hashtable current = res.getL10N(localeName, (String) localeObj);
                    for (Object key : current.keySet()) {
                        if (!keys.contains(key)) {
                            keys.add(key);
                        }
                    }
                }
                Collections.sort(keys);
                initTable();
            } catch (Exception ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(this, "Error: " + ex, "Error Occured", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
}
Also used : InputSource(org.xml.sax.InputSource) Attributes(org.xml.sax.Attributes) Properties(java.util.Properties) ContentHandler(org.xml.sax.ContentHandler) SAXException(org.xml.sax.SAXException) Locator(org.xml.sax.Locator) SAXParseException(org.xml.sax.SAXParseException) SAXParser(javax.xml.parsers.SAXParser) UIBuilderOverride(com.codename1.ui.util.UIBuilderOverride) XMLReader(org.xml.sax.XMLReader) ErrorHandler(org.xml.sax.ErrorHandler) InputStreamReader(java.io.InputStreamReader) Hashtable(java.util.Hashtable) FileInputStream(java.io.FileInputStream) SAXException(org.xml.sax.SAXException) IOException(java.io.IOException) SAXParseException(org.xml.sax.SAXParseException) CSVParser(com.codename1.io.CSVParser) EventObject(java.util.EventObject) File(java.io.File) SAXParserFactory(javax.xml.parsers.SAXParserFactory)

Example 10 with L10n

use of com.codename1.ui.util.xml.L10n in project CodenameOne by codenameone.

the class AddResourceDialog method addResource.

public String addResource(EditableResources res, ResourceEditorView view) {
    // "Image", "Animation", "Font", "Theme", "Data", "Localization (L10N)"
    String newName = name.getText();
    for (String r : res.getResourceNames()) {
        if (r.equalsIgnoreCase(newName)) {
            JOptionPane.showMessageDialog(this, "A resource called: " + newName + " already exists\nYou must delete the resource first.", "Add Resource", JOptionPane.ERROR_MESSAGE);
            return null;
        }
    }
    switch(type.getSelectedIndex()) {
        case // image
        IMAGE:
            ImageRGBEditor imageEditor = new ImageRGBEditor(res, name.getText(), view);
            imageEditor.selectFile();
            view.setSelectedResource(name.getText());
            break;
        case MULTI_IMAGE:
            ImageMultiEditor multiImageEditor = new ImageMultiEditor(res, name.getText(), view);
            view.setSelectedResource(name.getText());
            break;
        case TIMELINE:
            new TimelineEditor(res, name.getText(), view);
            view.setSelectedResource(name.getText());
            break;
        case // animation
        ANIMATION:
            TimelineEditor.selectFile(view, res, name.getText());
            /*ImageEditor animationEditor = new ImageEditor(res, name.getText());
                animationEditor.setAnimation(true);
                animationEditor.selectFile(view);*/
            break;
        case // font
        FONT:
            new FontEditor(res, new EditorFont(com.codename1.ui.Font.createSystemFont(com.codename1.ui.Font.FACE_SYSTEM, com.codename1.ui.Font.STYLE_PLAIN, com.codename1.ui.Font.SIZE_MEDIUM), null, "Arial-plain-12", true, RenderingHints.VALUE_TEXT_ANTIALIAS_ON, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,;:!@/\\*()[]{}|#$%^&<>?'\"+- "), name.getText()).createFont();
            view.setSelectedResource(name.getText());
            break;
        case // theme
        THEME:
            res.setTheme(name.getText(), new Hashtable());
            view.setSelectedResource(name.getText());
            // ResourceEditorView.expandAndSelect(tree, name.getText());
            break;
        case // data
        DATA:
            DataEditor dataEditor = new DataEditor(res, name.getText());
            dataEditor.selectDataFile(view);
            view.setSelectedResource(name.getText());
            break;
        case // localization
        LOCALIZATION:
            Hashtable h = new Hashtable();
            Hashtable local = new Hashtable();
            local.put("cancel", "Cancel");
            local.put("ok", "OK");
            local.put("menu", "Menu");
            local.put("select", "Select");
            local.put("edit", "Edit");
            h.put("en", local);
            res.setL10N(name.getText(), h);
            view.setSelectedResource(name.getText());
            // ResourceEditorView.expandAndSelect(tree, name.getText());
            break;
        case UI:
            UserInterfaceEditor uiEditor = new UserInterfaceEditor(name.getText(), res, view.getProjectGeneratorSettings(), view);
            view.setSelectedResource(name.getText());
            break;
    }
    return name.getText();
}
Also used : Hashtable(java.util.Hashtable) EditorFont(com.codename1.ui.EditorFont)

Aggregations

L10NManager (com.codename1.l10n.L10NManager)4 AnimationObject (com.codename1.ui.animations.AnimationObject)4 File (java.io.File)4 FileInputStream (java.io.FileInputStream)4 Hashtable (java.util.Hashtable)4 EncodedImage (com.codename1.ui.EncodedImage)3 DataInputStream (java.io.DataInputStream)3 IOException (java.io.IOException)3 ArrayList (java.util.ArrayList)3 Date (java.util.Date)3 Locale (java.util.Locale)3 EditorFont (com.codename1.ui.EditorFont)2 EditorTTFFont (com.codename1.ui.EditorTTFFont)2 Image (com.codename1.ui.Image)2 RoundBorder (com.codename1.ui.plaf.RoundBorder)2 RoundRectBorder (com.codename1.ui.plaf.RoundRectBorder)2 LegacyFont (com.codename1.ui.util.xml.LegacyFont)2 BufferedImage (java.awt.image.BufferedImage)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 DataOutputStream (java.io.DataOutputStream)2