RenderSessionImpl.java revision e9fa56466125254b2706a4bcc5869c191e1b0775
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.annotations.NonNull; 27import com.android.annotations.Nullable; 28import com.android.ide.common.rendering.api.AdapterBinding; 29import com.android.ide.common.rendering.api.HardwareConfig; 30import com.android.ide.common.rendering.api.IAnimationListener; 31import com.android.ide.common.rendering.api.ILayoutPullParser; 32import com.android.ide.common.rendering.api.IProjectCallback; 33import com.android.ide.common.rendering.api.RenderResources; 34import com.android.ide.common.rendering.api.RenderSession; 35import com.android.ide.common.rendering.api.ResourceReference; 36import com.android.ide.common.rendering.api.ResourceValue; 37import com.android.ide.common.rendering.api.Result; 38import com.android.ide.common.rendering.api.Result.Status; 39import com.android.ide.common.rendering.api.SessionParams; 40import com.android.ide.common.rendering.api.SessionParams.RenderingMode; 41import com.android.ide.common.rendering.api.StyleResourceValue; 42import com.android.ide.common.rendering.api.ViewInfo; 43import com.android.ide.common.rendering.api.ViewType; 44import com.android.internal.util.XmlUtils; 45import com.android.internal.view.menu.ActionMenuItemView; 46import com.android.internal.view.menu.BridgeMenuItemImpl; 47import com.android.internal.view.menu.IconMenuItemView; 48import com.android.internal.view.menu.ListMenuItemView; 49import com.android.internal.view.menu.MenuItemImpl; 50import com.android.internal.view.menu.MenuView; 51import com.android.layoutlib.bridge.Bridge; 52import com.android.layoutlib.bridge.android.BridgeContext; 53import com.android.layoutlib.bridge.android.BridgeLayoutParamsMapAttributes; 54import com.android.layoutlib.bridge.android.BridgeXmlBlockParser; 55import com.android.layoutlib.bridge.android.RenderParamsFlags; 56import com.android.layoutlib.bridge.android.support.RecyclerViewUtil; 57import com.android.layoutlib.bridge.bars.BridgeActionBar; 58import com.android.layoutlib.bridge.bars.AppCompatActionBar; 59import com.android.layoutlib.bridge.bars.Config; 60import com.android.layoutlib.bridge.bars.NavigationBar; 61import com.android.layoutlib.bridge.bars.StatusBar; 62import com.android.layoutlib.bridge.bars.TitleBar; 63import com.android.layoutlib.bridge.bars.FrameworkActionBar; 64import com.android.layoutlib.bridge.impl.binding.FakeAdapter; 65import com.android.layoutlib.bridge.impl.binding.FakeExpandableAdapter; 66import com.android.resources.Density; 67import com.android.resources.ResourceType; 68import com.android.resources.ScreenOrientation; 69import com.android.util.Pair; 70 71import org.xmlpull.v1.XmlPullParserException; 72 73import android.animation.AnimationThread; 74import android.animation.Animator; 75import android.animation.AnimatorInflater; 76import android.animation.LayoutTransition; 77import android.animation.LayoutTransition.TransitionListener; 78import android.app.Fragment_Delegate; 79import android.graphics.Bitmap; 80import android.graphics.Bitmap_Delegate; 81import android.graphics.Canvas; 82import android.graphics.drawable.Drawable; 83import android.preference.Preference_Delegate; 84import android.util.DisplayMetrics; 85import android.util.TypedValue; 86import android.view.AttachInfo_Accessor; 87import android.view.BridgeInflater; 88import android.view.IWindowManager; 89import android.view.IWindowManagerImpl; 90import android.view.Surface; 91import android.view.View; 92import android.view.View.MeasureSpec; 93import android.view.ViewGroup; 94import android.view.ViewGroup.LayoutParams; 95import android.view.ViewGroup.MarginLayoutParams; 96import android.view.ViewParent; 97import android.view.WindowManagerGlobal_Delegate; 98import android.widget.AbsListView; 99import android.widget.AbsSpinner; 100import android.widget.ActionMenuView; 101import android.widget.AdapterView; 102import android.widget.ExpandableListView; 103import android.widget.FrameLayout; 104import android.widget.LinearLayout; 105import android.widget.ListView; 106import android.widget.QuickContactBadge; 107import android.widget.TabHost; 108import android.widget.TabHost.TabSpec; 109import android.widget.TabWidget; 110 111import java.awt.AlphaComposite; 112import java.awt.Color; 113import java.awt.Graphics2D; 114import java.awt.image.BufferedImage; 115import java.util.ArrayList; 116import java.util.List; 117import java.util.Map; 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.getProjectCallback()); 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.setProjectCallback(params.getProjectCallback()); 405 406 String rootTag = params.getFlag(RenderParamsFlags.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.setProjectCallback(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.getProjectCallback(), 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 558 // When disableBitmapCaching is true, we do not reuse mImage and 559 // we create a new one in every render. 560 // This is useful when mImage is just a wrapper of Graphics2D so 561 // it doesn't get cached. 562 boolean disableBitmapCaching = Boolean.TRUE.equals(params.getFlag( 563 RenderParamsFlags.FLAG_KEY_DISABLE_BITMAP_CACHING)); 564 if (newRenderSize || mCanvas == null || disableBitmapCaching) { 565 if (params.getImageFactory() != null) { 566 mImage = params.getImageFactory().getImage( 567 mMeasuredScreenWidth, 568 mMeasuredScreenHeight); 569 } else { 570 mImage = new BufferedImage( 571 mMeasuredScreenWidth, 572 mMeasuredScreenHeight, 573 BufferedImage.TYPE_INT_ARGB); 574 newImage = true; 575 } 576 577 if (params.isBgColorOverridden()) { 578 // since we override the content, it's the same as if it was a new image. 579 newImage = true; 580 Graphics2D gc = mImage.createGraphics(); 581 gc.setColor(new Color(params.getOverrideBgColor(), true)); 582 gc.setComposite(AlphaComposite.Src); 583 gc.fillRect(0, 0, mMeasuredScreenWidth, mMeasuredScreenHeight); 584 gc.dispose(); 585 } 586 587 // create an Android bitmap around the BufferedImage 588 Bitmap bitmap = Bitmap_Delegate.createBitmap(mImage, 589 true /*isMutable*/, hardwareConfig.getDensity()); 590 591 if (mCanvas == null) { 592 // create a Canvas around the Android bitmap 593 mCanvas = new Canvas(bitmap); 594 } else { 595 mCanvas.setBitmap(bitmap); 596 } 597 mCanvas.setDensity(hardwareConfig.getDensity().getDpiValue()); 598 } 599 600 if (freshRender && !newImage) { 601 Graphics2D gc = mImage.createGraphics(); 602 gc.setComposite(AlphaComposite.Src); 603 604 gc.setColor(new Color(0x00000000, true)); 605 gc.fillRect(0, 0, 606 mMeasuredScreenWidth, mMeasuredScreenHeight); 607 608 // done 609 gc.dispose(); 610 } 611 612 mViewRoot.draw(mCanvas); 613 } 614 615 mSystemViewInfoList = visitAllChildren(mViewRoot, 0, params.getExtendedViewInfoMode(), 616 false); 617 618 // success! 619 return SUCCESS.createResult(); 620 } catch (Throwable e) { 621 // get the real cause of the exception. 622 Throwable t = e; 623 while (t.getCause() != null) { 624 t = t.getCause(); 625 } 626 627 return ERROR_UNKNOWN.createResult(t.getMessage(), t); 628 } 629 } 630 631 /** 632 * Executes {@link View#measure(int, int)} on a given view with the given parameters (used 633 * to create measure specs with {@link MeasureSpec#makeMeasureSpec(int, int)}. 634 * 635 * if <var>measuredView</var> is non null, the method returns a {@link Pair} of (width, height) 636 * for the view (using {@link View#getMeasuredWidth()} and {@link View#getMeasuredHeight()}). 637 * 638 * @param viewToMeasure the view on which to execute measure(). 639 * @param measuredView if non null, the view to query for its measured width/height. 640 * @param width the width to use in the MeasureSpec. 641 * @param widthMode the MeasureSpec mode to use for the width. 642 * @param height the height to use in the MeasureSpec. 643 * @param heightMode the MeasureSpec mode to use for the height. 644 * @return the measured width/height if measuredView is non-null, null otherwise. 645 */ 646 @SuppressWarnings("deprecation") // For the use of Pair 647 private Pair<Integer, Integer> measureView(ViewGroup viewToMeasure, View measuredView, 648 int width, int widthMode, int height, int heightMode) { 649 int w_spec = MeasureSpec.makeMeasureSpec(width, widthMode); 650 int h_spec = MeasureSpec.makeMeasureSpec(height, heightMode); 651 viewToMeasure.measure(w_spec, h_spec); 652 653 if (measuredView != null) { 654 return Pair.of(measuredView.getMeasuredWidth(), measuredView.getMeasuredHeight()); 655 } 656 657 return null; 658 } 659 660 /** 661 * Animate an object 662 * <p> 663 * {@link #acquire(long)} must have been called before this. 664 * 665 * @throws IllegalStateException if the current context is different than the one owned by 666 * the scene, or if {@link #acquire(long)} was not called. 667 * 668 * @see RenderSession#animate(Object, String, boolean, IAnimationListener) 669 */ 670 public Result animate(Object targetObject, String animationName, 671 boolean isFrameworkAnimation, IAnimationListener listener) { 672 checkLock(); 673 674 BridgeContext context = getContext(); 675 676 // find the animation file. 677 ResourceValue animationResource; 678 int animationId = 0; 679 if (isFrameworkAnimation) { 680 animationResource = context.getRenderResources().getFrameworkResource( 681 ResourceType.ANIMATOR, animationName); 682 if (animationResource != null) { 683 animationId = Bridge.getResourceId(ResourceType.ANIMATOR, animationName); 684 } 685 } else { 686 animationResource = context.getRenderResources().getProjectResource( 687 ResourceType.ANIMATOR, animationName); 688 if (animationResource != null) { 689 animationId = context.getProjectCallback().getResourceId( 690 ResourceType.ANIMATOR, animationName); 691 } 692 } 693 694 if (animationResource != null) { 695 try { 696 Animator anim = AnimatorInflater.loadAnimator(context, animationId); 697 if (anim != null) { 698 anim.setTarget(targetObject); 699 700 new PlayAnimationThread(anim, this, animationName, listener).start(); 701 702 return SUCCESS.createResult(); 703 } 704 } catch (Exception e) { 705 // get the real cause of the exception. 706 Throwable t = e; 707 while (t.getCause() != null) { 708 t = t.getCause(); 709 } 710 711 return ERROR_UNKNOWN.createResult(t.getMessage(), t); 712 } 713 } 714 715 return ERROR_ANIM_NOT_FOUND.createResult(); 716 } 717 718 /** 719 * Insert a new child into an existing parent. 720 * <p> 721 * {@link #acquire(long)} must have been called before this. 722 * 723 * @throws IllegalStateException if the current context is different than the one owned by 724 * the scene, or if {@link #acquire(long)} was not called. 725 * 726 * @see RenderSession#insertChild(Object, ILayoutPullParser, int, IAnimationListener) 727 */ 728 public Result insertChild(final ViewGroup parentView, ILayoutPullParser childXml, 729 final int index, IAnimationListener listener) { 730 checkLock(); 731 732 BridgeContext context = getContext(); 733 734 // create a block parser for the XML 735 BridgeXmlBlockParser blockParser = new BridgeXmlBlockParser( 736 childXml, context, false /* platformResourceFlag */); 737 738 // inflate the child without adding it to the root since we want to control where it'll 739 // get added. We do pass the parentView however to ensure that the layoutParams will 740 // be created correctly. 741 final View child = mInflater.inflate(blockParser, parentView, false /*attachToRoot*/); 742 blockParser.ensurePopped(); 743 744 invalidateRenderingSize(); 745 746 if (listener != null) { 747 new AnimationThread(this, "insertChild", listener) { 748 749 @Override 750 public Result preAnimation() { 751 parentView.setLayoutTransition(new LayoutTransition()); 752 return addView(parentView, child, index); 753 } 754 755 @Override 756 public void postAnimation() { 757 parentView.setLayoutTransition(null); 758 } 759 }.start(); 760 761 // always return success since the real status will come through the listener. 762 return SUCCESS.createResult(child); 763 } 764 765 // add it to the parentView in the correct location 766 Result result = addView(parentView, child, index); 767 if (!result.isSuccess()) { 768 return result; 769 } 770 771 result = render(false /*freshRender*/); 772 if (result.isSuccess()) { 773 result = result.getCopyWithData(child); 774 } 775 776 return result; 777 } 778 779 /** 780 * Adds a given view to a given parent at a given index. 781 * 782 * @param parent the parent to receive the view 783 * @param view the view to add to the parent 784 * @param index the index where to do the add. 785 * 786 * @return a Result with {@link Status#SUCCESS} or 787 * {@link Status#ERROR_VIEWGROUP_NO_CHILDREN} if the given parent doesn't support 788 * adding views. 789 */ 790 private Result addView(ViewGroup parent, View view, int index) { 791 try { 792 parent.addView(view, index); 793 return SUCCESS.createResult(); 794 } catch (UnsupportedOperationException e) { 795 // looks like this is a view class that doesn't support children manipulation! 796 return ERROR_VIEWGROUP_NO_CHILDREN.createResult(); 797 } 798 } 799 800 /** 801 * Moves a view to a new parent at a given location 802 * <p> 803 * {@link #acquire(long)} must have been called before this. 804 * 805 * @throws IllegalStateException if the current context is different than the one owned by 806 * the scene, or if {@link #acquire(long)} was not called. 807 * 808 * @see RenderSession#moveChild(Object, Object, int, Map, IAnimationListener) 809 */ 810 public Result moveChild(final ViewGroup newParentView, final View childView, final int index, 811 Map<String, String> layoutParamsMap, final IAnimationListener listener) { 812 checkLock(); 813 814 invalidateRenderingSize(); 815 816 LayoutParams layoutParams = null; 817 if (layoutParamsMap != null) { 818 // need to create a new LayoutParams object for the new parent. 819 layoutParams = newParentView.generateLayoutParams( 820 new BridgeLayoutParamsMapAttributes(layoutParamsMap)); 821 } 822 823 // get the current parent of the view that needs to be moved. 824 final ViewGroup previousParent = (ViewGroup) childView.getParent(); 825 826 if (listener != null) { 827 final LayoutParams params = layoutParams; 828 829 // there is no support for animating views across layouts, so in case the new and old 830 // parent views are different we fake the animation through a no animation thread. 831 if (previousParent != newParentView) { 832 new Thread("not animated moveChild") { 833 @Override 834 public void run() { 835 Result result = moveView(previousParent, newParentView, childView, index, 836 params); 837 if (!result.isSuccess()) { 838 listener.done(result); 839 } 840 841 // ready to do the work, acquire the scene. 842 result = acquire(250); 843 if (!result.isSuccess()) { 844 listener.done(result); 845 return; 846 } 847 848 try { 849 result = render(false /*freshRender*/); 850 if (result.isSuccess()) { 851 listener.onNewFrame(RenderSessionImpl.this.getSession()); 852 } 853 } finally { 854 release(); 855 } 856 857 listener.done(result); 858 } 859 }.start(); 860 } else { 861 new AnimationThread(this, "moveChild", listener) { 862 863 @Override 864 public Result preAnimation() { 865 // set up the transition for the parent. 866 LayoutTransition transition = new LayoutTransition(); 867 previousParent.setLayoutTransition(transition); 868 869 // tweak the animation durations and start delays (to match the duration of 870 // animation playing just before). 871 // Note: Cannot user Animation.setDuration() directly. Have to set it 872 // on the LayoutTransition. 873 transition.setDuration(LayoutTransition.DISAPPEARING, 100); 874 // CHANGE_DISAPPEARING plays after DISAPPEARING 875 transition.setStartDelay(LayoutTransition.CHANGE_DISAPPEARING, 100); 876 877 transition.setDuration(LayoutTransition.CHANGE_DISAPPEARING, 100); 878 879 transition.setDuration(LayoutTransition.CHANGE_APPEARING, 100); 880 // CHANGE_APPEARING plays after CHANGE_APPEARING 881 transition.setStartDelay(LayoutTransition.APPEARING, 100); 882 883 transition.setDuration(LayoutTransition.APPEARING, 100); 884 885 return moveView(previousParent, newParentView, childView, index, params); 886 } 887 888 @Override 889 public void postAnimation() { 890 previousParent.setLayoutTransition(null); 891 newParentView.setLayoutTransition(null); 892 } 893 }.start(); 894 } 895 896 // always return success since the real status will come through the listener. 897 return SUCCESS.createResult(layoutParams); 898 } 899 900 Result result = moveView(previousParent, newParentView, childView, index, layoutParams); 901 if (!result.isSuccess()) { 902 return result; 903 } 904 905 result = render(false /*freshRender*/); 906 if (layoutParams != null && result.isSuccess()) { 907 result = result.getCopyWithData(layoutParams); 908 } 909 910 return result; 911 } 912 913 /** 914 * Moves a View from its current parent to a new given parent at a new given location, with 915 * an optional new {@link LayoutParams} instance 916 * 917 * @param previousParent the previous parent, still owning the child at the time of the call. 918 * @param newParent the new parent 919 * @param movedView the view to move 920 * @param index the new location in the new parent 921 * @param params an option (can be null) {@link LayoutParams} instance. 922 * 923 * @return a Result with {@link Status#SUCCESS} or 924 * {@link Status#ERROR_VIEWGROUP_NO_CHILDREN} if the given parent doesn't support 925 * adding views. 926 */ 927 private Result moveView(ViewGroup previousParent, final ViewGroup newParent, 928 final View movedView, final int index, final LayoutParams params) { 929 try { 930 // check if there is a transition on the previousParent. 931 LayoutTransition previousTransition = previousParent.getLayoutTransition(); 932 if (previousTransition != null) { 933 // in this case there is an animation. This means we have to wait for the child's 934 // parent reference to be null'ed out so that we can add it to the new parent. 935 // It is technically removed right before the DISAPPEARING animation is done (if 936 // the animation of this type is not null, otherwise it's after which is impossible 937 // to handle). 938 // Because there is no move animation, if the new parent is the same as the old 939 // parent, we need to wait until the CHANGE_DISAPPEARING animation is done before 940 // adding the child or the child will appear in its new location before the 941 // other children have made room for it. 942 943 // add a listener to the transition to be notified of the actual removal. 944 previousTransition.addTransitionListener(new TransitionListener() { 945 private int mChangeDisappearingCount = 0; 946 947 @Override 948 public void startTransition(LayoutTransition transition, ViewGroup container, 949 View view, int transitionType) { 950 if (transitionType == LayoutTransition.CHANGE_DISAPPEARING) { 951 mChangeDisappearingCount++; 952 } 953 } 954 955 @Override 956 public void endTransition(LayoutTransition transition, ViewGroup container, 957 View view, int transitionType) { 958 if (transitionType == LayoutTransition.CHANGE_DISAPPEARING) { 959 mChangeDisappearingCount--; 960 } 961 962 if (transitionType == LayoutTransition.CHANGE_DISAPPEARING && 963 mChangeDisappearingCount == 0) { 964 // add it to the parentView in the correct location 965 if (params != null) { 966 newParent.addView(movedView, index, params); 967 } else { 968 newParent.addView(movedView, index); 969 } 970 } 971 } 972 }); 973 974 // remove the view from the current parent. 975 previousParent.removeView(movedView); 976 977 // and return since adding the view to the new parent is done in the listener. 978 return SUCCESS.createResult(); 979 } else { 980 // standard code with no animation. pretty simple. 981 previousParent.removeView(movedView); 982 983 // add it to the parentView in the correct location 984 if (params != null) { 985 newParent.addView(movedView, index, params); 986 } else { 987 newParent.addView(movedView, index); 988 } 989 990 return SUCCESS.createResult(); 991 } 992 } catch (UnsupportedOperationException e) { 993 // looks like this is a view class that doesn't support children manipulation! 994 return ERROR_VIEWGROUP_NO_CHILDREN.createResult(); 995 } 996 } 997 998 /** 999 * Removes a child from its current parent. 1000 * <p> 1001 * {@link #acquire(long)} must have been called before this. 1002 * 1003 * @throws IllegalStateException if the current context is different than the one owned by 1004 * the scene, or if {@link #acquire(long)} was not called. 1005 * 1006 * @see RenderSession#removeChild(Object, IAnimationListener) 1007 */ 1008 public Result removeChild(final View childView, IAnimationListener listener) { 1009 checkLock(); 1010 1011 invalidateRenderingSize(); 1012 1013 final ViewGroup parent = (ViewGroup) childView.getParent(); 1014 1015 if (listener != null) { 1016 new AnimationThread(this, "moveChild", listener) { 1017 1018 @Override 1019 public Result preAnimation() { 1020 parent.setLayoutTransition(new LayoutTransition()); 1021 return removeView(parent, childView); 1022 } 1023 1024 @Override 1025 public void postAnimation() { 1026 parent.setLayoutTransition(null); 1027 } 1028 }.start(); 1029 1030 // always return success since the real status will come through the listener. 1031 return SUCCESS.createResult(); 1032 } 1033 1034 Result result = removeView(parent, childView); 1035 if (!result.isSuccess()) { 1036 return result; 1037 } 1038 1039 return render(false /*freshRender*/); 1040 } 1041 1042 /** 1043 * Removes a given view from its current parent. 1044 * 1045 * @param view the view to remove from its parent 1046 * 1047 * @return a Result with {@link Status#SUCCESS} or 1048 * {@link Status#ERROR_VIEWGROUP_NO_CHILDREN} if the given parent doesn't support 1049 * adding views. 1050 */ 1051 private Result removeView(ViewGroup parent, View view) { 1052 try { 1053 parent.removeView(view); 1054 return SUCCESS.createResult(); 1055 } catch (UnsupportedOperationException e) { 1056 // looks like this is a view class that doesn't support children manipulation! 1057 return ERROR_VIEWGROUP_NO_CHILDREN.createResult(); 1058 } 1059 } 1060 1061 1062 private void findBackground(RenderResources resources) { 1063 if (!getParams().isBgColorOverridden()) { 1064 mWindowBackground = resources.findItemInTheme("windowBackground", 1065 true /*isFrameworkAttr*/); 1066 if (mWindowBackground != null) { 1067 mWindowBackground = resources.resolveResValue(mWindowBackground); 1068 } 1069 } 1070 } 1071 1072 private boolean hasSoftwareButtons() { 1073 return getParams().getHardwareConfig().hasSoftwareButtons(); 1074 } 1075 1076 private void findStatusBar(RenderResources resources, DisplayMetrics metrics) { 1077 boolean windowFullscreen = getBooleanThemeValue(resources, 1078 "windowFullscreen", false, !isThemeAppCompat(resources)); 1079 1080 if (!windowFullscreen && !mWindowIsFloating) { 1081 // default value 1082 mStatusBarSize = DEFAULT_STATUS_BAR_HEIGHT; 1083 1084 // get the real value 1085 ResourceValue value = resources.getFrameworkResource(ResourceType.DIMEN, 1086 "status_bar_height"); 1087 1088 if (value != null) { 1089 TypedValue typedValue = ResourceHelper.getValue("status_bar_height", 1090 value.getValue(), true /*requireUnit*/); 1091 if (typedValue != null) { 1092 // compute the pixel value based on the display metrics 1093 mStatusBarSize = (int)typedValue.getDimension(metrics); 1094 } 1095 } 1096 } 1097 } 1098 1099 private void findActionBar(RenderResources resources, DisplayMetrics metrics) { 1100 if (mWindowIsFloating) { 1101 return; 1102 } 1103 1104 boolean windowActionBar = getBooleanThemeValue(resources, 1105 "windowActionBar", true, !isThemeAppCompat(resources)); 1106 1107 // if there's a value and it's false (default is true) 1108 if (windowActionBar) { 1109 1110 // default size of the window title bar 1111 mActionBarSize = DEFAULT_TITLE_BAR_HEIGHT; 1112 1113 // get value from the theme. 1114 ResourceValue value = resources.findItemInTheme("actionBarSize", 1115 true /*isFrameworkAttr*/); 1116 1117 // resolve it 1118 value = resources.resolveResValue(value); 1119 1120 if (value != null) { 1121 // get the numerical value, if available 1122 TypedValue typedValue = ResourceHelper.getValue("actionBarSize", value.getValue(), 1123 true /*requireUnit*/); 1124 if (typedValue != null) { 1125 // compute the pixel value based on the display metrics 1126 mActionBarSize = (int)typedValue.getDimension(metrics); 1127 } 1128 } 1129 } else { 1130 // action bar overrides title bar so only look for this one if action bar is hidden 1131 boolean windowNoTitle = getBooleanThemeValue(resources, "windowNoTitle", false, true); 1132 1133 if (!windowNoTitle) { 1134 1135 // default size of the window title bar 1136 mTitleBarSize = DEFAULT_TITLE_BAR_HEIGHT; 1137 1138 // get value from the theme. 1139 ResourceValue value = resources.findItemInTheme("windowTitleSize", 1140 true /*isFrameworkAttr*/); 1141 1142 // resolve it 1143 value = resources.resolveResValue(value); 1144 1145 if (value != null) { 1146 // get the numerical value, if available 1147 TypedValue typedValue = ResourceHelper.getValue("windowTitleSize", 1148 value.getValue(), true /*requireUnit*/); 1149 if (typedValue != null) { 1150 // compute the pixel value based on the display metrics 1151 mTitleBarSize = (int)typedValue.getDimension(metrics); 1152 } 1153 } 1154 } 1155 1156 } 1157 } 1158 1159 private void findNavigationBar(RenderResources resources, DisplayMetrics metrics) { 1160 if (hasSoftwareButtons() && !mWindowIsFloating) { 1161 1162 // default value 1163 mNavigationBarSize = 48; // ?? 1164 1165 HardwareConfig hardwareConfig = getParams().getHardwareConfig(); 1166 1167 boolean barOnBottom = true; 1168 1169 if (hardwareConfig.getOrientation() == ScreenOrientation.LANDSCAPE) { 1170 // compute the dp of the screen. 1171 int shortSize = hardwareConfig.getScreenHeight(); 1172 1173 // compute in dp 1174 int shortSizeDp = shortSize * DisplayMetrics.DENSITY_DEFAULT / 1175 hardwareConfig.getDensity().getDpiValue(); 1176 1177 // 0-599dp: "phone" UI with bar on the side 1178 // 600+dp: "tablet" UI with bar on the bottom 1179 barOnBottom = shortSizeDp >= 600; 1180 } 1181 1182 if (barOnBottom) { 1183 mNavigationBarOrientation = LinearLayout.HORIZONTAL; 1184 } else { 1185 mNavigationBarOrientation = LinearLayout.VERTICAL; 1186 } 1187 1188 // get the real value 1189 ResourceValue value = resources.getFrameworkResource(ResourceType.DIMEN, 1190 barOnBottom ? "navigation_bar_height" : "navigation_bar_width"); 1191 1192 if (value != null) { 1193 TypedValue typedValue = ResourceHelper.getValue("navigation_bar_height", 1194 value.getValue(), true /*requireUnit*/); 1195 if (typedValue != null) { 1196 // compute the pixel value based on the display metrics 1197 mNavigationBarSize = (int)typedValue.getDimension(metrics); 1198 } 1199 } 1200 } 1201 } 1202 1203 private boolean isThemeAppCompat(RenderResources resources) { 1204 // Ideally, we should check if the corresponding activity extends 1205 // android.support.v7.app.ActionBarActivity, and not care about the theme name at all. 1206 if (mIsThemeAppCompat == null) { 1207 StyleResourceValue defaultTheme = resources.getDefaultTheme(); 1208 // We can't simply check for parent using resources.themeIsParentOf() since the 1209 // inheritance structure isn't really what one would expect. The first common parent 1210 // between Theme.AppCompat.Light and Theme.AppCompat is Theme.Material (for v21). 1211 boolean isThemeAppCompat = false; 1212 for (int i = 0; i < 50; i++) { 1213 // for loop ensures that we don't run into cyclic theme inheritance. 1214 if (defaultTheme.getName().startsWith("Theme.AppCompat")) { 1215 isThemeAppCompat = true; 1216 break; 1217 } 1218 defaultTheme = resources.getParent(defaultTheme); 1219 if (defaultTheme == null) { 1220 break; 1221 } 1222 } 1223 mIsThemeAppCompat = isThemeAppCompat; 1224 } 1225 return mIsThemeAppCompat; 1226 } 1227 1228 /** 1229 * Looks for an attribute in the current theme. 1230 * 1231 * @param resources the render resources 1232 * @param name the name of the attribute 1233 * @param defaultValue the default value. 1234 * @param isFrameworkAttr if the attribute is in android namespace 1235 * @return the value of the attribute or the default one if not found. 1236 */ 1237 private boolean getBooleanThemeValue(RenderResources resources, 1238 String name, boolean defaultValue, boolean isFrameworkAttr) { 1239 1240 ResourceValue value = resources.findItemInTheme(name, isFrameworkAttr); 1241 1242 // because it may reference something else, we resolve it. 1243 value = resources.resolveResValue(value); 1244 1245 // if there's no value, return the default. 1246 if (value == null || value.getValue() == null) { 1247 return defaultValue; 1248 } 1249 1250 return XmlUtils.convertValueToBoolean(value.getValue(), defaultValue); 1251 } 1252 1253 /** 1254 * Post process on a view hierarchy that was just inflated. 1255 * <p/> 1256 * At the moment this only supports TabHost: If {@link TabHost} is detected, look for the 1257 * {@link TabWidget}, and the corresponding {@link FrameLayout} and make new tabs automatically 1258 * based on the content of the {@link FrameLayout}. 1259 * @param view the root view to process. 1260 * @param projectCallback callback to the project. 1261 * @param skip the view and it's children are not processed. 1262 */ 1263 @SuppressWarnings("deprecation") // For the use of Pair 1264 private void postInflateProcess(View view, IProjectCallback projectCallback, View skip) 1265 throws PostInflateException { 1266 if (view == skip) { 1267 return; 1268 } 1269 if (view instanceof TabHost) { 1270 setupTabHost((TabHost) view, projectCallback); 1271 } else if (view instanceof QuickContactBadge) { 1272 QuickContactBadge badge = (QuickContactBadge) view; 1273 badge.setImageToDefault(); 1274 } else if (view instanceof AdapterView<?>) { 1275 // get the view ID. 1276 int id = view.getId(); 1277 1278 BridgeContext context = getContext(); 1279 1280 // get a ResourceReference from the integer ID. 1281 ResourceReference listRef = context.resolveId(id); 1282 1283 if (listRef != null) { 1284 SessionParams params = getParams(); 1285 AdapterBinding binding = params.getAdapterBindings().get(listRef); 1286 1287 // if there was no adapter binding, trying to get it from the call back. 1288 if (binding == null) { 1289 binding = params.getProjectCallback().getAdapterBinding(listRef, 1290 context.getViewKey(view), view); 1291 } 1292 1293 if (binding != null) { 1294 1295 if (view instanceof AbsListView) { 1296 if ((binding.getFooterCount() > 0 || binding.getHeaderCount() > 0) && 1297 view instanceof ListView) { 1298 ListView list = (ListView) view; 1299 1300 boolean skipCallbackParser = false; 1301 1302 int count = binding.getHeaderCount(); 1303 for (int i = 0; i < count; i++) { 1304 Pair<View, Boolean> pair = context.inflateView( 1305 binding.getHeaderAt(i), 1306 list, false /*attachToRoot*/, skipCallbackParser); 1307 if (pair.getFirst() != null) { 1308 list.addHeaderView(pair.getFirst()); 1309 } 1310 1311 skipCallbackParser |= pair.getSecond(); 1312 } 1313 1314 count = binding.getFooterCount(); 1315 for (int i = 0; i < count; i++) { 1316 Pair<View, Boolean> pair = context.inflateView( 1317 binding.getFooterAt(i), 1318 list, false /*attachToRoot*/, skipCallbackParser); 1319 if (pair.getFirst() != null) { 1320 list.addFooterView(pair.getFirst()); 1321 } 1322 1323 skipCallbackParser |= pair.getSecond(); 1324 } 1325 } 1326 1327 if (view instanceof ExpandableListView) { 1328 ((ExpandableListView) view).setAdapter( 1329 new FakeExpandableAdapter( 1330 listRef, binding, params.getProjectCallback())); 1331 } else { 1332 ((AbsListView) view).setAdapter( 1333 new FakeAdapter( 1334 listRef, binding, params.getProjectCallback())); 1335 } 1336 } else if (view instanceof AbsSpinner) { 1337 ((AbsSpinner) view).setAdapter( 1338 new FakeAdapter( 1339 listRef, binding, params.getProjectCallback())); 1340 } 1341 } 1342 } 1343 } else if (isInstanceOf(view, RecyclerViewUtil.CN_RECYCLER_VIEW)) { 1344 RecyclerViewUtil.setAdapter(view, getContext(), getParams()); 1345 } else if (view instanceof ViewGroup) { 1346 ViewGroup group = (ViewGroup) view; 1347 final int count = group.getChildCount(); 1348 for (int c = 0; c < count; c++) { 1349 View child = group.getChildAt(c); 1350 postInflateProcess(child, projectCallback, skip); 1351 } 1352 } 1353 } 1354 1355 /** 1356 * Check if the object is an instance of a class named {@code className}. This doesn't work 1357 * for interfaces. 1358 */ 1359 public static boolean isInstanceOf(Object object, String className) { 1360 Class superClass = object.getClass(); 1361 while (superClass != null) { 1362 String name = superClass.getName(); 1363 if (name.equals(className)) { 1364 return true; 1365 } 1366 superClass = superClass.getSuperclass(); 1367 } 1368 return false; 1369 } 1370 1371 /** 1372 * Sets up a {@link TabHost} object. 1373 * @param tabHost the TabHost to setup. 1374 * @param projectCallback The project callback object to access the project R class. 1375 * @throws PostInflateException 1376 */ 1377 private void setupTabHost(TabHost tabHost, IProjectCallback projectCallback) 1378 throws PostInflateException { 1379 // look for the TabWidget, and the FrameLayout. They have their own specific names 1380 View v = tabHost.findViewById(android.R.id.tabs); 1381 1382 if (v == null) { 1383 throw new PostInflateException( 1384 "TabHost requires a TabWidget with id \"android:id/tabs\".\n"); 1385 } 1386 1387 if (!(v instanceof TabWidget)) { 1388 throw new PostInflateException(String.format( 1389 "TabHost requires a TabWidget with id \"android:id/tabs\".\n" + 1390 "View found with id 'tabs' is '%s'", v.getClass().getCanonicalName())); 1391 } 1392 1393 v = tabHost.findViewById(android.R.id.tabcontent); 1394 1395 if (v == null) { 1396 // TODO: see if we can fake tabs even without the FrameLayout (same below when the frameLayout is empty) 1397 //noinspection SpellCheckingInspection 1398 throw new PostInflateException( 1399 "TabHost requires a FrameLayout with id \"android:id/tabcontent\"."); 1400 } 1401 1402 if (!(v instanceof FrameLayout)) { 1403 //noinspection SpellCheckingInspection 1404 throw new PostInflateException(String.format( 1405 "TabHost requires a FrameLayout with id \"android:id/tabcontent\".\n" + 1406 "View found with id 'tabcontent' is '%s'", v.getClass().getCanonicalName())); 1407 } 1408 1409 FrameLayout content = (FrameLayout)v; 1410 1411 // now process the content of the frameLayout and dynamically create tabs for it. 1412 final int count = content.getChildCount(); 1413 1414 // this must be called before addTab() so that the TabHost searches its TabWidget 1415 // and FrameLayout. 1416 tabHost.setup(); 1417 1418 if (count == 0) { 1419 // Create a dummy child to get a single tab 1420 TabSpec spec = tabHost.newTabSpec("tag").setIndicator("Tab Label", 1421 tabHost.getResources().getDrawable(android.R.drawable.ic_menu_info_details)) 1422 .setContent(new TabHost.TabContentFactory() { 1423 @Override 1424 public View createTabContent(String tag) { 1425 return new LinearLayout(getContext()); 1426 } 1427 }); 1428 tabHost.addTab(spec); 1429 } else { 1430 // for each child of the frameLayout, add a new TabSpec 1431 for (int i = 0 ; i < count ; i++) { 1432 View child = content.getChildAt(i); 1433 String tabSpec = String.format("tab_spec%d", i+1); 1434 @SuppressWarnings("ConstantConditions") // child cannot be null. 1435 int id = child.getId(); 1436 @SuppressWarnings("deprecation") 1437 Pair<ResourceType, String> resource = projectCallback.resolveResourceId(id); 1438 String name; 1439 if (resource != null) { 1440 name = resource.getSecond(); 1441 } else { 1442 name = String.format("Tab %d", i+1); // default name if id is unresolved. 1443 } 1444 tabHost.addTab(tabHost.newTabSpec(tabSpec).setIndicator(name).setContent(id)); 1445 } 1446 } 1447 } 1448 1449 /** 1450 * Visits a {@link View} and its children and generate a {@link ViewInfo} containing the 1451 * bounds of all the views. 1452 * 1453 * @param view the root View 1454 * @param offset an offset for the view bounds. 1455 * @param setExtendedInfo whether to set the extended view info in the {@link ViewInfo} object. 1456 * @param isContentFrame {@code true} if the {@code ViewInfo} to be created is part of the 1457 * content frame. 1458 * 1459 * @return {@code ViewInfo} containing the bounds of the view and it children otherwise. 1460 */ 1461 private ViewInfo visit(View view, int offset, boolean setExtendedInfo, 1462 boolean isContentFrame) { 1463 ViewInfo result = createViewInfo(view, offset, setExtendedInfo, isContentFrame); 1464 1465 if (view instanceof ViewGroup) { 1466 ViewGroup group = ((ViewGroup) view); 1467 result.setChildren(visitAllChildren(group, isContentFrame ? 0 : offset, 1468 setExtendedInfo, isContentFrame)); 1469 } 1470 return result; 1471 } 1472 1473 /** 1474 * Visits all the children of a given ViewGroup and generates a list of {@link ViewInfo} 1475 * containing the bounds of all the views. It also initializes the {@link #mViewInfoList} with 1476 * the children of the {@code mContentRoot}. 1477 * 1478 * @param viewGroup the root View 1479 * @param offset an offset from the top for the content view frame. 1480 * @param setExtendedInfo whether to set the extended view info in the {@link ViewInfo} object. 1481 * @param isContentFrame {@code true} if the {@code ViewInfo} to be created is part of the 1482 * content frame. {@code false} if the {@code ViewInfo} to be created is 1483 * part of the system decor. 1484 */ 1485 private List<ViewInfo> visitAllChildren(ViewGroup viewGroup, int offset, 1486 boolean setExtendedInfo, boolean isContentFrame) { 1487 if (viewGroup == null) { 1488 return null; 1489 } 1490 1491 if (!isContentFrame) { 1492 offset += viewGroup.getTop(); 1493 } 1494 1495 int childCount = viewGroup.getChildCount(); 1496 if (viewGroup == mContentRoot) { 1497 List<ViewInfo> childrenWithoutOffset = new ArrayList<ViewInfo>(childCount); 1498 List<ViewInfo> childrenWithOffset = new ArrayList<ViewInfo>(childCount); 1499 for (int i = 0; i < childCount; i++) { 1500 ViewInfo[] childViewInfo = visitContentRoot(viewGroup.getChildAt(i), offset, 1501 setExtendedInfo); 1502 childrenWithoutOffset.add(childViewInfo[0]); 1503 childrenWithOffset.add(childViewInfo[1]); 1504 } 1505 mViewInfoList = childrenWithOffset; 1506 return childrenWithoutOffset; 1507 } else { 1508 List<ViewInfo> children = new ArrayList<ViewInfo>(childCount); 1509 for (int i = 0; i < childCount; i++) { 1510 children.add(visit(viewGroup.getChildAt(i), offset, setExtendedInfo, 1511 isContentFrame)); 1512 } 1513 return children; 1514 } 1515 } 1516 1517 /** 1518 * Visits the children of {@link #mContentRoot} and generates {@link ViewInfo} containing the 1519 * bounds of all the views. It returns two {@code ViewInfo} objects with the same children, 1520 * one with the {@code offset} and other without the {@code offset}. The offset is needed to 1521 * get the right bounds if the {@code ViewInfo} hierarchy is accessed from 1522 * {@code mViewInfoList}. When the hierarchy is accessed via {@code mSystemViewInfoList}, the 1523 * offset is not needed. 1524 * 1525 * @return an array of length two, with ViewInfo at index 0 is without offset and ViewInfo at 1526 * index 1 is with the offset. 1527 */ 1528 @NonNull 1529 private ViewInfo[] visitContentRoot(View view, int offset, boolean setExtendedInfo) { 1530 ViewInfo[] result = new ViewInfo[2]; 1531 if (view == null) { 1532 return result; 1533 } 1534 1535 result[0] = createViewInfo(view, 0, setExtendedInfo, true); 1536 result[1] = createViewInfo(view, offset, setExtendedInfo, true); 1537 if (view instanceof ViewGroup) { 1538 List<ViewInfo> children = visitAllChildren((ViewGroup) view, 0, setExtendedInfo, true); 1539 result[0].setChildren(children); 1540 result[1].setChildren(children); 1541 } 1542 return result; 1543 } 1544 1545 /** 1546 * Creates a {@link ViewInfo} for the view. The {@code ViewInfo} corresponding to the children 1547 * of the {@code view} are not created. Consequently, the children of {@code ViewInfo} is not 1548 * set. 1549 * @param offset an offset for the view bounds. Used only if view is part of the content frame. 1550 */ 1551 private ViewInfo createViewInfo(View view, int offset, boolean setExtendedInfo, 1552 boolean isContentFrame) { 1553 if (view == null) { 1554 return null; 1555 } 1556 1557 ViewInfo result; 1558 if (isContentFrame) { 1559 // The view is part of the layout added by the user. Hence, 1560 // the ViewCookie may be obtained only through the Context. 1561 result = new ViewInfo(view.getClass().getName(), 1562 getContext().getViewKey(view), 1563 view.getLeft(), view.getTop() + offset, view.getRight(), 1564 view.getBottom() + offset, view, view.getLayoutParams()); 1565 } else { 1566 // We are part of the system decor. 1567 SystemViewInfo r = new SystemViewInfo(view.getClass().getName(), 1568 getViewKey(view), 1569 view.getLeft(), view.getTop(), view.getRight(), 1570 view.getBottom(), view, view.getLayoutParams()); 1571 result = r; 1572 // We currently mark three kinds of views: 1573 // 1. Menus in the Action Bar 1574 // 2. Menus in the Overflow popup. 1575 // 3. The overflow popup button. 1576 if (view instanceof ListMenuItemView) { 1577 // Mark 2. 1578 // All menus in the popup are of type ListMenuItemView. 1579 r.setViewType(ViewType.ACTION_BAR_OVERFLOW_MENU); 1580 } else { 1581 // Mark 3. 1582 ViewGroup.LayoutParams lp = view.getLayoutParams(); 1583 if (lp instanceof ActionMenuView.LayoutParams && 1584 ((ActionMenuView.LayoutParams) lp).isOverflowButton) { 1585 r.setViewType(ViewType.ACTION_BAR_OVERFLOW); 1586 } else { 1587 // Mark 1. 1588 // A view is a menu in the Action Bar is it is not the overflow button and of 1589 // its parent is of type ActionMenuView. We can also check if the view is 1590 // instanceof ActionMenuItemView but that will fail for menus using 1591 // actionProviderClass. 1592 ViewParent parent = view.getParent(); 1593 while (parent != mViewRoot && parent instanceof ViewGroup) { 1594 if (parent instanceof ActionMenuView) { 1595 r.setViewType(ViewType.ACTION_BAR_MENU); 1596 break; 1597 } 1598 parent = parent.getParent(); 1599 } 1600 } 1601 } 1602 } 1603 1604 if (setExtendedInfo) { 1605 MarginLayoutParams marginParams = null; 1606 LayoutParams params = view.getLayoutParams(); 1607 if (params instanceof MarginLayoutParams) { 1608 marginParams = (MarginLayoutParams) params; 1609 } 1610 result.setExtendedInfo(view.getBaseline(), 1611 marginParams != null ? marginParams.leftMargin : 0, 1612 marginParams != null ? marginParams.topMargin : 0, 1613 marginParams != null ? marginParams.rightMargin : 0, 1614 marginParams != null ? marginParams.bottomMargin : 0); 1615 } 1616 1617 return result; 1618 } 1619 1620 /* (non-Javadoc) 1621 * The cookie for menu items are stored in menu item and not in the map from View stored in 1622 * BridgeContext. 1623 */ 1624 @Nullable 1625 private Object getViewKey(View view) { 1626 BridgeContext context = getContext(); 1627 if (!(view instanceof MenuView.ItemView)) { 1628 return context.getViewKey(view); 1629 } 1630 MenuItemImpl menuItem; 1631 if (view instanceof ActionMenuItemView) { 1632 menuItem = ((ActionMenuItemView) view).getItemData(); 1633 } else if (view instanceof ListMenuItemView) { 1634 menuItem = ((ListMenuItemView) view).getItemData(); 1635 } else if (view instanceof IconMenuItemView) { 1636 menuItem = ((IconMenuItemView) view).getItemData(); 1637 } else { 1638 menuItem = null; 1639 } 1640 if (menuItem instanceof BridgeMenuItemImpl) { 1641 return ((BridgeMenuItemImpl) menuItem).getViewCookie(); 1642 } 1643 1644 return null; 1645 } 1646 1647 public void invalidateRenderingSize() { 1648 mMeasuredScreenWidth = mMeasuredScreenHeight = -1; 1649 } 1650 1651 /** 1652 * Creates the status bar with wifi and battery icons. 1653 */ 1654 private StatusBar createStatusBar(BridgeContext context, Density density, int direction, 1655 boolean isRtlSupported, int platformVersion) throws XmlPullParserException { 1656 StatusBar statusBar = new StatusBar(context, density, 1657 direction, isRtlSupported, platformVersion); 1658 statusBar.setLayoutParams( 1659 new LinearLayout.LayoutParams( 1660 LayoutParams.MATCH_PARENT, mStatusBarSize)); 1661 return statusBar; 1662 } 1663 1664 /** 1665 * Creates the navigation bar with back, home and recent buttons. 1666 * 1667 * @param isRtl true if the current locale is right-to-left 1668 * @param isRtlSupported true is the project manifest declares that the application 1669 * is RTL aware. 1670 */ 1671 private NavigationBar createNavigationBar(BridgeContext context, Density density, 1672 boolean isRtl, boolean isRtlSupported, int simulatedPlatformVersion) 1673 throws XmlPullParserException { 1674 NavigationBar navigationBar = new NavigationBar(context, 1675 density, mNavigationBarOrientation, isRtl, 1676 isRtlSupported, simulatedPlatformVersion); 1677 if (mNavigationBarOrientation == LinearLayout.VERTICAL) { 1678 navigationBar.setLayoutParams(new LinearLayout.LayoutParams(mNavigationBarSize, 1679 LayoutParams.MATCH_PARENT)); 1680 } else { 1681 navigationBar.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 1682 mNavigationBarSize)); 1683 } 1684 return navigationBar; 1685 } 1686 1687 private TitleBar createTitleBar(BridgeContext context, String title, 1688 int simulatedPlatformVersion) 1689 throws XmlPullParserException { 1690 TitleBar titleBar = new TitleBar(context, title, simulatedPlatformVersion); 1691 titleBar.setLayoutParams( 1692 new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, mTitleBarSize)); 1693 return titleBar; 1694 } 1695 1696 /** 1697 * Creates the action bar. Also queries the project callback for missing information. 1698 */ 1699 private BridgeActionBar createActionBar(BridgeContext context, SessionParams params, 1700 ViewGroup parentView) { 1701 if (mIsThemeAppCompat == Boolean.TRUE) { 1702 return new AppCompatActionBar(context, params, parentView); 1703 } else { 1704 return new FrameworkActionBar(context, params, parentView); 1705 } 1706 } 1707 1708 public BufferedImage getImage() { 1709 return mImage; 1710 } 1711 1712 public boolean isAlphaChannelImage() { 1713 return mIsAlphaChannelImage; 1714 } 1715 1716 public List<ViewInfo> getViewInfos() { 1717 return mViewInfoList; 1718 } 1719 1720 public List<ViewInfo> getSystemViewInfos() { 1721 return mSystemViewInfoList; 1722 } 1723 1724 public Map<String, String> getDefaultProperties(Object viewObject) { 1725 return getContext().getDefaultPropMap(viewObject); 1726 } 1727 1728 public void setScene(RenderSession session) { 1729 mScene = session; 1730 } 1731 1732 public RenderSession getSession() { 1733 return mScene; 1734 } 1735} 1736