ResourceHelper.java revision 2d56b273ef6e2984a4e8914fb67772b173d0a154
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.IDensityBasedResourceValue; 20import com.android.layoutlib.api.IDensityBasedResourceValue.Density; 21import com.android.layoutlib.api.IResourceValue; 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(IResourceValue 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 Density density = Density.MEDIUM; 147 if (value instanceof IDensityBasedResourceValue) { 148 density = ((IDensityBasedResourceValue)value).getDensity(); 149 } 150 151 bitmap = Bitmap_Delegate.createBitmap(ninePatch.getImage(), 152 false /*isMutable*/, 153 density); 154 155 Bridge.setCachedBitmap(stringValue, bitmap, 156 isFramework ? null : context.getProjectKey()); 157 } 158 } 159 } catch (MalformedURLException e) { 160 // URL is wrong, we'll return null below 161 } catch (IOException e) { 162 // failed to read the file, we'll return null below. 163 } 164 } 165 166 if (chunk != null && bitmap != null) { 167 int[] padding = chunk.getPadding(); 168 Rect paddingRect = new Rect(padding[0], padding[1], padding[2], padding[3]); 169 170 return new NinePatchDrawable(context.getResources(), bitmap, 171 NinePatch_Delegate.serialize(chunk), 172 paddingRect, null); 173 } 174 } 175 176 return null; 177 } else if (lowerCaseValue.endsWith(".xml")) { 178 // create a blockparser for the file 179 File f = new File(stringValue); 180 if (f.isFile()) { 181 try { 182 // let the framework inflate the Drawable from the XML file. 183 KXmlParser parser = new KXmlParser(); 184 parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true); 185 parser.setInput(new FileReader(f)); 186 187 d = Drawable.createFromXml(context.getResources(), 188 new BridgeXmlBlockParser(parser, context, isFramework)); 189 return d; 190 } catch (XmlPullParserException e) { 191 context.getLogger().error(e); 192 } catch (FileNotFoundException e) { 193 // will not happen, since we pre-check 194 } catch (IOException e) { 195 context.getLogger().error(e); 196 } 197 } 198 199 return null; 200 } else { 201 File bmpFile = new File(stringValue); 202 if (bmpFile.isFile()) { 203 try { 204 Bitmap bitmap = Bridge.getCachedBitmap(stringValue, 205 isFramework ? null : context.getProjectKey()); 206 207 if (bitmap == null) { 208 Density density = Density.MEDIUM; 209 if (value instanceof IDensityBasedResourceValue) { 210 density = ((IDensityBasedResourceValue)value).getDensity(); 211 } 212 213 bitmap = Bitmap_Delegate.createBitmap(bmpFile, false /*isMutable*/, 214 density); 215 Bridge.setCachedBitmap(stringValue, bitmap, 216 isFramework ? null : context.getProjectKey()); 217 } 218 219 return new BitmapDrawable(context.getResources(), bitmap); 220 } catch (IOException e) { 221 // we'll return null below 222 // TODO: log the error. 223 } 224 } else { 225 // attempt to get a color from the value 226 try { 227 int color = getColor(stringValue); 228 return new ColorDrawable(color); 229 } catch (NumberFormatException e) { 230 // we'll return null below. 231 // TODO: log the error 232 } 233 } 234 } 235 236 return null; 237 } 238 239 240 // ------- TypedValue stuff 241 // This is taken from //device/libs/utils/ResourceTypes.cpp 242 243 private static final class UnitEntry { 244 String name; 245 int type; 246 int unit; 247 float scale; 248 249 UnitEntry(String name, int type, int unit, float scale) { 250 this.name = name; 251 this.type = type; 252 this.unit = unit; 253 this.scale = scale; 254 } 255 } 256 257 private final static UnitEntry[] sUnitNames = new UnitEntry[] { 258 new UnitEntry("px", TypedValue.TYPE_DIMENSION, TypedValue.COMPLEX_UNIT_PX, 1.0f), 259 new UnitEntry("dip", TypedValue.TYPE_DIMENSION, TypedValue.COMPLEX_UNIT_DIP, 1.0f), 260 new UnitEntry("dp", TypedValue.TYPE_DIMENSION, TypedValue.COMPLEX_UNIT_DIP, 1.0f), 261 new UnitEntry("sp", TypedValue.TYPE_DIMENSION, TypedValue.COMPLEX_UNIT_SP, 1.0f), 262 new UnitEntry("pt", TypedValue.TYPE_DIMENSION, TypedValue.COMPLEX_UNIT_PT, 1.0f), 263 new UnitEntry("in", TypedValue.TYPE_DIMENSION, TypedValue.COMPLEX_UNIT_IN, 1.0f), 264 new UnitEntry("mm", TypedValue.TYPE_DIMENSION, TypedValue.COMPLEX_UNIT_MM, 1.0f), 265 new UnitEntry("%", TypedValue.TYPE_FRACTION, TypedValue.COMPLEX_UNIT_FRACTION, 1.0f/100), 266 new UnitEntry("%p", TypedValue.TYPE_FRACTION, TypedValue.COMPLEX_UNIT_FRACTION_PARENT, 1.0f/100), 267 }; 268 269 /** 270 * Returns the raw value from the given string. 271 * This object is only valid until the next call on to {@link ResourceHelper}. 272 */ 273 public static TypedValue getValue(String s) { 274 if (stringToFloat(s, mValue)) { 275 return mValue; 276 } 277 278 return null; 279 } 280 281 /** 282 * Convert the string into a {@link TypedValue}. 283 * @param s 284 * @param outValue 285 * @return true if success. 286 */ 287 public static boolean stringToFloat(String s, TypedValue outValue) { 288 // remove the space before and after 289 s.trim(); 290 int len = s.length(); 291 292 if (len <= 0) { 293 return false; 294 } 295 296 // check that there's no non ascii characters. 297 char[] buf = s.toCharArray(); 298 for (int i = 0 ; i < len ; i++) { 299 if (buf[i] > 255) { 300 return false; 301 } 302 } 303 304 // check the first character 305 if (buf[0] < '0' && buf[0] > '9' && buf[0] != '.') { 306 return false; 307 } 308 309 // now look for the string that is after the float... 310 Matcher m = sFloatPattern.matcher(s); 311 if (m.matches()) { 312 String f_str = m.group(1); 313 String end = m.group(2); 314 315 float f; 316 try { 317 f = Float.parseFloat(f_str); 318 } catch (NumberFormatException e) { 319 // this shouldn't happen with the regexp above. 320 return false; 321 } 322 323 if (end.length() > 0 && end.charAt(0) != ' ') { 324 // Might be a unit... 325 if (parseUnit(end, outValue, sFloatOut)) { 326 327 f *= sFloatOut[0]; 328 boolean neg = f < 0; 329 if (neg) { 330 f = -f; 331 } 332 long bits = (long)(f*(1<<23)+.5f); 333 int radix; 334 int shift; 335 if ((bits&0x7fffff) == 0) { 336 // Always use 23p0 if there is no fraction, just to make 337 // things easier to read. 338 radix = TypedValue.COMPLEX_RADIX_23p0; 339 shift = 23; 340 } else if ((bits&0xffffffffff800000L) == 0) { 341 // Magnitude is zero -- can fit in 0 bits of precision. 342 radix = TypedValue.COMPLEX_RADIX_0p23; 343 shift = 0; 344 } else if ((bits&0xffffffff80000000L) == 0) { 345 // Magnitude can fit in 8 bits of precision. 346 radix = TypedValue.COMPLEX_RADIX_8p15; 347 shift = 8; 348 } else if ((bits&0xffffff8000000000L) == 0) { 349 // Magnitude can fit in 16 bits of precision. 350 radix = TypedValue.COMPLEX_RADIX_16p7; 351 shift = 16; 352 } else { 353 // Magnitude needs entire range, so no fractional part. 354 radix = TypedValue.COMPLEX_RADIX_23p0; 355 shift = 23; 356 } 357 int mantissa = (int)( 358 (bits>>shift) & TypedValue.COMPLEX_MANTISSA_MASK); 359 if (neg) { 360 mantissa = (-mantissa) & TypedValue.COMPLEX_MANTISSA_MASK; 361 } 362 outValue.data |= 363 (radix<<TypedValue.COMPLEX_RADIX_SHIFT) 364 | (mantissa<<TypedValue.COMPLEX_MANTISSA_SHIFT); 365 return true; 366 } 367 return false; 368 } 369 370 // make sure it's only spaces at the end. 371 end = end.trim(); 372 373 if (end.length() == 0) { 374 if (outValue != null) { 375 outValue.type = TypedValue.TYPE_FLOAT; 376 outValue.data = Float.floatToIntBits(f); 377 return true; 378 } 379 } 380 } 381 382 return false; 383 } 384 385 private static boolean parseUnit(String str, TypedValue outValue, float[] outScale) { 386 str = str.trim(); 387 388 for (UnitEntry unit : sUnitNames) { 389 if (unit.name.equals(str)) { 390 outValue.type = unit.type; 391 outValue.data = unit.unit << TypedValue.COMPLEX_UNIT_SHIFT; 392 outScale[0] = unit.scale; 393 394 return true; 395 } 396 } 397 398 return false; 399 } 400} 401