ResourceHelper.java revision ffb42f6c5043de226f02318a1311669d35a90711
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.layoutlib.bridge.impl;
18
19import com.android.layoutlib.api.DensityBasedResourceValue;
20import com.android.layoutlib.api.ResourceDensity;
21import com.android.layoutlib.api.ResourceValue;
22import com.android.layoutlib.bridge.Bridge;
23import com.android.layoutlib.bridge.android.BridgeContext;
24import com.android.layoutlib.bridge.android.BridgeXmlBlockParser;
25import com.android.ninepatch.NinePatch;
26import com.android.ninepatch.NinePatchChunk;
27
28import org.kxml2.io.KXmlParser;
29import org.xmlpull.v1.XmlPullParser;
30import org.xmlpull.v1.XmlPullParserException;
31
32import android.graphics.Bitmap;
33import android.graphics.Bitmap_Delegate;
34import android.graphics.NinePatch_Delegate;
35import android.graphics.Rect;
36import android.graphics.drawable.BitmapDrawable;
37import android.graphics.drawable.ColorDrawable;
38import android.graphics.drawable.Drawable;
39import android.graphics.drawable.NinePatchDrawable;
40import android.util.TypedValue;
41
42import java.io.File;
43import java.io.FileNotFoundException;
44import java.io.FileReader;
45import java.io.IOException;
46import java.net.MalformedURLException;
47import java.util.regex.Matcher;
48import java.util.regex.Pattern;
49
50/**
51 * Helper class to provide various convertion method used in handling android resources.
52 */
53public final class ResourceHelper {
54
55    private final static Pattern sFloatPattern = Pattern.compile("(-?[0-9]+(?:\\.[0-9]+)?)(.*)");
56    private final static float[] sFloatOut = new float[1];
57
58    private final static TypedValue mValue = new TypedValue();
59
60    /**
61     * Returns the color value represented by the given string value
62     * @param value the color value
63     * @return the color as an int
64     * @throw NumberFormatException if the conversion failed.
65     */
66    public static int getColor(String value) {
67        if (value != null) {
68            if (value.startsWith("#") == false) {
69                throw new NumberFormatException();
70            }
71
72            value = value.substring(1);
73
74            // make sure it's not longer than 32bit
75            if (value.length() > 8) {
76                throw new NumberFormatException();
77            }
78
79            if (value.length() == 3) { // RGB format
80                char[] color = new char[8];
81                color[0] = color[1] = 'F';
82                color[2] = color[3] = value.charAt(0);
83                color[4] = color[5] = value.charAt(1);
84                color[6] = color[7] = value.charAt(2);
85                value = new String(color);
86            } else if (value.length() == 4) { // ARGB format
87                char[] color = new char[8];
88                color[0] = color[1] = value.charAt(0);
89                color[2] = color[3] = value.charAt(1);
90                color[4] = color[5] = value.charAt(2);
91                color[6] = color[7] = value.charAt(3);
92                value = new String(color);
93            } else if (value.length() == 6) {
94                value = "FF" + value;
95            }
96
97            // this is a RRGGBB or AARRGGBB value
98
99            // Integer.parseInt will fail to parse strings like "ff191919", so we use
100            // a Long, but cast the result back into an int, since we know that we're only
101            // dealing with 32 bit values.
102            return (int)Long.parseLong(value, 16);
103        }
104
105        throw new NumberFormatException();
106    }
107
108    /**
109     * Returns a drawable from the given value.
110     * @param value The value that contains a path to a 9 patch, a bitmap or a xml based drawable,
111     * or an hexadecimal color
112     * @param context
113     * @param isFramework indicates whether the resource is a framework resources.
114     * Framework resources are cached, and loaded only once.
115     */
116    public static Drawable getDrawable(ResourceValue value, BridgeContext context,
117            boolean isFramework) {
118        Drawable d = null;
119
120        String stringValue = value.getValue();
121
122        String lowerCaseValue = stringValue.toLowerCase();
123
124        if (lowerCaseValue.endsWith(NinePatch.EXTENSION_9PATCH)) {
125            File file = new File(stringValue);
126            if (file.isFile()) {
127                // see if we still have both the chunk and the bitmap in the caches
128                NinePatchChunk chunk = Bridge.getCached9Patch(stringValue,
129                        isFramework ? null : context.getProjectKey());
130                Bitmap bitmap = Bridge.getCachedBitmap(stringValue,
131                        isFramework ? null : context.getProjectKey());
132
133                // if either chunk or bitmap is null, then we reload the 9-patch file.
134                if (chunk == null || bitmap == null) {
135                    try {
136                        NinePatch ninePatch = NinePatch.load(file.toURL(), false /* convert */);
137                        if (ninePatch != null) {
138                            if (chunk == null) {
139                                chunk = ninePatch.getChunk();
140
141                                Bridge.setCached9Patch(stringValue, chunk,
142                                        isFramework ? null : context.getProjectKey());
143                            }
144
145                            if (bitmap == null) {
146                                ResourceDensity density = ResourceDensity.MEDIUM;
147                                if (value instanceof DensityBasedResourceValue) {
148                                    density =
149                                        ((DensityBasedResourceValue)value).getResourceDensity();
150                                }
151
152                                bitmap = Bitmap_Delegate.createBitmap(ninePatch.getImage(),
153                                        false /*isMutable*/,
154                                        density);
155
156                                Bridge.setCachedBitmap(stringValue, bitmap,
157                                        isFramework ? null : context.getProjectKey());
158                            }
159                        }
160                    } catch (MalformedURLException e) {
161                        // URL is wrong, we'll return null below
162                    } catch (IOException e) {
163                        // failed to read the file, we'll return null below.
164                    }
165                }
166
167                if (chunk != null && bitmap != null) {
168                    int[] padding = chunk.getPadding();
169                    Rect paddingRect = new Rect(padding[0], padding[1], padding[2], padding[3]);
170
171                    return new NinePatchDrawable(context.getResources(), bitmap,
172                            NinePatch_Delegate.serialize(chunk),
173                            paddingRect, null);
174                }
175            }
176
177            return null;
178        } else if (lowerCaseValue.endsWith(".xml")) {
179            // create a blockparser for the file
180            File f = new File(stringValue);
181            if (f.isFile()) {
182                try {
183                    // let the framework inflate the Drawable from the XML file.
184                    KXmlParser parser = new KXmlParser();
185                    parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
186                    parser.setInput(new FileReader(f));
187
188                    d = Drawable.createFromXml(context.getResources(),
189                            new BridgeXmlBlockParser(parser, context, isFramework));
190                    return d;
191                } catch (XmlPullParserException e) {
192                    Bridge.getLog().error(null, e);
193                } catch (FileNotFoundException e) {
194                    // will not happen, since we pre-check
195                } catch (IOException e) {
196                    Bridge.getLog().error(null, e);
197                }
198            }
199
200            return null;
201        } else {
202            File bmpFile = new File(stringValue);
203            if (bmpFile.isFile()) {
204                try {
205                    Bitmap bitmap = Bridge.getCachedBitmap(stringValue,
206                            isFramework ? null : context.getProjectKey());
207
208                    if (bitmap == null) {
209                        ResourceDensity density = ResourceDensity.MEDIUM;
210                        if (value instanceof DensityBasedResourceValue) {
211                            density = ((DensityBasedResourceValue)value).getResourceDensity();
212                        }
213
214                        bitmap = Bitmap_Delegate.createBitmap(bmpFile, false /*isMutable*/,
215                                density);
216                        Bridge.setCachedBitmap(stringValue, bitmap,
217                                isFramework ? null : context.getProjectKey());
218                    }
219
220                    return new BitmapDrawable(context.getResources(), bitmap);
221                } catch (IOException e) {
222                    // we'll return null below
223                    // TODO: log the error.
224                }
225            } else {
226                // attempt to get a color from the value
227                try {
228                    int color = getColor(stringValue);
229                    return new ColorDrawable(color);
230                } catch (NumberFormatException e) {
231                    // we'll return null below.
232                    // TODO: log the error
233                }
234            }
235        }
236
237        return null;
238    }
239
240
241    // ------- TypedValue stuff
242    // This is taken from //device/libs/utils/ResourceTypes.cpp
243
244    private static final class UnitEntry {
245        String name;
246        int type;
247        int unit;
248        float scale;
249
250        UnitEntry(String name, int type, int unit, float scale) {
251            this.name = name;
252            this.type = type;
253            this.unit = unit;
254            this.scale = scale;
255        }
256    }
257
258    private final static UnitEntry[] sUnitNames = new UnitEntry[] {
259        new UnitEntry("px", TypedValue.TYPE_DIMENSION, TypedValue.COMPLEX_UNIT_PX, 1.0f),
260        new UnitEntry("dip", TypedValue.TYPE_DIMENSION, TypedValue.COMPLEX_UNIT_DIP, 1.0f),
261        new UnitEntry("dp", TypedValue.TYPE_DIMENSION, TypedValue.COMPLEX_UNIT_DIP, 1.0f),
262        new UnitEntry("sp", TypedValue.TYPE_DIMENSION, TypedValue.COMPLEX_UNIT_SP, 1.0f),
263        new UnitEntry("pt", TypedValue.TYPE_DIMENSION, TypedValue.COMPLEX_UNIT_PT, 1.0f),
264        new UnitEntry("in", TypedValue.TYPE_DIMENSION, TypedValue.COMPLEX_UNIT_IN, 1.0f),
265        new UnitEntry("mm", TypedValue.TYPE_DIMENSION, TypedValue.COMPLEX_UNIT_MM, 1.0f),
266        new UnitEntry("%", TypedValue.TYPE_FRACTION, TypedValue.COMPLEX_UNIT_FRACTION, 1.0f/100),
267        new UnitEntry("%p", TypedValue.TYPE_FRACTION, TypedValue.COMPLEX_UNIT_FRACTION_PARENT, 1.0f/100),
268    };
269
270    /**
271     * Returns the raw value from the given string.
272     * This object is only valid until the next call on to {@link ResourceHelper}.
273     */
274    public static TypedValue getValue(String s) {
275        if (stringToFloat(s, mValue)) {
276            return mValue;
277        }
278
279        return null;
280    }
281
282    /**
283     * Convert the string into a {@link TypedValue}.
284     * @param s
285     * @param outValue
286     * @return true if success.
287     */
288    public static boolean stringToFloat(String s, TypedValue outValue) {
289        // remove the space before and after
290        s.trim();
291        int len = s.length();
292
293        if (len <= 0) {
294            return false;
295        }
296
297        // check that there's no non ascii characters.
298        char[] buf = s.toCharArray();
299        for (int i = 0 ; i < len ; i++) {
300            if (buf[i] > 255) {
301                return false;
302            }
303        }
304
305        // check the first character
306        if (buf[0] < '0' && buf[0] > '9' && buf[0] != '.') {
307            return false;
308        }
309
310        // now look for the string that is after the float...
311        Matcher m = sFloatPattern.matcher(s);
312        if (m.matches()) {
313            String f_str = m.group(1);
314            String end = m.group(2);
315
316            float f;
317            try {
318                f = Float.parseFloat(f_str);
319            } catch (NumberFormatException e) {
320                // this shouldn't happen with the regexp above.
321                return false;
322            }
323
324            if (end.length() > 0 && end.charAt(0) != ' ') {
325                // Might be a unit...
326                if (parseUnit(end, outValue, sFloatOut)) {
327
328                    f *= sFloatOut[0];
329                    boolean neg = f < 0;
330                    if (neg) {
331                        f = -f;
332                    }
333                    long bits = (long)(f*(1<<23)+.5f);
334                    int radix;
335                    int shift;
336                    if ((bits&0x7fffff) == 0) {
337                        // Always use 23p0 if there is no fraction, just to make
338                        // things easier to read.
339                        radix = TypedValue.COMPLEX_RADIX_23p0;
340                        shift = 23;
341                    } else if ((bits&0xffffffffff800000L) == 0) {
342                        // Magnitude is zero -- can fit in 0 bits of precision.
343                        radix = TypedValue.COMPLEX_RADIX_0p23;
344                        shift = 0;
345                    } else if ((bits&0xffffffff80000000L) == 0) {
346                        // Magnitude can fit in 8 bits of precision.
347                        radix = TypedValue.COMPLEX_RADIX_8p15;
348                        shift = 8;
349                    } else if ((bits&0xffffff8000000000L) == 0) {
350                        // Magnitude can fit in 16 bits of precision.
351                        radix = TypedValue.COMPLEX_RADIX_16p7;
352                        shift = 16;
353                    } else {
354                        // Magnitude needs entire range, so no fractional part.
355                        radix = TypedValue.COMPLEX_RADIX_23p0;
356                        shift = 23;
357                    }
358                    int mantissa = (int)(
359                        (bits>>shift) & TypedValue.COMPLEX_MANTISSA_MASK);
360                    if (neg) {
361                        mantissa = (-mantissa) & TypedValue.COMPLEX_MANTISSA_MASK;
362                    }
363                    outValue.data |=
364                        (radix<<TypedValue.COMPLEX_RADIX_SHIFT)
365                        | (mantissa<<TypedValue.COMPLEX_MANTISSA_SHIFT);
366                    return true;
367                }
368                return false;
369            }
370
371            // make sure it's only spaces at the end.
372            end = end.trim();
373
374            if (end.length() == 0) {
375                if (outValue != null) {
376                    outValue.type = TypedValue.TYPE_FLOAT;
377                    outValue.data = Float.floatToIntBits(f);
378                    return true;
379                }
380            }
381        }
382
383        return false;
384    }
385
386    private static boolean parseUnit(String str, TypedValue outValue, float[] outScale) {
387        str = str.trim();
388
389        for (UnitEntry unit : sUnitNames) {
390            if (unit.name.equals(str)) {
391                outValue.type = unit.type;
392                outValue.data = unit.unit << TypedValue.COMPLEX_UNIT_SHIFT;
393                outScale[0] = unit.scale;
394
395                return true;
396            }
397        }
398
399        return false;
400    }
401}
402