RenderSessionImpl.java revision 094fd8ecb6f4b666be6c9e7332679bce28fdc3ca
1/* 2 * Copyright (C) 2010 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 static com.android.ide.common.rendering.api.Result.Status.ERROR_ANIM_NOT_FOUND; 20import static com.android.ide.common.rendering.api.Result.Status.ERROR_INFLATION; 21import static com.android.ide.common.rendering.api.Result.Status.ERROR_NOT_INFLATED; 22import static com.android.ide.common.rendering.api.Result.Status.ERROR_UNKNOWN; 23import static com.android.ide.common.rendering.api.Result.Status.ERROR_VIEWGROUP_NO_CHILDREN; 24import static com.android.ide.common.rendering.api.Result.Status.SUCCESS; 25 26import com.android.ide.common.rendering.api.AdapterBinding; 27import com.android.ide.common.rendering.api.HardwareConfig; 28import com.android.ide.common.rendering.api.IAnimationListener; 29import com.android.ide.common.rendering.api.ILayoutPullParser; 30import com.android.ide.common.rendering.api.IProjectCallback; 31import com.android.ide.common.rendering.api.RenderResources; 32import com.android.ide.common.rendering.api.RenderSession; 33import com.android.ide.common.rendering.api.ResourceReference; 34import com.android.ide.common.rendering.api.ResourceValue; 35import com.android.ide.common.rendering.api.Result; 36import com.android.ide.common.rendering.api.Result.Status; 37import com.android.ide.common.rendering.api.SessionParams; 38import com.android.ide.common.rendering.api.SessionParams.RenderingMode; 39import com.android.ide.common.rendering.api.ViewInfo; 40import com.android.internal.util.XmlUtils; 41import com.android.internal.view.menu.ActionMenuItemView; 42import com.android.internal.view.menu.BridgeMenuItemImpl; 43import com.android.internal.view.menu.IconMenuItemView; 44import com.android.internal.view.menu.ListMenuItemView; 45import com.android.internal.view.menu.MenuItemImpl; 46import com.android.internal.view.menu.MenuView; 47import com.android.layoutlib.bridge.Bridge; 48import com.android.layoutlib.bridge.android.BridgeContext; 49import com.android.layoutlib.bridge.android.BridgeLayoutParamsMapAttributes; 50import com.android.layoutlib.bridge.android.BridgeXmlBlockParser; 51import com.android.layoutlib.bridge.bars.NavigationBar; 52import com.android.layoutlib.bridge.bars.StatusBar; 53import com.android.layoutlib.bridge.bars.TitleBar; 54import com.android.layoutlib.bridge.bars.ActionBarLayout; 55import com.android.layoutlib.bridge.impl.binding.FakeAdapter; 56import com.android.layoutlib.bridge.impl.binding.FakeExpandableAdapter; 57import com.android.resources.Density; 58import com.android.resources.ResourceType; 59import com.android.resources.ScreenOrientation; 60import com.android.util.Pair; 61 62import org.xmlpull.v1.XmlPullParserException; 63 64import android.animation.AnimationThread; 65import android.animation.Animator; 66import android.animation.AnimatorInflater; 67import android.animation.LayoutTransition; 68import android.animation.LayoutTransition.TransitionListener; 69import android.app.Fragment_Delegate; 70import android.graphics.Bitmap; 71import android.graphics.Bitmap_Delegate; 72import android.graphics.Canvas; 73import android.graphics.drawable.Drawable; 74import android.util.DisplayMetrics; 75import android.util.TypedValue; 76import android.view.AttachInfo_Accessor; 77import android.view.BridgeInflater; 78import android.view.IWindowManager; 79import android.view.IWindowManagerImpl; 80import android.view.Surface; 81import android.view.View; 82import android.view.View.MeasureSpec; 83import android.view.ViewGroup; 84import android.view.ViewGroup.LayoutParams; 85import android.view.ViewGroup.MarginLayoutParams; 86import android.view.WindowManagerGlobal_Delegate; 87import android.widget.AbsListView; 88import android.widget.AbsSpinner; 89import android.widget.AdapterView; 90import android.widget.ExpandableListView; 91import android.widget.FrameLayout; 92import android.widget.LinearLayout; 93import android.widget.ListView; 94import android.widget.QuickContactBadge; 95import android.widget.TabHost; 96import android.widget.TabHost.TabSpec; 97import android.widget.TabWidget; 98 99import java.awt.AlphaComposite; 100import java.awt.Color; 101import java.awt.Graphics2D; 102import java.awt.image.BufferedImage; 103import java.util.ArrayList; 104import java.util.List; 105import java.util.Map; 106 107/** 108 * Class implementing the render session. 109 * 110 * A session is a stateful representation of a layout file. It is initialized with data coming 111 * through the {@link Bridge} API to inflate the layout. Further actions and rendering can then 112 * be done on the layout. 113 * 114 */ 115public class RenderSessionImpl extends RenderAction<SessionParams> { 116 117 private static final int DEFAULT_TITLE_BAR_HEIGHT = 25; 118 private static final int DEFAULT_STATUS_BAR_HEIGHT = 25; 119 120 // scene state 121 private RenderSession mScene; 122 private BridgeXmlBlockParser mBlockParser; 123 private BridgeInflater mInflater; 124 private ResourceValue mWindowBackground; 125 private ViewGroup mViewRoot; 126 private FrameLayout mContentRoot; 127 private Canvas mCanvas; 128 private int mMeasuredScreenWidth = -1; 129 private int mMeasuredScreenHeight = -1; 130 private boolean mIsAlphaChannelImage; 131 private boolean mWindowIsFloating; 132 133 private int mStatusBarSize; 134 private int mNavigationBarSize; 135 private int mNavigationBarOrientation = LinearLayout.HORIZONTAL; 136 private int mTitleBarSize; 137 private int mActionBarSize; 138 139 140 // information being returned through the API 141 private BufferedImage mImage; 142 private List<ViewInfo> mViewInfoList; 143 private List<ViewInfo> mSystemViewInfoList; 144 145 private static final class PostInflateException extends Exception { 146 private static final long serialVersionUID = 1L; 147 148 public PostInflateException(String message) { 149 super(message); 150 } 151 } 152 153 /** 154 * Creates a layout scene with all the information coming from the layout bridge API. 155 * <p> 156 * This <b>must</b> be followed by a call to {@link RenderSessionImpl#init(long)}, 157 * which act as a 158 * call to {@link RenderSessionImpl#acquire(long)} 159 * 160 * @see Bridge#createSession(SessionParams) 161 */ 162 public RenderSessionImpl(SessionParams params) { 163 super(new SessionParams(params)); 164 } 165 166 /** 167 * Initializes and acquires the scene, creating various Android objects such as context, 168 * inflater, and parser. 169 * 170 * @param timeout the time to wait if another rendering is happening. 171 * 172 * @return whether the scene was prepared 173 * 174 * @see #acquire(long) 175 * @see #release() 176 */ 177 @Override 178 public Result init(long timeout) { 179 Result result = super.init(timeout); 180 if (result.isSuccess() == false) { 181 return result; 182 } 183 184 SessionParams params = getParams(); 185 BridgeContext context = getContext(); 186 187 RenderResources resources = getParams().getResources(); 188 DisplayMetrics metrics = getContext().getMetrics(); 189 190 // use default of true in case it's not found to use alpha by default 191 mIsAlphaChannelImage = getBooleanThemeValue(resources, 192 "windowIsFloating", true /*defaultValue*/); 193 194 mWindowIsFloating = getBooleanThemeValue(resources, "windowIsFloating", 195 true /*defaultValue*/); 196 197 findBackground(resources); 198 findStatusBar(resources, metrics); 199 findActionBar(resources, metrics); 200 findNavigationBar(resources, metrics); 201 202 // FIXME: find those out, and possibly add them to the render params 203 boolean hasSystemNavBar = true; 204 boolean hasNavigationBar = true; 205 IWindowManager iwm = new IWindowManagerImpl(getContext().getConfiguration(), 206 metrics, Surface.ROTATION_0, 207 hasSystemNavBar, hasNavigationBar); 208 WindowManagerGlobal_Delegate.setWindowManagerService(iwm); 209 210 // build the inflater and parser. 211 mInflater = new BridgeInflater(context, params.getProjectCallback()); 212 context.setBridgeInflater(mInflater); 213 214 mBlockParser = new BridgeXmlBlockParser( 215 params.getLayoutDescription(), context, false /* platformResourceFlag */); 216 217 return SUCCESS.createResult(); 218 } 219 220 /** 221 * Inflates the layout. 222 * <p> 223 * {@link #acquire(long)} must have been called before this. 224 * 225 * @throws IllegalStateException if the current context is different than the one owned by 226 * the scene, or if {@link #init(long)} was not called. 227 */ 228 public Result inflate() { 229 checkLock(); 230 231 try { 232 233 SessionParams params = getParams(); 234 HardwareConfig hardwareConfig = params.getHardwareConfig(); 235 BridgeContext context = getContext(); 236 boolean isRtl = Bridge.isLocaleRtl(params.getLocale()); 237 int layoutDirection = isRtl ? View.LAYOUT_DIRECTION_RTL : View.LAYOUT_DIRECTION_LTR; 238 ActionBarLayout actionBar = null; 239 240 // the view group that receives the window background. 241 ViewGroup backgroundView = null; 242 243 if (mWindowIsFloating || params.isForceNoDecor()) { 244 backgroundView = mViewRoot = mContentRoot = new FrameLayout(context); 245 mViewRoot.setLayoutDirection(layoutDirection); 246 } else { 247 if (hasSoftwareButtons() && mNavigationBarOrientation == LinearLayout.VERTICAL) { 248 /* 249 * This is a special case where the navigation bar is on the right. 250 +-------------------------------------------------+---+ 251 | Status bar (always) | | 252 +-------------------------------------------------+ | 253 | (Layout with background drawable) | | 254 | +---------------------------------------------+ | | 255 | | Title/Action bar (optional) | | | 256 | +---------------------------------------------+ | | 257 | | Content, vertical extending | | | 258 | | | | | 259 | +---------------------------------------------+ | | 260 +-------------------------------------------------+---+ 261 262 So we create a horizontal layout, with the nav bar on the right, 263 and the left part is the normal layout below without the nav bar at 264 the bottom 265 */ 266 LinearLayout topLayout = new LinearLayout(context); 267 topLayout.setLayoutDirection(layoutDirection); 268 mViewRoot = topLayout; 269 topLayout.setOrientation(LinearLayout.HORIZONTAL); 270 271 try { 272 NavigationBar navigationBar = createNavigationBar(context, 273 hardwareConfig.getDensity(), isRtl, params.isRtlSupported()); 274 topLayout.addView(navigationBar); 275 } catch (XmlPullParserException e) { 276 277 } 278 } 279 280 /* 281 * we're creating the following layout 282 * 283 +-------------------------------------------------+ 284 | Status bar (always) | 285 +-------------------------------------------------+ 286 | (Layout with background drawable) | 287 | +---------------------------------------------+ | 288 | | Title/Action bar (optional) | | 289 | +---------------------------------------------+ | 290 | | Content, vertical extending | | 291 | | | | 292 | +---------------------------------------------+ | 293 +-------------------------------------------------+ 294 | Navigation bar for soft buttons, maybe see above| 295 +-------------------------------------------------+ 296 297 */ 298 299 LinearLayout topLayout = new LinearLayout(context); 300 topLayout.setOrientation(LinearLayout.VERTICAL); 301 topLayout.setLayoutDirection(layoutDirection); 302 // if we don't already have a view root this is it 303 if (mViewRoot == null) { 304 mViewRoot = topLayout; 305 } else { 306 int topLayoutWidth = 307 params.getHardwareConfig().getScreenWidth() - mNavigationBarSize; 308 LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( 309 topLayoutWidth, LayoutParams.MATCH_PARENT); 310 topLayout.setLayoutParams(layoutParams); 311 312 // this is the case of soft buttons + vertical bar. 313 // this top layout is the first layout in the horizontal layout. see above) 314 if (isRtl && params.isRtlSupported()) { 315 // If RTL is enabled, layoutlib will mirror the layouts. So, add the 316 // topLayout to the right of Navigation Bar and layoutlib will draw it 317 // to the left. 318 mViewRoot.addView(topLayout); 319 } else { 320 // Add the top layout to the left of the Navigation Bar. 321 mViewRoot.addView(topLayout, 0); 322 } 323 } 324 325 if (mStatusBarSize > 0) { 326 // system bar 327 try { 328 StatusBar statusBar = createStatusBar(context, hardwareConfig.getDensity(), 329 layoutDirection, params.isRtlSupported()); 330 topLayout.addView(statusBar); 331 } catch (XmlPullParserException e) { 332 333 } 334 } 335 336 LinearLayout backgroundLayout = new LinearLayout(context); 337 backgroundView = backgroundLayout; 338 backgroundLayout.setOrientation(LinearLayout.VERTICAL); 339 LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( 340 LayoutParams.MATCH_PARENT, 0); 341 layoutParams.weight = 1; 342 backgroundLayout.setLayoutParams(layoutParams); 343 topLayout.addView(backgroundLayout); 344 345 346 // if the theme says no title/action bar, then the size will be 0 347 if (mActionBarSize > 0) { 348 try { 349 actionBar = createActionBar(context, params); 350 backgroundLayout.addView(actionBar); 351 actionBar.createMenuPopup(); 352 mContentRoot = actionBar.getContentRoot(); 353 } catch (XmlPullParserException e) { 354 355 } 356 } else if (mTitleBarSize > 0) { 357 try { 358 TitleBar titleBar = createTitleBar(context, 359 hardwareConfig.getDensity(), params.getAppLabel()); 360 backgroundLayout.addView(titleBar); 361 } catch (XmlPullParserException e) { 362 363 } 364 } 365 366 // content frame 367 if (mContentRoot == null) { 368 mContentRoot = new FrameLayout(context); 369 layoutParams = new LinearLayout.LayoutParams( 370 LayoutParams.MATCH_PARENT, 0); 371 layoutParams.weight = 1; 372 mContentRoot.setLayoutParams(layoutParams); 373 backgroundLayout.addView(mContentRoot); 374 } 375 376 if (mNavigationBarOrientation == LinearLayout.HORIZONTAL && 377 mNavigationBarSize > 0) { 378 // system bar 379 try { 380 NavigationBar navigationBar = createNavigationBar(context, 381 hardwareConfig.getDensity(), isRtl, params.isRtlSupported()); 382 topLayout.addView(navigationBar); 383 } catch (XmlPullParserException e) { 384 385 } 386 } 387 } 388 389 390 // Sets the project callback (custom view loader) to the fragment delegate so that 391 // it can instantiate the custom Fragment. 392 Fragment_Delegate.setProjectCallback(params.getProjectCallback()); 393 394 View view = mInflater.inflate(mBlockParser, mContentRoot); 395 396 // done with the parser, pop it. 397 context.popParser(); 398 399 Fragment_Delegate.setProjectCallback(null); 400 401 // set the AttachInfo on the root view. 402 AttachInfo_Accessor.setAttachInfo(mViewRoot); 403 404 // post-inflate process. For now this supports TabHost/TabWidget 405 postInflateProcess(view, params.getProjectCallback()); 406 407 // get the background drawable 408 if (mWindowBackground != null && backgroundView != null) { 409 Drawable d = ResourceHelper.getDrawable(mWindowBackground, context); 410 backgroundView.setBackground(d); 411 } 412 413 return SUCCESS.createResult(); 414 } catch (PostInflateException e) { 415 return ERROR_INFLATION.createResult(e.getMessage(), e); 416 } catch (Throwable e) { 417 // get the real cause of the exception. 418 Throwable t = e; 419 while (t.getCause() != null) { 420 t = t.getCause(); 421 } 422 423 return ERROR_INFLATION.createResult(t.getMessage(), t); 424 } 425 } 426 427 /** 428 * Renders the scene. 429 * <p> 430 * {@link #acquire(long)} must have been called before this. 431 * 432 * @param freshRender whether the render is a new one and should erase the existing bitmap (in 433 * the case where bitmaps are reused). This is typically needed when not playing 434 * animations.) 435 * 436 * @throws IllegalStateException if the current context is different than the one owned by 437 * the scene, or if {@link #acquire(long)} was not called. 438 * 439 * @see SessionParams#getRenderingMode() 440 * @see RenderSession#render(long) 441 */ 442 public Result render(boolean freshRender) { 443 checkLock(); 444 445 SessionParams params = getParams(); 446 447 try { 448 if (mViewRoot == null) { 449 return ERROR_NOT_INFLATED.createResult(); 450 } 451 452 RenderingMode renderingMode = params.getRenderingMode(); 453 HardwareConfig hardwareConfig = params.getHardwareConfig(); 454 455 // only do the screen measure when needed. 456 boolean newRenderSize = false; 457 if (mMeasuredScreenWidth == -1) { 458 newRenderSize = true; 459 mMeasuredScreenWidth = hardwareConfig.getScreenWidth(); 460 mMeasuredScreenHeight = hardwareConfig.getScreenHeight(); 461 462 if (renderingMode != RenderingMode.NORMAL) { 463 int widthMeasureSpecMode = renderingMode.isHorizExpand() ? 464 MeasureSpec.UNSPECIFIED // this lets us know the actual needed size 465 : MeasureSpec.EXACTLY; 466 int heightMeasureSpecMode = renderingMode.isVertExpand() ? 467 MeasureSpec.UNSPECIFIED // this lets us know the actual needed size 468 : MeasureSpec.EXACTLY; 469 470 // We used to compare the measured size of the content to the screen size but 471 // this does not work anymore due to the 2 following issues: 472 // - If the content is in a decor (system bar, title/action bar), the root view 473 // will not resize even with the UNSPECIFIED because of the embedded layout. 474 // - If there is no decor, but a dialog frame, then the dialog padding prevents 475 // comparing the size of the content to the screen frame (as it would not 476 // take into account the dialog padding). 477 478 // The solution is to first get the content size in a normal rendering, inside 479 // the decor or the dialog padding. 480 // Then measure only the content with UNSPECIFIED to see the size difference 481 // and apply this to the screen size. 482 483 // first measure the full layout, with EXACTLY to get the size of the 484 // content as it is inside the decor/dialog 485 Pair<Integer, Integer> exactMeasure = measureView( 486 mViewRoot, mContentRoot.getChildAt(0), 487 mMeasuredScreenWidth, MeasureSpec.EXACTLY, 488 mMeasuredScreenHeight, MeasureSpec.EXACTLY); 489 490 // now measure the content only using UNSPECIFIED (where applicable, based on 491 // the rendering mode). This will give us the size the content needs. 492 Pair<Integer, Integer> result = measureView( 493 mContentRoot, mContentRoot.getChildAt(0), 494 mMeasuredScreenWidth, widthMeasureSpecMode, 495 mMeasuredScreenHeight, heightMeasureSpecMode); 496 497 // now look at the difference and add what is needed. 498 if (renderingMode.isHorizExpand()) { 499 int measuredWidth = exactMeasure.getFirst(); 500 int neededWidth = result.getFirst(); 501 if (neededWidth > measuredWidth) { 502 mMeasuredScreenWidth += neededWidth - measuredWidth; 503 } 504 } 505 506 if (renderingMode.isVertExpand()) { 507 int measuredHeight = exactMeasure.getSecond(); 508 int neededHeight = result.getSecond(); 509 if (neededHeight > measuredHeight) { 510 mMeasuredScreenHeight += neededHeight - measuredHeight; 511 } 512 } 513 } 514 } 515 516 // measure again with the size we need 517 // This must always be done before the call to layout 518 measureView(mViewRoot, null /*measuredView*/, 519 mMeasuredScreenWidth, MeasureSpec.EXACTLY, 520 mMeasuredScreenHeight, MeasureSpec.EXACTLY); 521 522 // now do the layout. 523 mViewRoot.layout(0, 0, mMeasuredScreenWidth, mMeasuredScreenHeight); 524 525 if (params.isLayoutOnly()) { 526 // delete the canvas and image to reset them on the next full rendering 527 mImage = null; 528 mCanvas = null; 529 } else { 530 AttachInfo_Accessor.dispatchOnPreDraw(mViewRoot); 531 532 // draw the views 533 // create the BufferedImage into which the layout will be rendered. 534 boolean newImage = false; 535 if (newRenderSize || mCanvas == null) { 536 if (params.getImageFactory() != null) { 537 mImage = params.getImageFactory().getImage( 538 mMeasuredScreenWidth, 539 mMeasuredScreenHeight); 540 } else { 541 mImage = new BufferedImage( 542 mMeasuredScreenWidth, 543 mMeasuredScreenHeight, 544 BufferedImage.TYPE_INT_ARGB); 545 newImage = true; 546 } 547 548 if (params.isBgColorOverridden()) { 549 // since we override the content, it's the same as if it was a new image. 550 newImage = true; 551 Graphics2D gc = mImage.createGraphics(); 552 gc.setColor(new Color(params.getOverrideBgColor(), true)); 553 gc.setComposite(AlphaComposite.Src); 554 gc.fillRect(0, 0, mMeasuredScreenWidth, mMeasuredScreenHeight); 555 gc.dispose(); 556 } 557 558 // create an Android bitmap around the BufferedImage 559 Bitmap bitmap = Bitmap_Delegate.createBitmap(mImage, 560 true /*isMutable*/, hardwareConfig.getDensity()); 561 562 // create a Canvas around the Android bitmap 563 mCanvas = new Canvas(bitmap); 564 mCanvas.setDensity(hardwareConfig.getDensity().getDpiValue()); 565 } 566 567 if (freshRender && newImage == false) { 568 Graphics2D gc = mImage.createGraphics(); 569 gc.setComposite(AlphaComposite.Src); 570 571 gc.setColor(new Color(0x00000000, true)); 572 gc.fillRect(0, 0, 573 mMeasuredScreenWidth, mMeasuredScreenHeight); 574 575 // done 576 gc.dispose(); 577 } 578 579 mViewRoot.draw(mCanvas); 580 } 581 582 mSystemViewInfoList = visitAllChildren(mViewRoot, 0, params.getExtendedViewInfoMode(), 583 false); 584 585 // success! 586 return SUCCESS.createResult(); 587 } catch (Throwable e) { 588 // get the real cause of the exception. 589 Throwable t = e; 590 while (t.getCause() != null) { 591 t = t.getCause(); 592 } 593 594 return ERROR_UNKNOWN.createResult(t.getMessage(), t); 595 } 596 } 597 598 /** 599 * Executes {@link View#measure(int, int)} on a given view with the given parameters (used 600 * to create measure specs with {@link MeasureSpec#makeMeasureSpec(int, int)}. 601 * 602 * if <var>measuredView</var> is non null, the method returns a {@link Pair} of (width, height) 603 * for the view (using {@link View#getMeasuredWidth()} and {@link View#getMeasuredHeight()}). 604 * 605 * @param viewToMeasure the view on which to execute measure(). 606 * @param measuredView if non null, the view to query for its measured width/height. 607 * @param width the width to use in the MeasureSpec. 608 * @param widthMode the MeasureSpec mode to use for the width. 609 * @param height the height to use in the MeasureSpec. 610 * @param heightMode the MeasureSpec mode to use for the height. 611 * @return the measured width/height if measuredView is non-null, null otherwise. 612 */ 613 private Pair<Integer, Integer> measureView(ViewGroup viewToMeasure, View measuredView, 614 int width, int widthMode, int height, int heightMode) { 615 int w_spec = MeasureSpec.makeMeasureSpec(width, widthMode); 616 int h_spec = MeasureSpec.makeMeasureSpec(height, heightMode); 617 viewToMeasure.measure(w_spec, h_spec); 618 619 if (measuredView != null) { 620 return Pair.of(measuredView.getMeasuredWidth(), measuredView.getMeasuredHeight()); 621 } 622 623 return null; 624 } 625 626 /** 627 * Animate an object 628 * <p> 629 * {@link #acquire(long)} must have been called before this. 630 * 631 * @throws IllegalStateException if the current context is different than the one owned by 632 * the scene, or if {@link #acquire(long)} was not called. 633 * 634 * @see RenderSession#animate(Object, String, boolean, IAnimationListener) 635 */ 636 public Result animate(Object targetObject, String animationName, 637 boolean isFrameworkAnimation, IAnimationListener listener) { 638 checkLock(); 639 640 BridgeContext context = getContext(); 641 642 // find the animation file. 643 ResourceValue animationResource = null; 644 int animationId = 0; 645 if (isFrameworkAnimation) { 646 animationResource = context.getRenderResources().getFrameworkResource( 647 ResourceType.ANIMATOR, animationName); 648 if (animationResource != null) { 649 animationId = Bridge.getResourceId(ResourceType.ANIMATOR, animationName); 650 } 651 } else { 652 animationResource = context.getRenderResources().getProjectResource( 653 ResourceType.ANIMATOR, animationName); 654 if (animationResource != null) { 655 animationId = context.getProjectCallback().getResourceId( 656 ResourceType.ANIMATOR, animationName); 657 } 658 } 659 660 if (animationResource != null) { 661 try { 662 Animator anim = AnimatorInflater.loadAnimator(context, animationId); 663 if (anim != null) { 664 anim.setTarget(targetObject); 665 666 new PlayAnimationThread(anim, this, animationName, listener).start(); 667 668 return SUCCESS.createResult(); 669 } 670 } catch (Exception e) { 671 // get the real cause of the exception. 672 Throwable t = e; 673 while (t.getCause() != null) { 674 t = t.getCause(); 675 } 676 677 return ERROR_UNKNOWN.createResult(t.getMessage(), t); 678 } 679 } 680 681 return ERROR_ANIM_NOT_FOUND.createResult(); 682 } 683 684 /** 685 * Insert a new child into an existing parent. 686 * <p> 687 * {@link #acquire(long)} must have been called before this. 688 * 689 * @throws IllegalStateException if the current context is different than the one owned by 690 * the scene, or if {@link #acquire(long)} was not called. 691 * 692 * @see RenderSession#insertChild(Object, ILayoutPullParser, int, IAnimationListener) 693 */ 694 public Result insertChild(final ViewGroup parentView, ILayoutPullParser childXml, 695 final int index, IAnimationListener listener) { 696 checkLock(); 697 698 BridgeContext context = getContext(); 699 700 // create a block parser for the XML 701 BridgeXmlBlockParser blockParser = new BridgeXmlBlockParser( 702 childXml, context, false /* platformResourceFlag */); 703 704 // inflate the child without adding it to the root since we want to control where it'll 705 // get added. We do pass the parentView however to ensure that the layoutParams will 706 // be created correctly. 707 final View child = mInflater.inflate(blockParser, parentView, false /*attachToRoot*/); 708 blockParser.ensurePopped(); 709 710 invalidateRenderingSize(); 711 712 if (listener != null) { 713 new AnimationThread(this, "insertChild", listener) { 714 715 @Override 716 public Result preAnimation() { 717 parentView.setLayoutTransition(new LayoutTransition()); 718 return addView(parentView, child, index); 719 } 720 721 @Override 722 public void postAnimation() { 723 parentView.setLayoutTransition(null); 724 } 725 }.start(); 726 727 // always return success since the real status will come through the listener. 728 return SUCCESS.createResult(child); 729 } 730 731 // add it to the parentView in the correct location 732 Result result = addView(parentView, child, index); 733 if (result.isSuccess() == false) { 734 return result; 735 } 736 737 result = render(false /*freshRender*/); 738 if (result.isSuccess()) { 739 result = result.getCopyWithData(child); 740 } 741 742 return result; 743 } 744 745 /** 746 * Adds a given view to a given parent at a given index. 747 * 748 * @param parent the parent to receive the view 749 * @param view the view to add to the parent 750 * @param index the index where to do the add. 751 * 752 * @return a Result with {@link Status#SUCCESS} or 753 * {@link Status#ERROR_VIEWGROUP_NO_CHILDREN} if the given parent doesn't support 754 * adding views. 755 */ 756 private Result addView(ViewGroup parent, View view, int index) { 757 try { 758 parent.addView(view, index); 759 return SUCCESS.createResult(); 760 } catch (UnsupportedOperationException e) { 761 // looks like this is a view class that doesn't support children manipulation! 762 return ERROR_VIEWGROUP_NO_CHILDREN.createResult(); 763 } 764 } 765 766 /** 767 * Moves a view to a new parent at a given location 768 * <p> 769 * {@link #acquire(long)} must have been called before this. 770 * 771 * @throws IllegalStateException if the current context is different than the one owned by 772 * the scene, or if {@link #acquire(long)} was not called. 773 * 774 * @see RenderSession#moveChild(Object, Object, int, Map, IAnimationListener) 775 */ 776 public Result moveChild(final ViewGroup newParentView, final View childView, final int index, 777 Map<String, String> layoutParamsMap, final IAnimationListener listener) { 778 checkLock(); 779 780 invalidateRenderingSize(); 781 782 LayoutParams layoutParams = null; 783 if (layoutParamsMap != null) { 784 // need to create a new LayoutParams object for the new parent. 785 layoutParams = newParentView.generateLayoutParams( 786 new BridgeLayoutParamsMapAttributes(layoutParamsMap)); 787 } 788 789 // get the current parent of the view that needs to be moved. 790 final ViewGroup previousParent = (ViewGroup) childView.getParent(); 791 792 if (listener != null) { 793 final LayoutParams params = layoutParams; 794 795 // there is no support for animating views across layouts, so in case the new and old 796 // parent views are different we fake the animation through a no animation thread. 797 if (previousParent != newParentView) { 798 new Thread("not animated moveChild") { 799 @Override 800 public void run() { 801 Result result = moveView(previousParent, newParentView, childView, index, 802 params); 803 if (result.isSuccess() == false) { 804 listener.done(result); 805 } 806 807 // ready to do the work, acquire the scene. 808 result = acquire(250); 809 if (result.isSuccess() == false) { 810 listener.done(result); 811 return; 812 } 813 814 try { 815 result = render(false /*freshRender*/); 816 if (result.isSuccess()) { 817 listener.onNewFrame(RenderSessionImpl.this.getSession()); 818 } 819 } finally { 820 release(); 821 } 822 823 listener.done(result); 824 } 825 }.start(); 826 } else { 827 new AnimationThread(this, "moveChild", listener) { 828 829 @Override 830 public Result preAnimation() { 831 // set up the transition for the parent. 832 LayoutTransition transition = new LayoutTransition(); 833 previousParent.setLayoutTransition(transition); 834 835 // tweak the animation durations and start delays (to match the duration of 836 // animation playing just before). 837 // Note: Cannot user Animation.setDuration() directly. Have to set it 838 // on the LayoutTransition. 839 transition.setDuration(LayoutTransition.DISAPPEARING, 100); 840 // CHANGE_DISAPPEARING plays after DISAPPEARING 841 transition.setStartDelay(LayoutTransition.CHANGE_DISAPPEARING, 100); 842 843 transition.setDuration(LayoutTransition.CHANGE_DISAPPEARING, 100); 844 845 transition.setDuration(LayoutTransition.CHANGE_APPEARING, 100); 846 // CHANGE_APPEARING plays after CHANGE_APPEARING 847 transition.setStartDelay(LayoutTransition.APPEARING, 100); 848 849 transition.setDuration(LayoutTransition.APPEARING, 100); 850 851 return moveView(previousParent, newParentView, childView, index, params); 852 } 853 854 @Override 855 public void postAnimation() { 856 previousParent.setLayoutTransition(null); 857 newParentView.setLayoutTransition(null); 858 } 859 }.start(); 860 } 861 862 // always return success since the real status will come through the listener. 863 return SUCCESS.createResult(layoutParams); 864 } 865 866 Result result = moveView(previousParent, newParentView, childView, index, layoutParams); 867 if (result.isSuccess() == false) { 868 return result; 869 } 870 871 result = render(false /*freshRender*/); 872 if (layoutParams != null && result.isSuccess()) { 873 result = result.getCopyWithData(layoutParams); 874 } 875 876 return result; 877 } 878 879 /** 880 * Moves a View from its current parent to a new given parent at a new given location, with 881 * an optional new {@link LayoutParams} instance 882 * 883 * @param previousParent the previous parent, still owning the child at the time of the call. 884 * @param newParent the new parent 885 * @param movedView the view to move 886 * @param index the new location in the new parent 887 * @param params an option (can be null) {@link LayoutParams} instance. 888 * 889 * @return a Result with {@link Status#SUCCESS} or 890 * {@link Status#ERROR_VIEWGROUP_NO_CHILDREN} if the given parent doesn't support 891 * adding views. 892 */ 893 private Result moveView(ViewGroup previousParent, final ViewGroup newParent, 894 final View movedView, final int index, final LayoutParams params) { 895 try { 896 // check if there is a transition on the previousParent. 897 LayoutTransition previousTransition = previousParent.getLayoutTransition(); 898 if (previousTransition != null) { 899 // in this case there is an animation. This means we have to wait for the child's 900 // parent reference to be null'ed out so that we can add it to the new parent. 901 // It is technically removed right before the DISAPPEARING animation is done (if 902 // the animation of this type is not null, otherwise it's after which is impossible 903 // to handle). 904 // Because there is no move animation, if the new parent is the same as the old 905 // parent, we need to wait until the CHANGE_DISAPPEARING animation is done before 906 // adding the child or the child will appear in its new location before the 907 // other children have made room for it. 908 909 // add a listener to the transition to be notified of the actual removal. 910 previousTransition.addTransitionListener(new TransitionListener() { 911 private int mChangeDisappearingCount = 0; 912 913 @Override 914 public void startTransition(LayoutTransition transition, ViewGroup container, 915 View view, int transitionType) { 916 if (transitionType == LayoutTransition.CHANGE_DISAPPEARING) { 917 mChangeDisappearingCount++; 918 } 919 } 920 921 @Override 922 public void endTransition(LayoutTransition transition, ViewGroup container, 923 View view, int transitionType) { 924 if (transitionType == LayoutTransition.CHANGE_DISAPPEARING) { 925 mChangeDisappearingCount--; 926 } 927 928 if (transitionType == LayoutTransition.CHANGE_DISAPPEARING && 929 mChangeDisappearingCount == 0) { 930 // add it to the parentView in the correct location 931 if (params != null) { 932 newParent.addView(movedView, index, params); 933 } else { 934 newParent.addView(movedView, index); 935 } 936 } 937 } 938 }); 939 940 // remove the view from the current parent. 941 previousParent.removeView(movedView); 942 943 // and return since adding the view to the new parent is done in the listener. 944 return SUCCESS.createResult(); 945 } else { 946 // standard code with no animation. pretty simple. 947 previousParent.removeView(movedView); 948 949 // add it to the parentView in the correct location 950 if (params != null) { 951 newParent.addView(movedView, index, params); 952 } else { 953 newParent.addView(movedView, index); 954 } 955 956 return SUCCESS.createResult(); 957 } 958 } catch (UnsupportedOperationException e) { 959 // looks like this is a view class that doesn't support children manipulation! 960 return ERROR_VIEWGROUP_NO_CHILDREN.createResult(); 961 } 962 } 963 964 /** 965 * Removes a child from its current parent. 966 * <p> 967 * {@link #acquire(long)} must have been called before this. 968 * 969 * @throws IllegalStateException if the current context is different than the one owned by 970 * the scene, or if {@link #acquire(long)} was not called. 971 * 972 * @see RenderSession#removeChild(Object, IAnimationListener) 973 */ 974 public Result removeChild(final View childView, IAnimationListener listener) { 975 checkLock(); 976 977 invalidateRenderingSize(); 978 979 final ViewGroup parent = (ViewGroup) childView.getParent(); 980 981 if (listener != null) { 982 new AnimationThread(this, "moveChild", listener) { 983 984 @Override 985 public Result preAnimation() { 986 parent.setLayoutTransition(new LayoutTransition()); 987 return removeView(parent, childView); 988 } 989 990 @Override 991 public void postAnimation() { 992 parent.setLayoutTransition(null); 993 } 994 }.start(); 995 996 // always return success since the real status will come through the listener. 997 return SUCCESS.createResult(); 998 } 999 1000 Result result = removeView(parent, childView); 1001 if (result.isSuccess() == false) { 1002 return result; 1003 } 1004 1005 return render(false /*freshRender*/); 1006 } 1007 1008 /** 1009 * Removes a given view from its current parent. 1010 * 1011 * @param view the view to remove from its parent 1012 * 1013 * @return a Result with {@link Status#SUCCESS} or 1014 * {@link Status#ERROR_VIEWGROUP_NO_CHILDREN} if the given parent doesn't support 1015 * adding views. 1016 */ 1017 private Result removeView(ViewGroup parent, View view) { 1018 try { 1019 parent.removeView(view); 1020 return SUCCESS.createResult(); 1021 } catch (UnsupportedOperationException e) { 1022 // looks like this is a view class that doesn't support children manipulation! 1023 return ERROR_VIEWGROUP_NO_CHILDREN.createResult(); 1024 } 1025 } 1026 1027 1028 private void findBackground(RenderResources resources) { 1029 if (getParams().isBgColorOverridden() == false) { 1030 mWindowBackground = resources.findItemInTheme("windowBackground", 1031 true /*isFrameworkAttr*/); 1032 if (mWindowBackground != null) { 1033 mWindowBackground = resources.resolveResValue(mWindowBackground); 1034 } 1035 } 1036 } 1037 1038 private boolean hasSoftwareButtons() { 1039 return getParams().getHardwareConfig().hasSoftwareButtons(); 1040 } 1041 1042 private void findStatusBar(RenderResources resources, DisplayMetrics metrics) { 1043 boolean windowFullscreen = getBooleanThemeValue(resources, 1044 "windowFullscreen", false /*defaultValue*/); 1045 1046 if (windowFullscreen == false && mWindowIsFloating == false) { 1047 // default value 1048 mStatusBarSize = DEFAULT_STATUS_BAR_HEIGHT; 1049 1050 // get the real value 1051 ResourceValue value = resources.getFrameworkResource(ResourceType.DIMEN, 1052 "status_bar_height"); 1053 1054 if (value != null) { 1055 TypedValue typedValue = ResourceHelper.getValue("status_bar_height", 1056 value.getValue(), true /*requireUnit*/); 1057 if (typedValue != null) { 1058 // compute the pixel value based on the display metrics 1059 mStatusBarSize = (int)typedValue.getDimension(metrics); 1060 } 1061 } 1062 } 1063 } 1064 1065 private void findActionBar(RenderResources resources, DisplayMetrics metrics) { 1066 if (mWindowIsFloating) { 1067 return; 1068 } 1069 1070 boolean windowActionBar = getBooleanThemeValue(resources, 1071 "windowActionBar", true /*defaultValue*/); 1072 1073 // if there's a value and it's false (default is true) 1074 if (windowActionBar) { 1075 1076 // default size of the window title bar 1077 mActionBarSize = DEFAULT_TITLE_BAR_HEIGHT; 1078 1079 // get value from the theme. 1080 ResourceValue value = resources.findItemInTheme("actionBarSize", 1081 true /*isFrameworkAttr*/); 1082 1083 // resolve it 1084 value = resources.resolveResValue(value); 1085 1086 if (value != null) { 1087 // get the numerical value, if available 1088 TypedValue typedValue = ResourceHelper.getValue("actionBarSize", value.getValue(), 1089 true /*requireUnit*/); 1090 if (typedValue != null) { 1091 // compute the pixel value based on the display metrics 1092 mActionBarSize = (int)typedValue.getDimension(metrics); 1093 } 1094 } 1095 } else { 1096 // action bar overrides title bar so only look for this one if action bar is hidden 1097 boolean windowNoTitle = getBooleanThemeValue(resources, 1098 "windowNoTitle", false /*defaultValue*/); 1099 1100 if (windowNoTitle == false) { 1101 1102 // default size of the window title bar 1103 mTitleBarSize = DEFAULT_TITLE_BAR_HEIGHT; 1104 1105 // get value from the theme. 1106 ResourceValue value = resources.findItemInTheme("windowTitleSize", 1107 true /*isFrameworkAttr*/); 1108 1109 // resolve it 1110 value = resources.resolveResValue(value); 1111 1112 if (value != null) { 1113 // get the numerical value, if available 1114 TypedValue typedValue = ResourceHelper.getValue("windowTitleSize", 1115 value.getValue(), true /*requireUnit*/); 1116 if (typedValue != null) { 1117 // compute the pixel value based on the display metrics 1118 mTitleBarSize = (int)typedValue.getDimension(metrics); 1119 } 1120 } 1121 } 1122 1123 } 1124 } 1125 1126 private void findNavigationBar(RenderResources resources, DisplayMetrics metrics) { 1127 if (hasSoftwareButtons() && mWindowIsFloating == false) { 1128 1129 // default value 1130 mNavigationBarSize = 48; // ?? 1131 1132 HardwareConfig hardwareConfig = getParams().getHardwareConfig(); 1133 1134 boolean barOnBottom = true; 1135 1136 if (hardwareConfig.getOrientation() == ScreenOrientation.LANDSCAPE) { 1137 // compute the dp of the screen. 1138 int shortSize = hardwareConfig.getScreenHeight(); 1139 1140 // compute in dp 1141 int shortSizeDp = shortSize * DisplayMetrics.DENSITY_DEFAULT / hardwareConfig.getDensity().getDpiValue(); 1142 1143 if (shortSizeDp < 600) { 1144 // 0-599dp: "phone" UI with bar on the side 1145 barOnBottom = false; 1146 } else { 1147 // 600+dp: "tablet" UI with bar on the bottom 1148 barOnBottom = true; 1149 } 1150 } 1151 1152 if (barOnBottom) { 1153 mNavigationBarOrientation = LinearLayout.HORIZONTAL; 1154 } else { 1155 mNavigationBarOrientation = LinearLayout.VERTICAL; 1156 } 1157 1158 // get the real value 1159 ResourceValue value = resources.getFrameworkResource(ResourceType.DIMEN, 1160 barOnBottom ? "navigation_bar_height" : "navigation_bar_width"); 1161 1162 if (value != null) { 1163 TypedValue typedValue = ResourceHelper.getValue("navigation_bar_height", 1164 value.getValue(), true /*requireUnit*/); 1165 if (typedValue != null) { 1166 // compute the pixel value based on the display metrics 1167 mNavigationBarSize = (int)typedValue.getDimension(metrics); 1168 } 1169 } 1170 } 1171 } 1172 1173 /** 1174 * Looks for a attribute in the current theme. The attribute is in the android 1175 * namespace. 1176 * 1177 * @param resources the render resources 1178 * @param name the name of the attribute 1179 * @param defaultValue the default value. 1180 * @return the value of the attribute or the default one if not found. 1181 */ 1182 private boolean getBooleanThemeValue(RenderResources resources, 1183 String name, boolean defaultValue) { 1184 1185 // get the title bar flag from the current theme. 1186 ResourceValue value = resources.findItemInTheme(name, true /*isFrameworkAttr*/); 1187 1188 // because it may reference something else, we resolve it. 1189 value = resources.resolveResValue(value); 1190 1191 // if there's no value, return the default. 1192 if (value == null || value.getValue() == null) { 1193 return defaultValue; 1194 } 1195 1196 return XmlUtils.convertValueToBoolean(value.getValue(), defaultValue); 1197 } 1198 1199 /** 1200 * Post process on a view hierachy that was just inflated. 1201 * <p/>At the moment this only support TabHost: If {@link TabHost} is detected, look for the 1202 * {@link TabWidget}, and the corresponding {@link FrameLayout} and make new tabs automatically 1203 * based on the content of the {@link FrameLayout}. 1204 * @param view the root view to process. 1205 * @param projectCallback callback to the project. 1206 */ 1207 private void postInflateProcess(View view, IProjectCallback projectCallback) 1208 throws PostInflateException { 1209 if (view instanceof TabHost) { 1210 setupTabHost((TabHost)view, projectCallback); 1211 } else if (view instanceof QuickContactBadge) { 1212 QuickContactBadge badge = (QuickContactBadge) view; 1213 badge.setImageToDefault(); 1214 } else if (view instanceof AdapterView<?>) { 1215 // get the view ID. 1216 int id = view.getId(); 1217 1218 BridgeContext context = getContext(); 1219 1220 // get a ResourceReference from the integer ID. 1221 ResourceReference listRef = context.resolveId(id); 1222 1223 if (listRef != null) { 1224 SessionParams params = getParams(); 1225 AdapterBinding binding = params.getAdapterBindings().get(listRef); 1226 1227 // if there was no adapter binding, trying to get it from the call back. 1228 if (binding == null) { 1229 binding = params.getProjectCallback().getAdapterBinding(listRef, 1230 context.getViewKey(view), view); 1231 } 1232 1233 if (binding != null) { 1234 1235 if (view instanceof AbsListView) { 1236 if ((binding.getFooterCount() > 0 || binding.getHeaderCount() > 0) && 1237 view instanceof ListView) { 1238 ListView list = (ListView) view; 1239 1240 boolean skipCallbackParser = false; 1241 1242 int count = binding.getHeaderCount(); 1243 for (int i = 0 ; i < count ; i++) { 1244 Pair<View, Boolean> pair = context.inflateView( 1245 binding.getHeaderAt(i), 1246 list, false /*attachToRoot*/, skipCallbackParser); 1247 if (pair.getFirst() != null) { 1248 list.addHeaderView(pair.getFirst()); 1249 } 1250 1251 skipCallbackParser |= pair.getSecond(); 1252 } 1253 1254 count = binding.getFooterCount(); 1255 for (int i = 0 ; i < count ; i++) { 1256 Pair<View, Boolean> pair = context.inflateView( 1257 binding.getFooterAt(i), 1258 list, false /*attachToRoot*/, skipCallbackParser); 1259 if (pair.getFirst() != null) { 1260 list.addFooterView(pair.getFirst()); 1261 } 1262 1263 skipCallbackParser |= pair.getSecond(); 1264 } 1265 } 1266 1267 if (view instanceof ExpandableListView) { 1268 ((ExpandableListView) view).setAdapter( 1269 new FakeExpandableAdapter( 1270 listRef, binding, params.getProjectCallback())); 1271 } else { 1272 ((AbsListView) view).setAdapter( 1273 new FakeAdapter( 1274 listRef, binding, params.getProjectCallback())); 1275 } 1276 } else if (view instanceof AbsSpinner) { 1277 ((AbsSpinner) view).setAdapter( 1278 new FakeAdapter( 1279 listRef, binding, params.getProjectCallback())); 1280 } 1281 } 1282 } 1283 } else if (view instanceof ViewGroup) { 1284 ViewGroup group = (ViewGroup)view; 1285 final int count = group.getChildCount(); 1286 for (int c = 0 ; c < count ; c++) { 1287 View child = group.getChildAt(c); 1288 postInflateProcess(child, projectCallback); 1289 } 1290 } 1291 } 1292 1293 /** 1294 * Sets up a {@link TabHost} object. 1295 * @param tabHost the TabHost to setup. 1296 * @param projectCallback The project callback object to access the project R class. 1297 * @throws PostInflateException 1298 */ 1299 private void setupTabHost(TabHost tabHost, IProjectCallback projectCallback) 1300 throws PostInflateException { 1301 // look for the TabWidget, and the FrameLayout. They have their own specific names 1302 View v = tabHost.findViewById(android.R.id.tabs); 1303 1304 if (v == null) { 1305 throw new PostInflateException( 1306 "TabHost requires a TabWidget with id \"android:id/tabs\".\n"); 1307 } 1308 1309 if ((v instanceof TabWidget) == false) { 1310 throw new PostInflateException(String.format( 1311 "TabHost requires a TabWidget with id \"android:id/tabs\".\n" + 1312 "View found with id 'tabs' is '%s'", v.getClass().getCanonicalName())); 1313 } 1314 1315 v = tabHost.findViewById(android.R.id.tabcontent); 1316 1317 if (v == null) { 1318 // TODO: see if we can fake tabs even without the FrameLayout (same below when the framelayout is empty) 1319 throw new PostInflateException( 1320 "TabHost requires a FrameLayout with id \"android:id/tabcontent\"."); 1321 } 1322 1323 if ((v instanceof FrameLayout) == false) { 1324 throw new PostInflateException(String.format( 1325 "TabHost requires a FrameLayout with id \"android:id/tabcontent\".\n" + 1326 "View found with id 'tabcontent' is '%s'", v.getClass().getCanonicalName())); 1327 } 1328 1329 FrameLayout content = (FrameLayout)v; 1330 1331 // now process the content of the framelayout and dynamically create tabs for it. 1332 final int count = content.getChildCount(); 1333 1334 // this must be called before addTab() so that the TabHost searches its TabWidget 1335 // and FrameLayout. 1336 tabHost.setup(); 1337 1338 if (count == 0) { 1339 // Create a dummy child to get a single tab 1340 TabSpec spec = tabHost.newTabSpec("tag").setIndicator("Tab Label", 1341 tabHost.getResources().getDrawable(android.R.drawable.ic_menu_info_details)) 1342 .setContent(new TabHost.TabContentFactory() { 1343 @Override 1344 public View createTabContent(String tag) { 1345 return new LinearLayout(getContext()); 1346 } 1347 }); 1348 tabHost.addTab(spec); 1349 return; 1350 } else { 1351 // for each child of the framelayout, add a new TabSpec 1352 for (int i = 0 ; i < count ; i++) { 1353 View child = content.getChildAt(i); 1354 String tabSpec = String.format("tab_spec%d", i+1); 1355 int id = child.getId(); 1356 Pair<ResourceType, String> resource = projectCallback.resolveResourceId(id); 1357 String name; 1358 if (resource != null) { 1359 name = resource.getSecond(); 1360 } else { 1361 name = String.format("Tab %d", i+1); // default name if id is unresolved. 1362 } 1363 tabHost.addTab(tabHost.newTabSpec(tabSpec).setIndicator(name).setContent(id)); 1364 } 1365 } 1366 } 1367 1368 /** 1369 * Visits a {@link View} and its children and generate a {@link ViewInfo} containing the 1370 * bounds of all the views. 1371 * 1372 * @param view the root View 1373 * @param offset an offset for the view bounds. 1374 * @param setExtendedInfo whether to set the extended view info in the {@link ViewInfo} object. 1375 * @param isContentFrame {@code true} if the {@code ViewInfo} to be created is part of the 1376 * content frame. 1377 * 1378 * @return {@code ViewInfo} containing the bounds of the view and it children otherwise. 1379 */ 1380 private ViewInfo visit(View view, int offset, boolean setExtendedInfo, 1381 boolean isContentFrame) { 1382 ViewInfo result = createViewInfo(view, offset, setExtendedInfo, isContentFrame); 1383 1384 if (view instanceof ViewGroup) { 1385 ViewGroup group = ((ViewGroup) view); 1386 result.setChildren(visitAllChildren(group, isContentFrame ? 0 : offset, 1387 setExtendedInfo, isContentFrame)); 1388 } 1389 return result; 1390 } 1391 1392 /** 1393 * Visits all the children of a given ViewGroup and generates a list of {@link ViewInfo} 1394 * containing the bounds of all the views. It also initializes the {@link #mViewInfoList} with 1395 * the children of the {@code mContentRoot}. 1396 * 1397 * @param viewGroup the root View 1398 * @param offset an offset from the top for the content view frame. 1399 * @param setExtendedInfo whether to set the extended view info in the {@link ViewInfo} object. 1400 * @param isContentFrame {@code true} if the {@code ViewInfo} to be created is part of the 1401 * content frame. {@code false} if the {@code ViewInfo} to be created is 1402 * part of the system decor. 1403 */ 1404 private List<ViewInfo> visitAllChildren(ViewGroup viewGroup, int offset, 1405 boolean setExtendedInfo, boolean isContentFrame) { 1406 if (viewGroup == null) { 1407 return null; 1408 } 1409 1410 if (!isContentFrame) { 1411 offset += viewGroup.getTop(); 1412 } 1413 1414 int childCount = viewGroup.getChildCount(); 1415 if (viewGroup == mContentRoot) { 1416 List<ViewInfo> childrenWithoutOffset = new ArrayList<ViewInfo>(childCount); 1417 List<ViewInfo> childrenWithOffset = new ArrayList<ViewInfo>(childCount); 1418 for (int i = 0; i < childCount; i++) { 1419 ViewInfo[] childViewInfo = visitContentRoot(viewGroup.getChildAt(i), offset, 1420 setExtendedInfo); 1421 childrenWithoutOffset.add(childViewInfo[0]); 1422 childrenWithOffset.add(childViewInfo[1]); 1423 } 1424 mViewInfoList = childrenWithOffset; 1425 return childrenWithoutOffset; 1426 } else { 1427 List<ViewInfo> children = new ArrayList<ViewInfo>(childCount); 1428 for (int i = 0; i < childCount; i++) { 1429 children.add(visit(viewGroup.getChildAt(i), offset, setExtendedInfo, 1430 isContentFrame)); 1431 } 1432 return children; 1433 } 1434 } 1435 1436 /** 1437 * Visits the children of {@link #mContentRoot} and generates {@link ViewInfo} containing the 1438 * bounds of all the views. It returns two {@code ViewInfo} objects with the same children, 1439 * one with the {@code offset} and other without the {@code offset}. The offset is needed to 1440 * get the right bounds if the {@code ViewInfo} hierarchy is accessed from 1441 * {@code mViewInfoList}. When the hierarchy is accessed via {@code mSystemViewInfoList}, the 1442 * offset is not needed. 1443 * 1444 * @return an array of length two, with ViewInfo at index 0 is without offset and ViewInfo at 1445 * index 1 is with the offset. 1446 */ 1447 private ViewInfo[] visitContentRoot(View view, int offset, boolean setExtendedInfo) { 1448 ViewInfo[] result = new ViewInfo[2]; 1449 if (view == null) { 1450 return result; 1451 } 1452 1453 result[0] = createViewInfo(view, 0, setExtendedInfo, true); 1454 result[1] = createViewInfo(view, offset, setExtendedInfo, true); 1455 if (view instanceof ViewGroup) { 1456 List<ViewInfo> children = visitAllChildren((ViewGroup) view, 0, setExtendedInfo, true); 1457 result[0].setChildren(children); 1458 result[1].setChildren(children); 1459 } 1460 return result; 1461 } 1462 1463 /** 1464 * Creates a {@link ViewInfo} for the view. The {@code ViewInfo} corresponding to the children 1465 * of the {@code view} are not created. Consequently, the children of {@code ViewInfo} is not 1466 * set. 1467 * @param offset an offset for the view bounds. Used only if view is part of the content frame. 1468 */ 1469 private ViewInfo createViewInfo(View view, int offset, boolean setExtendedInfo, 1470 boolean isContentFrame) { 1471 if (view == null) { 1472 return null; 1473 } 1474 1475 ViewInfo result; 1476 if (isContentFrame) { 1477 result = new ViewInfo(view.getClass().getName(), 1478 getViewKey(view), 1479 view.getLeft(), view.getTop() + offset, view.getRight(), 1480 view.getBottom() + offset, view, view.getLayoutParams()); 1481 1482 } else { 1483 result = new SystemViewInfo(view.getClass().getName(), 1484 getViewKey(view), 1485 view.getLeft(), view.getTop(), view.getRight(), 1486 view.getBottom(), view, view.getLayoutParams()); 1487 } 1488 1489 if (setExtendedInfo) { 1490 MarginLayoutParams marginParams = null; 1491 LayoutParams params = view.getLayoutParams(); 1492 if (params instanceof MarginLayoutParams) { 1493 marginParams = (MarginLayoutParams) params; 1494 } 1495 result.setExtendedInfo(view.getBaseline(), 1496 marginParams != null ? marginParams.leftMargin : 0, 1497 marginParams != null ? marginParams.topMargin : 0, 1498 marginParams != null ? marginParams.rightMargin : 0, 1499 marginParams != null ? marginParams.bottomMargin : 0); 1500 } 1501 1502 return result; 1503 } 1504 1505 /** 1506 * The cookie for menu items are stored in menu item and not in the map from View stored in 1507 * BridgeContext. 1508 */ 1509 private Object getViewKey(View view) { 1510 BridgeContext context = getContext(); 1511 if (!(view instanceof MenuView.ItemView)) { 1512 return context.getViewKey(view); 1513 } 1514 MenuItemImpl menuItem; 1515 if (view instanceof ActionMenuItemView) { 1516 menuItem = ((ActionMenuItemView) view).getItemData(); 1517 } else if (view instanceof ListMenuItemView) { 1518 menuItem = ((ListMenuItemView) view).getItemData(); 1519 } else if (view instanceof IconMenuItemView) { 1520 menuItem = ((IconMenuItemView) view).getItemData(); 1521 } else { 1522 menuItem = null; 1523 } 1524 if (menuItem instanceof BridgeMenuItemImpl) { 1525 return ((BridgeMenuItemImpl) menuItem).getViewCookie(); 1526 } 1527 1528 return null; 1529 } 1530 1531 private void invalidateRenderingSize() { 1532 mMeasuredScreenWidth = mMeasuredScreenHeight = -1; 1533 } 1534 1535 /** 1536 * Creates the status bar with wifi and battery icons. 1537 */ 1538 private StatusBar createStatusBar(BridgeContext context, Density density, int direction, 1539 boolean isRtlSupported) throws XmlPullParserException { 1540 StatusBar statusBar = new StatusBar(context, density, 1541 direction, isRtlSupported); 1542 statusBar.setLayoutParams( 1543 new LinearLayout.LayoutParams( 1544 LayoutParams.MATCH_PARENT, mStatusBarSize)); 1545 return statusBar; 1546 } 1547 1548 /** 1549 * Creates the navigation bar with back, home and recent buttons. 1550 * 1551 * @param isRtl true if the current locale is right-to-left 1552 * @param isRtlSupported true is the project manifest declares that the application 1553 * is RTL aware. 1554 */ 1555 private NavigationBar createNavigationBar(BridgeContext context, Density density, 1556 boolean isRtl, boolean isRtlSupported) throws XmlPullParserException { 1557 NavigationBar navigationBar = new NavigationBar(context, 1558 density, mNavigationBarOrientation, isRtl, 1559 isRtlSupported); 1560 if (mNavigationBarOrientation == LinearLayout.VERTICAL) { 1561 navigationBar.setLayoutParams(new LinearLayout.LayoutParams(mNavigationBarSize, 1562 LayoutParams.MATCH_PARENT)); 1563 } else { 1564 navigationBar.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 1565 mNavigationBarSize)); 1566 } 1567 return navigationBar; 1568 } 1569 1570 private TitleBar createTitleBar(BridgeContext context, Density density, String title) 1571 throws XmlPullParserException { 1572 TitleBar titleBar = new TitleBar(context, density, title); 1573 titleBar.setLayoutParams( 1574 new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, mTitleBarSize)); 1575 return titleBar; 1576 } 1577 1578 /** 1579 * Creates the action bar. Also queries the project callback for missing information. 1580 */ 1581 private ActionBarLayout createActionBar(BridgeContext context, SessionParams params) 1582 throws XmlPullParserException { 1583 ActionBarLayout actionBar = new ActionBarLayout(context, params); 1584 actionBar.setLayoutParams(new LinearLayout.LayoutParams( 1585 LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); 1586 return actionBar; 1587 } 1588 1589 public BufferedImage getImage() { 1590 return mImage; 1591 } 1592 1593 public boolean isAlphaChannelImage() { 1594 return mIsAlphaChannelImage; 1595 } 1596 1597 public List<ViewInfo> getViewInfos() { 1598 return mViewInfoList; 1599 } 1600 1601 public List<ViewInfo> getSystemViewInfos() { 1602 return mSystemViewInfoList; 1603 } 1604 1605 public Map<String, String> getDefaultProperties(Object viewObject) { 1606 return getContext().getDefaultPropMap(viewObject); 1607 } 1608 1609 public void setScene(RenderSession session) { 1610 mScene = session; 1611 } 1612 1613 public RenderSession getSession() { 1614 return mScene; 1615 } 1616} 1617