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