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