Bridge.java revision 2473ef5654b2a4b65132a35677c6ddfd481aab2c
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; 18 19import com.android.internal.util.XmlUtils; 20import com.android.layoutlib.api.ILayoutBridge; 21import com.android.layoutlib.api.ILayoutLog; 22import com.android.layoutlib.api.ILayoutResult; 23import com.android.layoutlib.api.IProjectCallback; 24import com.android.layoutlib.api.IResourceValue; 25import com.android.layoutlib.api.IStyleResourceValue; 26import com.android.layoutlib.api.IXmlPullParser; 27import com.android.layoutlib.api.ILayoutResult.ILayoutViewInfo; 28import com.android.layoutlib.bridge.LayoutResult.LayoutViewInfo; 29import com.android.ninepatch.NinePatch; 30import com.android.tools.layoutlib.create.MethodAdapter; 31import com.android.tools.layoutlib.create.OverrideMethod; 32 33import android.graphics.Bitmap; 34import android.graphics.Canvas; 35import android.graphics.Rect; 36import android.graphics.Region; 37import android.graphics.Typeface; 38import android.graphics.drawable.Drawable; 39import android.os.Handler; 40import android.os.IBinder; 41import android.os.Looper; 42import android.os.ParcelFileDescriptor; 43import android.os.RemoteException; 44import android.util.DisplayMetrics; 45import android.util.TypedValue; 46import android.view.BridgeInflater; 47import android.view.IWindow; 48import android.view.IWindowSession; 49import android.view.KeyEvent; 50import android.view.MotionEvent; 51import android.view.Surface; 52import android.view.SurfaceView; 53import android.view.View; 54import android.view.ViewGroup; 55import android.view.View.AttachInfo; 56import android.view.View.MeasureSpec; 57import android.view.WindowManager.LayoutParams; 58import android.widget.FrameLayout; 59import android.widget.TabHost; 60import android.widget.TabWidget; 61 62import java.lang.ref.SoftReference; 63import java.lang.reflect.Field; 64import java.lang.reflect.Modifier; 65import java.util.Collection; 66import java.util.HashMap; 67import java.util.Map; 68 69/** 70 * Main entry point of the LayoutLib Bridge. 71 * <p/>To use this bridge, simply instantiate an object of type {@link Bridge} and call 72 * {@link #computeLayout(IXmlPullParser, Object, int, int, String, boolean, Map, Map, IProjectCallback, ILayoutLog)}. 73 */ 74public final class Bridge implements ILayoutBridge { 75 76 private static final int DEFAULT_TITLE_BAR_HEIGHT = 25; 77 private static final int DEFAULT_STATUS_BAR_HEIGHT = 25; 78 79 public static class StaticMethodNotImplementedException extends RuntimeException { 80 private static final long serialVersionUID = 1L; 81 82 public StaticMethodNotImplementedException(String msg) { 83 super(msg); 84 } 85 } 86 87 /** 88 * Maps from id to resource name/type. This is for android.R only. 89 */ 90 private final static Map<Integer, String[]> sRMap = new HashMap<Integer, String[]>(); 91 /** 92 * Same as sRMap except for int[] instead of int resources. This is for android.R only. 93 */ 94 private final static Map<int[], String> sRArrayMap = new HashMap<int[], String>(); 95 /** 96 * Reverse map compared to sRMap, resource type -> (resource name -> id). 97 * This is for android.R only. 98 */ 99 private final static Map<String, Map<String, Integer>> sRFullMap = 100 new HashMap<String, Map<String,Integer>>(); 101 102 private final static Map<Object, Map<String, SoftReference<Bitmap>>> sProjectBitmapCache = 103 new HashMap<Object, Map<String, SoftReference<Bitmap>>>(); 104 private final static Map<Object, Map<String, SoftReference<NinePatch>>> sProject9PatchCache = 105 new HashMap<Object, Map<String, SoftReference<NinePatch>>>(); 106 107 private final static Map<String, SoftReference<Bitmap>> sFrameworkBitmapCache = 108 new HashMap<String, SoftReference<Bitmap>>(); 109 private final static Map<String, SoftReference<NinePatch>> sFramework9PatchCache = 110 new HashMap<String, SoftReference<NinePatch>>(); 111 112 private static Map<String, Map<String, Integer>> sEnumValueMap; 113 114 /** 115 * A default logger than prints to stdout/stderr. 116 */ 117 private final static ILayoutLog sDefaultLogger = new ILayoutLog() { 118 public void error(String message) { 119 System.err.println(message); 120 } 121 122 public void error(Throwable t) { 123 String message = t.getMessage(); 124 if (message == null) { 125 message = t.getClass().getName(); 126 } 127 128 System.err.println(message); 129 } 130 131 public void warning(String message) { 132 System.out.println(message); 133 } 134 }; 135 136 /** 137 * Logger defined during a compute layout operation. 138 * <p/> 139 * This logger is generally set to {@link #sDefaultLogger} except during rendering 140 * operations when it might be set to a specific provided logger. 141 * <p/> 142 * To change this value, use a block synchronized on {@link #sDefaultLogger}. 143 */ 144 private static ILayoutLog sLogger = sDefaultLogger; 145 146 /* 147 * (non-Javadoc) 148 * @see com.android.layoutlib.api.ILayoutBridge#getApiLevel() 149 */ 150 public int getApiLevel() { 151 return API_CURRENT; 152 } 153 154 /* 155 * (non-Javadoc) 156 * @see com.android.layoutlib.api.ILayoutLibBridge#init(java.lang.String, java.util.Map) 157 */ 158 public boolean init( 159 String fontOsLocation, Map<String, Map<String, Integer>> enumValueMap) { 160 161 return sinit(fontOsLocation, enumValueMap); 162 } 163 164 private static synchronized boolean sinit(String fontOsLocation, 165 Map<String, Map<String, Integer>> enumValueMap) { 166 167 // When DEBUG_LAYOUT is set and is not 0 or false, setup a default listener 168 // on static (native) methods which prints the signature on the console and 169 // throws an exception. 170 // This is useful when testing the rendering in ADT to identify static native 171 // methods that are ignored -- layoutlib_create makes them returns 0/false/null 172 // which is generally OK yet might be a problem, so this is how you'd find out. 173 // 174 // Currently layoutlib_create only overrides static native method. 175 // Static non-natives are not overridden and thus do not get here. 176 final String debug = System.getenv("DEBUG_LAYOUT"); 177 if (debug != null && !debug.equals("0") && !debug.equals("false")) { 178 179 OverrideMethod.setDefaultListener(new MethodAdapter() { 180 @Override 181 public void onInvokeV(String signature, boolean isNative, Object caller) { 182 if (sLogger != null) { 183 synchronized (sDefaultLogger) { 184 sLogger.error("Missing Stub: " + signature + 185 (isNative ? " (native)" : "")); 186 } 187 } 188 189 if (debug.equalsIgnoreCase("throw")) { 190 // Throwing this exception doesn't seem that useful. It breaks 191 // the layout editor yet doesn't display anything meaningful to the 192 // user. Having the error in the console is just as useful. We'll 193 // throw it only if the environment variable is "throw" or "THROW". 194 throw new StaticMethodNotImplementedException(signature); 195 } 196 } 197 }); 198 } 199 200 // Override View.isInEditMode to return true. 201 // 202 // This allows custom views that are drawn in the Graphical Layout Editor to adapt their 203 // rendering for preview. Most important this let custom views know that they can't expect 204 // the rest of their activities to be alive. 205 OverrideMethod.setMethodListener("android.view.View#isInEditMode()Z", 206 new MethodAdapter() { 207 @Override 208 public int onInvokeI(String signature, boolean isNative, Object caller) { 209 return 1; 210 } 211 } 212 ); 213 214 // load the fonts. 215 FontLoader fontLoader = FontLoader.create(fontOsLocation); 216 if (fontLoader != null) { 217 Typeface.init(fontLoader); 218 } else { 219 return false; 220 } 221 222 sEnumValueMap = enumValueMap; 223 224 // now parse com.android.internal.R (and only this one as android.R is a subset of 225 // the internal version), and put the content in the maps. 226 try { 227 // WARNING: this only works because the class is already loaded, and therefore 228 // the objects returned by Field.get() are the same as the ones used by 229 // the code accessing the R class. 230 // int[] does not implement equals/hashCode, and if the parsing used a different class 231 // loader for the R class, this would NOT work. 232 Class<?> r = com.android.internal.R.class; 233 234 for (Class<?> inner : r.getDeclaredClasses()) { 235 String resType = inner.getSimpleName(); 236 237 Map<String, Integer> fullMap = new HashMap<String, Integer>(); 238 sRFullMap.put(resType, fullMap); 239 240 for (Field f : inner.getDeclaredFields()) { 241 // only process static final fields. Since the final attribute may have 242 // been altered by layoutlib_create, we only check static 243 int modifiers = f.getModifiers(); 244 if (Modifier.isStatic(modifiers)) { 245 Class<?> type = f.getType(); 246 if (type.isArray() && type.getComponentType() == int.class) { 247 // if the object is an int[] we put it in sRArrayMap 248 sRArrayMap.put((int[]) f.get(null), f.getName()); 249 } else if (type == int.class) { 250 Integer value = (Integer) f.get(null); 251 sRMap.put(value, new String[] { f.getName(), resType }); 252 fullMap.put(f.getName(), value); 253 } else { 254 assert false; 255 } 256 } 257 } 258 } 259 } catch (IllegalArgumentException e) { 260 // FIXME: log/return the error (there's no logger object at this point!) 261 e.printStackTrace(); 262 return false; 263 } catch (IllegalAccessException e) { 264 e.printStackTrace(); 265 return false; 266 } 267 268 return true; 269 } 270 271 /* 272 * For compatilibty purposes, we implement the old deprecated version of computeLayout. 273 * (non-Javadoc) 274 * @see com.android.layoutlib.api.ILayoutBridge#computeLayout(com.android.layoutlib.api.IXmlPullParser, java.lang.Object, int, int, java.lang.String, java.util.Map, java.util.Map, com.android.layoutlib.api.IProjectCallback, com.android.layoutlib.api.ILayoutLog) 275 */ 276 @Deprecated 277 public ILayoutResult computeLayout(IXmlPullParser layoutDescription, 278 Object projectKey, 279 int screenWidth, int screenHeight, String themeName, 280 Map<String, Map<String, IResourceValue>> projectResources, 281 Map<String, Map<String, IResourceValue>> frameworkResources, 282 IProjectCallback customViewLoader, ILayoutLog logger) { 283 boolean isProjectTheme = false; 284 if (themeName.charAt(0) == '*') { 285 themeName = themeName.substring(1); 286 isProjectTheme = true; 287 } 288 289 return computeLayout(layoutDescription, projectKey, 290 screenWidth, screenHeight, DisplayMetrics.DENSITY_DEFAULT, 291 DisplayMetrics.DENSITY_DEFAULT, DisplayMetrics.DENSITY_DEFAULT, 292 themeName, isProjectTheme, 293 projectResources, frameworkResources, customViewLoader, logger); 294 } 295 296 /* 297 * For compatilibty purposes, we implement the old deprecated version of computeLayout. 298 * (non-Javadoc) 299 * @see com.android.layoutlib.api.ILayoutBridge#computeLayout(com.android.layoutlib.api.IXmlPullParser, java.lang.Object, int, int, java.lang.String, boolean, java.util.Map, java.util.Map, com.android.layoutlib.api.IProjectCallback, com.android.layoutlib.api.ILayoutLog) 300 */ 301 @Deprecated 302 public ILayoutResult computeLayout(IXmlPullParser layoutDescription, Object projectKey, 303 int screenWidth, int screenHeight, String themeName, boolean isProjectTheme, 304 Map<String, Map<String, IResourceValue>> projectResources, 305 Map<String, Map<String, IResourceValue>> frameworkResources, 306 IProjectCallback customViewLoader, ILayoutLog logger) { 307 return computeLayout(layoutDescription, projectKey, 308 screenWidth, screenHeight, DisplayMetrics.DENSITY_DEFAULT, 309 DisplayMetrics.DENSITY_DEFAULT, DisplayMetrics.DENSITY_DEFAULT, 310 themeName, isProjectTheme, 311 projectResources, frameworkResources, customViewLoader, logger); 312 } 313 314 /* 315 * (non-Javadoc) 316 * @see com.android.layoutlib.api.ILayoutBridge#computeLayout(com.android.layoutlib.api.IXmlPullParser, java.lang.Object, int, int, int, float, float, java.lang.String, boolean, java.util.Map, java.util.Map, com.android.layoutlib.api.IProjectCallback, com.android.layoutlib.api.ILayoutLog) 317 */ 318 public ILayoutResult computeLayout(IXmlPullParser layoutDescription, Object projectKey, 319 int screenWidth, int screenHeight, int density, float xdpi, float ydpi, 320 String themeName, boolean isProjectTheme, 321 Map<String, Map<String, IResourceValue>> projectResources, 322 Map<String, Map<String, IResourceValue>> frameworkResources, 323 IProjectCallback customViewLoader, ILayoutLog logger) { 324 if (logger == null) { 325 logger = sDefaultLogger; 326 } 327 328 synchronized (sDefaultLogger) { 329 sLogger = logger; 330 } 331 332 // find the current theme and compute the style inheritance map 333 Map<IStyleResourceValue, IStyleResourceValue> styleParentMap = 334 new HashMap<IStyleResourceValue, IStyleResourceValue>(); 335 336 IStyleResourceValue currentTheme = computeStyleMaps(themeName, isProjectTheme, 337 projectResources.get(BridgeConstants.RES_STYLE), 338 frameworkResources.get(BridgeConstants.RES_STYLE), styleParentMap); 339 340 BridgeContext context = null; 341 try { 342 // setup the display Metrics. 343 DisplayMetrics metrics = new DisplayMetrics(); 344 metrics.density = density / (float) DisplayMetrics.DENSITY_DEFAULT; 345 metrics.scaledDensity = metrics.density; 346 metrics.widthPixels = screenWidth; 347 metrics.heightPixels = screenHeight; 348 metrics.xdpi = xdpi; 349 metrics.ydpi = ydpi; 350 351 context = new BridgeContext(projectKey, metrics, currentTheme, projectResources, 352 frameworkResources, styleParentMap, customViewLoader, logger); 353 BridgeInflater inflater = new BridgeInflater(context, customViewLoader); 354 context.setBridgeInflater(inflater); 355 356 IResourceValue windowBackground = null; 357 int screenOffset = 0; 358 if (currentTheme != null) { 359 windowBackground = context.findItemInStyle(currentTheme, "windowBackground"); 360 windowBackground = context.resolveResValue(windowBackground); 361 362 screenOffset = getScreenOffset(frameworkResources, currentTheme, context); 363 } 364 365 // we need to make sure the Looper has been initialized for this thread. 366 // this is required for View that creates Handler objects. 367 if (Looper.myLooper() == null) { 368 Looper.prepare(); 369 } 370 371 BridgeXmlBlockParser parser = new BridgeXmlBlockParser(layoutDescription, 372 context, false /* platformResourceFlag */); 373 374 ViewGroup root = new FrameLayout(context); 375 376 View view = inflater.inflate(parser, root); 377 378 // post-inflate process. For now this supports TabHost/TabWidget 379 postInflateProcess(view, customViewLoader); 380 381 // set the AttachInfo on the root view. 382 AttachInfo info = new AttachInfo(new WindowSession(), new Window(), 383 new Handler(), null); 384 info.mHasWindowFocus = true; 385 info.mWindowVisibility = View.VISIBLE; 386 info.mInTouchMode = false; // this is so that we can display selections. 387 root.dispatchAttachedToWindow(info, 0); 388 389 // get the background drawable 390 if (windowBackground != null) { 391 Drawable d = ResourceHelper.getDrawable(windowBackground.getValue(), 392 context, true /* isFramework */); 393 root.setBackgroundDrawable(d); 394 } 395 396 int w_spec = MeasureSpec.makeMeasureSpec(screenWidth, MeasureSpec.EXACTLY); 397 int h_spec = MeasureSpec.makeMeasureSpec(screenHeight - screenOffset, 398 MeasureSpec.EXACTLY); 399 400 // measure the views 401 view.measure(w_spec, h_spec); 402 view.layout(0, screenOffset, screenWidth, screenHeight); 403 404 // draw them 405 Canvas canvas = new Canvas(screenWidth, screenHeight - screenOffset, logger); 406 407 root.draw(canvas); 408 canvas.dispose(); 409 410 return new LayoutResult(visit(((ViewGroup)view).getChildAt(0), context), 411 canvas.getImage()); 412 } catch (PostInflateException e) { 413 return new LayoutResult(ILayoutResult.ERROR, "Error during post inflation process:\n" 414 + e.getMessage()); 415 } catch (Throwable e) { 416 // get the real cause of the exception. 417 Throwable t = e; 418 while (t.getCause() != null) { 419 t = t.getCause(); 420 } 421 422 // log it 423 logger.error(t); 424 425 // then return with an ERROR status and the message from the real exception 426 return new LayoutResult(ILayoutResult.ERROR, 427 t.getClass().getSimpleName() + ": " + t.getMessage()); 428 } finally { 429 // Make sure to remove static references, otherwise we could not unload the lib 430 BridgeResources.clearSystem(); 431 BridgeAssetManager.clearSystem(); 432 433 // Remove the global logger 434 synchronized (sDefaultLogger) { 435 sLogger = sDefaultLogger; 436 } 437 } 438 } 439 440 /* 441 * (non-Javadoc) 442 * @see com.android.layoutlib.api.ILayoutLibBridge#clearCaches(java.lang.Object) 443 */ 444 public void clearCaches(Object projectKey) { 445 if (projectKey != null) { 446 sProjectBitmapCache.remove(projectKey); 447 sProject9PatchCache.remove(projectKey); 448 } 449 } 450 451 /** 452 * Returns details of a framework resource from its integer value. 453 * @param value the integer value 454 * @return an array of 2 strings containing the resource name and type, or null if the id 455 * does not match any resource. 456 */ 457 public static String[] resolveResourceValue(int value) { 458 return sRMap.get(value); 459 460 } 461 462 /** 463 * Returns the name of a framework resource whose value is an int array. 464 * @param array 465 */ 466 public static String resolveResourceValue(int[] array) { 467 return sRArrayMap.get(array); 468 } 469 470 /** 471 * Returns the integer id of a framework resource, from a given resource type and resource name. 472 * @param type the type of the resource 473 * @param name the name of the resource. 474 * @return an {@link Integer} containing the resource id, or null if no resource were found. 475 */ 476 public static Integer getResourceValue(String type, String name) { 477 Map<String, Integer> map = sRFullMap.get(type); 478 if (map != null) { 479 return map.get(name); 480 } 481 482 return null; 483 } 484 485 static Map<String, Integer> getEnumValues(String attributeName) { 486 if (sEnumValueMap != null) { 487 return sEnumValueMap.get(attributeName); 488 } 489 490 return null; 491 } 492 493 /** 494 * Visits a View and its children and generate a {@link ILayoutViewInfo} containing the 495 * bounds of all the views. 496 * @param view the root View 497 * @param context the context. 498 */ 499 private ILayoutViewInfo visit(View view, BridgeContext context) { 500 if (view == null) { 501 return null; 502 } 503 504 LayoutViewInfo result = new LayoutViewInfo(view.getClass().getName(), 505 context.getViewKey(view), 506 view.getLeft(), view.getTop(), view.getRight(), view.getBottom()); 507 508 if (view instanceof ViewGroup) { 509 ViewGroup group = ((ViewGroup) view); 510 int n = group.getChildCount(); 511 ILayoutViewInfo[] children = new ILayoutViewInfo[n]; 512 for (int i = 0; i < group.getChildCount(); i++) { 513 children[i] = visit(group.getChildAt(i), context); 514 } 515 result.setChildren(children); 516 } 517 518 return result; 519 } 520 521 /** 522 * Compute style information from the given list of style for the project and framework. 523 * @param themeName the name of the current theme. In order to differentiate project and 524 * platform themes sharing the same name, all project themes must be prepended with 525 * a '*' character. 526 * @param isProjectTheme Is this a project theme 527 * @param inProjectStyleMap the project style map 528 * @param inFrameworkStyleMap the framework style map 529 * @param outInheritanceMap the map of style inheritance. This is filled by the method 530 * @return the {@link IStyleResourceValue} matching <var>themeName</var> 531 */ 532 private IStyleResourceValue computeStyleMaps( 533 String themeName, boolean isProjectTheme, Map<String, 534 IResourceValue> inProjectStyleMap, Map<String, IResourceValue> inFrameworkStyleMap, 535 Map<IStyleResourceValue, IStyleResourceValue> outInheritanceMap) { 536 537 if (inProjectStyleMap != null && inFrameworkStyleMap != null) { 538 // first, get the theme 539 IResourceValue theme = null; 540 541 // project theme names have been prepended with a * 542 if (isProjectTheme) { 543 theme = inProjectStyleMap.get(themeName); 544 } else { 545 theme = inFrameworkStyleMap.get(themeName); 546 } 547 548 if (theme instanceof IStyleResourceValue) { 549 // compute the inheritance map for both the project and framework styles 550 computeStyleInheritance(inProjectStyleMap.values(), inProjectStyleMap, 551 inFrameworkStyleMap, outInheritanceMap); 552 553 // Compute the style inheritance for the framework styles/themes. 554 // Since, for those, the style parent values do not contain 'android:' 555 // we want to force looking in the framework style only to avoid using 556 // similarly named styles from the project. 557 // To do this, we pass null in lieu of the project style map. 558 computeStyleInheritance(inFrameworkStyleMap.values(), null /*inProjectStyleMap */, 559 inFrameworkStyleMap, outInheritanceMap); 560 561 return (IStyleResourceValue)theme; 562 } 563 } 564 565 return null; 566 } 567 568 /** 569 * Compute the parent style for all the styles in a given list. 570 * @param styles the styles for which we compute the parent. 571 * @param inProjectStyleMap the map of project styles. 572 * @param inFrameworkStyleMap the map of framework styles. 573 * @param outInheritanceMap the map of style inheritance. This is filled by the method. 574 */ 575 private void computeStyleInheritance(Collection<IResourceValue> styles, 576 Map<String, IResourceValue> inProjectStyleMap, 577 Map<String, IResourceValue> inFrameworkStyleMap, 578 Map<IStyleResourceValue, IStyleResourceValue> outInheritanceMap) { 579 for (IResourceValue value : styles) { 580 if (value instanceof IStyleResourceValue) { 581 IStyleResourceValue style = (IStyleResourceValue)value; 582 IStyleResourceValue parentStyle = null; 583 584 // first look for a specified parent. 585 String parentName = style.getParentStyle(); 586 587 // no specified parent? try to infer it from the name of the style. 588 if (parentName == null) { 589 parentName = getParentName(value.getName()); 590 } 591 592 if (parentName != null) { 593 parentStyle = getStyle(parentName, inProjectStyleMap, inFrameworkStyleMap); 594 595 if (parentStyle != null) { 596 outInheritanceMap.put(style, parentStyle); 597 } 598 } 599 } 600 } 601 } 602 603 /** 604 * Searches for and returns the {@link IStyleResourceValue} from a given name. 605 * <p/>The format of the name can be: 606 * <ul> 607 * <li>[android:]<name></li> 608 * <li>[android:]style/<name></li> 609 * <li>@[android:]style/<name></li> 610 * </ul> 611 * @param parentName the name of the style. 612 * @param inProjectStyleMap the project style map. Can be <code>null</code> 613 * @param inFrameworkStyleMap the framework style map. 614 * @return The matching {@link IStyleResourceValue} object or <code>null</code> if not found. 615 */ 616 private IStyleResourceValue getStyle(String parentName, 617 Map<String, IResourceValue> inProjectStyleMap, 618 Map<String, IResourceValue> inFrameworkStyleMap) { 619 boolean frameworkOnly = false; 620 621 String name = parentName; 622 623 // remove the useless @ if it's there 624 if (name.startsWith(BridgeConstants.PREFIX_RESOURCE_REF)) { 625 name = name.substring(BridgeConstants.PREFIX_RESOURCE_REF.length()); 626 } 627 628 // check for framework identifier. 629 if (name.startsWith(BridgeConstants.PREFIX_ANDROID)) { 630 frameworkOnly = true; 631 name = name.substring(BridgeConstants.PREFIX_ANDROID.length()); 632 } 633 634 // at this point we could have the format style/<name>. we want only the name 635 if (name.startsWith(BridgeConstants.REFERENCE_STYLE)) { 636 name = name.substring(BridgeConstants.REFERENCE_STYLE.length()); 637 } 638 639 IResourceValue parent = null; 640 641 // if allowed, search in the project resources. 642 if (frameworkOnly == false && inProjectStyleMap != null) { 643 parent = inProjectStyleMap.get(name); 644 } 645 646 // if not found, then look in the framework resources. 647 if (parent == null) { 648 parent = inFrameworkStyleMap.get(name); 649 } 650 651 // make sure the result is the proper class type and return it. 652 if (parent instanceof IStyleResourceValue) { 653 return (IStyleResourceValue)parent; 654 } 655 656 sLogger.error(String.format("Unable to resolve parent style name: ", parentName)); 657 658 return null; 659 } 660 661 /** 662 * Computes the name of the parent style, or <code>null</code> if the style is a root style. 663 */ 664 private String getParentName(String styleName) { 665 int index = styleName.lastIndexOf('.'); 666 if (index != -1) { 667 return styleName.substring(0, index); 668 } 669 670 return null; 671 } 672 673 /** 674 * Returns the top screen offset. This depends on whether the current theme defines the user 675 * of the title and status bars. 676 * @param frameworkResources The framework resources 677 * @param currentTheme The current theme 678 * @param context The context 679 * @return the pixel height offset 680 */ 681 private int getScreenOffset(Map<String, Map<String, IResourceValue>> frameworkResources, 682 IStyleResourceValue currentTheme, BridgeContext context) { 683 int offset = 0; 684 685 // get the title bar flag from the current theme. 686 IResourceValue value = context.findItemInStyle(currentTheme, "windowNoTitle"); 687 688 // because it may reference something else, we resolve it. 689 value = context.resolveResValue(value); 690 691 // if there's a value and it's true (default is false) 692 if (value == null || value.getValue() == null || 693 XmlUtils.convertValueToBoolean(value.getValue(), false /* defValue */) == false) { 694 // default size of the window title bar 695 int defaultOffset = DEFAULT_TITLE_BAR_HEIGHT; 696 697 // get value from the theme. 698 value = context.findItemInStyle(currentTheme, "windowTitleSize"); 699 700 // resolve it 701 value = context.resolveResValue(value); 702 703 if (value != null) { 704 // get the numerical value, if available 705 TypedValue typedValue = ResourceHelper.getValue(value.getValue()); 706 if (typedValue != null) { 707 // compute the pixel value based on the display metrics 708 defaultOffset = (int)typedValue.getDimension(context.getResources().mMetrics); 709 } 710 } 711 712 offset += defaultOffset; 713 } 714 715 // get the fullscreen flag from the current theme. 716 value = context.findItemInStyle(currentTheme, "windowFullscreen"); 717 718 // because it may reference something else, we resolve it. 719 value = context.resolveResValue(value); 720 721 if (value == null || value.getValue() == null || 722 XmlUtils.convertValueToBoolean(value.getValue(), false /* defValue */) == false) { 723 724 // default value 725 int defaultOffset = DEFAULT_STATUS_BAR_HEIGHT; 726 727 // get the real value, first the list of Dimensions from the framework map 728 Map<String, IResourceValue> dimens = frameworkResources.get(BridgeConstants.RES_DIMEN); 729 730 // now get the value 731 value = dimens.get("status_bar_height"); 732 if (value != null) { 733 TypedValue typedValue = ResourceHelper.getValue(value.getValue()); 734 if (typedValue != null) { 735 // compute the pixel value based on the display metrics 736 defaultOffset = (int)typedValue.getDimension(context.getResources().mMetrics); 737 } 738 } 739 740 // add the computed offset. 741 offset += defaultOffset; 742 } 743 744 return offset; 745 } 746 747 /** 748 * Post process on a view hierachy that was just inflated. 749 * <p/>At the moment this only support TabHost: If {@link TabHost} is detected, look for the 750 * {@link TabWidget}, and the corresponding {@link FrameLayout} and make new tabs automatically 751 * based on the content of the {@link FrameLayout}. 752 * @param view the root view to process. 753 * @param projectCallback callback to the project. 754 */ 755 private void postInflateProcess(View view, IProjectCallback projectCallback) 756 throws PostInflateException { 757 if (view instanceof TabHost) { 758 setupTabHost((TabHost)view, projectCallback); 759 } else if (view instanceof ViewGroup) { 760 ViewGroup group = (ViewGroup)view; 761 final int count = group.getChildCount(); 762 for (int c = 0 ; c < count ; c++) { 763 View child = group.getChildAt(c); 764 postInflateProcess(child, projectCallback); 765 } 766 } 767 } 768 769 /** 770 * Sets up a {@link TabHost} object. 771 * @param tabHost the TabHost to setup. 772 * @param projectCallback The project callback object to access the project R class. 773 * @throws PostInflateException 774 */ 775 private void setupTabHost(TabHost tabHost, IProjectCallback projectCallback) 776 throws PostInflateException { 777 // look for the TabWidget, and the FrameLayout. They have their own specific names 778 View v = tabHost.findViewById(android.R.id.tabs); 779 780 if (v == null) { 781 throw new PostInflateException( 782 "TabHost requires a TabWidget with id \"android:id/tabs\".\n"); 783 } 784 785 if ((v instanceof TabWidget) == false) { 786 throw new PostInflateException(String.format( 787 "TabHost requires a TabWidget with id \"android:id/tabs\".\n" + 788 "View found with id 'tabs' is '%s'", v.getClass().getCanonicalName())); 789 } 790 791 v = tabHost.findViewById(android.R.id.tabcontent); 792 793 if (v == null) { 794 // TODO: see if we can fake tabs even without the FrameLayout (same below when the framelayout is empty) 795 throw new PostInflateException( 796 "TabHost requires a FrameLayout with id \"android:id/tabcontent\"."); 797 } 798 799 if ((v instanceof FrameLayout) == false) { 800 throw new PostInflateException(String.format( 801 "TabHost requires a FrameLayout with id \"android:id/tabcontent\".\n" + 802 "View found with id 'tabcontent' is '%s'", v.getClass().getCanonicalName())); 803 } 804 805 FrameLayout content = (FrameLayout)v; 806 807 // now process the content of the framelayout and dynamically create tabs for it. 808 final int count = content.getChildCount(); 809 810 if (count == 0) { 811 throw new PostInflateException( 812 "The FrameLayout for the TabHost has no content. Rendering failed.\n"); 813 } 814 815 // this must be called before addTab() so that the TabHost searches its TabWidget 816 // and FrameLayout. 817 tabHost.setup(); 818 819 // for each child of the framelayout, add a new TabSpec 820 for (int i = 0 ; i < count ; i++) { 821 View child = content.getChildAt(i); 822 String tabSpec = String.format("tab_spec%d", i+1); 823 int id = child.getId(); 824 String[] resource = projectCallback.resolveResourceValue(id); 825 String name; 826 if (resource != null) { 827 name = resource[0]; // 0 is resource name, 1 is resource type. 828 } else { 829 name = String.format("Tab %d", i+1); // default name if id is unresolved. 830 } 831 tabHost.addTab(tabHost.newTabSpec(tabSpec).setIndicator(name).setContent(id)); 832 } 833 } 834 835 /** 836 * Returns the bitmap for a specific path, from a specific project cache, or from the 837 * framework cache. 838 * @param value the path of the bitmap 839 * @param projectKey the key of the project, or null to query the framework cache. 840 * @return the cached Bitmap or null if not found. 841 */ 842 static Bitmap getCachedBitmap(String value, Object projectKey) { 843 if (projectKey != null) { 844 Map<String, SoftReference<Bitmap>> map = sProjectBitmapCache.get(projectKey); 845 if (map != null) { 846 SoftReference<Bitmap> ref = map.get(value); 847 if (ref != null) { 848 return ref.get(); 849 } 850 } 851 } else { 852 SoftReference<Bitmap> ref = sFrameworkBitmapCache.get(value); 853 if (ref != null) { 854 return ref.get(); 855 } 856 } 857 858 return null; 859 } 860 861 /** 862 * Sets a bitmap in a project cache or in the framework cache. 863 * @param value the path of the bitmap 864 * @param bmp the Bitmap object 865 * @param projectKey the key of the project, or null to put the bitmap in the framework cache. 866 */ 867 static void setCachedBitmap(String value, Bitmap bmp, Object projectKey) { 868 if (projectKey != null) { 869 Map<String, SoftReference<Bitmap>> map = sProjectBitmapCache.get(projectKey); 870 871 if (map == null) { 872 map = new HashMap<String, SoftReference<Bitmap>>(); 873 sProjectBitmapCache.put(projectKey, map); 874 } 875 876 map.put(value, new SoftReference<Bitmap>(bmp)); 877 } else { 878 sFrameworkBitmapCache.put(value, new SoftReference<Bitmap>(bmp)); 879 } 880 } 881 882 /** 883 * Returns the 9 patch for a specific path, from a specific project cache, or from the 884 * framework cache. 885 * @param value the path of the 9 patch 886 * @param projectKey the key of the project, or null to query the framework cache. 887 * @return the cached 9 patch or null if not found. 888 */ 889 static NinePatch getCached9Patch(String value, Object projectKey) { 890 if (projectKey != null) { 891 Map<String, SoftReference<NinePatch>> map = sProject9PatchCache.get(projectKey); 892 893 if (map != null) { 894 SoftReference<NinePatch> ref = map.get(value); 895 if (ref != null) { 896 return ref.get(); 897 } 898 } 899 } else { 900 SoftReference<NinePatch> ref = sFramework9PatchCache.get(value); 901 if (ref != null) { 902 return ref.get(); 903 } 904 } 905 906 return null; 907 } 908 909 /** 910 * Sets a 9 patch in a project cache or in the framework cache. 911 * @param value the path of the 9 patch 912 * @param ninePatch the 9 patch object 913 * @param projectKey the key of the project, or null to put the bitmap in the framework cache. 914 */ 915 static void setCached9Patch(String value, NinePatch ninePatch, Object projectKey) { 916 if (projectKey != null) { 917 Map<String, SoftReference<NinePatch>> map = sProject9PatchCache.get(projectKey); 918 919 if (map == null) { 920 map = new HashMap<String, SoftReference<NinePatch>>(); 921 sProject9PatchCache.put(projectKey, map); 922 } 923 924 map.put(value, new SoftReference<NinePatch>(ninePatch)); 925 } else { 926 sFramework9PatchCache.put(value, new SoftReference<NinePatch>(ninePatch)); 927 } 928 } 929 930 private static final class PostInflateException extends Exception { 931 private static final long serialVersionUID = 1L; 932 933 public PostInflateException(String message) { 934 super(message); 935 } 936 } 937 938 /** 939 * Implementation of {@link IWindowSession} so that mSession is not null in 940 * the {@link SurfaceView}. 941 */ 942 private static final class WindowSession implements IWindowSession { 943 944 @SuppressWarnings("unused") 945 public int add(IWindow arg0, LayoutParams arg1, int arg2, Rect arg3) 946 throws RemoteException { 947 // pass for now. 948 return 0; 949 } 950 951 @SuppressWarnings("unused") 952 public void finishDrawing(IWindow arg0) throws RemoteException { 953 // pass for now. 954 } 955 956 @SuppressWarnings("unused") 957 public void finishKey(IWindow arg0) throws RemoteException { 958 // pass for now. 959 } 960 961 @SuppressWarnings("unused") 962 public boolean getInTouchMode() throws RemoteException { 963 // pass for now. 964 return false; 965 } 966 967 @SuppressWarnings("unused") 968 public boolean performHapticFeedback(IWindow window, int effectId, boolean always) { 969 // pass for now. 970 return false; 971 } 972 973 @SuppressWarnings("unused") 974 public MotionEvent getPendingPointerMove(IWindow arg0) throws RemoteException { 975 // pass for now. 976 return null; 977 } 978 979 @SuppressWarnings("unused") 980 public MotionEvent getPendingTrackballMove(IWindow arg0) throws RemoteException { 981 // pass for now. 982 return null; 983 } 984 985 @SuppressWarnings("unused") 986 public int relayout(IWindow arg0, LayoutParams arg1, int arg2, int arg3, int arg4, 987 boolean arg4_5, Rect arg5, Rect arg6, Rect arg7, Surface arg8) 988 throws RemoteException { 989 // pass for now. 990 return 0; 991 } 992 993 public void getDisplayFrame(IWindow window, Rect outDisplayFrame) { 994 // pass for now. 995 } 996 997 @SuppressWarnings("unused") 998 public void remove(IWindow arg0) throws RemoteException { 999 // pass for now. 1000 } 1001 1002 @SuppressWarnings("unused") 1003 public void setInTouchMode(boolean arg0) throws RemoteException { 1004 // pass for now. 1005 } 1006 1007 @SuppressWarnings("unused") 1008 public void setTransparentRegion(IWindow arg0, Region arg1) throws RemoteException { 1009 // pass for now. 1010 } 1011 1012 public void setInsets(IWindow window, int touchable, Rect contentInsets, 1013 Rect visibleInsets) { 1014 // pass for now. 1015 } 1016 1017 public IBinder asBinder() { 1018 // pass for now. 1019 return null; 1020 } 1021 } 1022 1023 /** 1024 * Implementation of {@link IWindow} to pass to the {@link AttachInfo}. 1025 */ 1026 private static final class Window implements IWindow { 1027 1028 @SuppressWarnings("unused") 1029 public void dispatchAppVisibility(boolean arg0) throws RemoteException { 1030 // pass for now. 1031 } 1032 1033 @SuppressWarnings("unused") 1034 public void dispatchGetNewSurface() throws RemoteException { 1035 // pass for now. 1036 } 1037 1038 @SuppressWarnings("unused") 1039 public void dispatchKey(KeyEvent arg0) throws RemoteException { 1040 // pass for now. 1041 } 1042 1043 @SuppressWarnings("unused") 1044 public void dispatchPointer(MotionEvent arg0, long arg1) throws RemoteException { 1045 // pass for now. 1046 } 1047 1048 @SuppressWarnings("unused") 1049 public void dispatchTrackball(MotionEvent arg0, long arg1) throws RemoteException { 1050 // pass for now. 1051 } 1052 1053 @SuppressWarnings("unused") 1054 public void executeCommand(String arg0, String arg1, ParcelFileDescriptor arg2) 1055 throws RemoteException { 1056 // pass for now. 1057 } 1058 1059 @SuppressWarnings("unused") 1060 public void resized(int arg0, int arg1, Rect arg2, Rect arg3, boolean arg4) 1061 throws RemoteException { 1062 // pass for now. 1063 } 1064 1065 @SuppressWarnings("unused") 1066 public void windowFocusChanged(boolean arg0, boolean arg1) throws RemoteException { 1067 // pass for now. 1068 } 1069 1070 public IBinder asBinder() { 1071 // pass for now. 1072 return null; 1073 } 1074 } 1075 1076} 1077