RenderSessionImpl.java revision f3cb4ba213a0fa4d1c184c430a2eaac7e27ccf6f
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.layoutlib.bridge.impl;
18
19import com.android.annotations.NonNull;
20import com.android.annotations.Nullable;
21import com.android.ide.common.rendering.api.AdapterBinding;
22import com.android.ide.common.rendering.api.HardwareConfig;
23import com.android.ide.common.rendering.api.IAnimationListener;
24import com.android.ide.common.rendering.api.ILayoutPullParser;
25import com.android.ide.common.rendering.api.LayoutlibCallback;
26import com.android.ide.common.rendering.api.RenderResources;
27import com.android.ide.common.rendering.api.RenderSession;
28import com.android.ide.common.rendering.api.ResourceReference;
29import com.android.ide.common.rendering.api.ResourceValue;
30import com.android.ide.common.rendering.api.Result;
31import com.android.ide.common.rendering.api.Result.Status;
32import com.android.ide.common.rendering.api.SessionParams;
33import com.android.ide.common.rendering.api.SessionParams.RenderingMode;
34import com.android.ide.common.rendering.api.StyleResourceValue;
35import com.android.ide.common.rendering.api.ViewInfo;
36import com.android.ide.common.rendering.api.ViewType;
37import com.android.internal.util.XmlUtils;
38import com.android.internal.view.menu.ActionMenuItemView;
39import com.android.internal.view.menu.BridgeMenuItemImpl;
40import com.android.internal.view.menu.IconMenuItemView;
41import com.android.internal.view.menu.ListMenuItemView;
42import com.android.internal.view.menu.MenuItemImpl;
43import com.android.internal.view.menu.MenuView;
44import com.android.layoutlib.bridge.Bridge;
45import com.android.layoutlib.bridge.android.BridgeContext;
46import com.android.layoutlib.bridge.android.BridgeLayoutParamsMapAttributes;
47import com.android.layoutlib.bridge.android.BridgeXmlBlockParser;
48import com.android.layoutlib.bridge.android.SessionParamsFlags;
49import com.android.layoutlib.bridge.android.support.RecyclerViewUtil;
50import com.android.layoutlib.bridge.bars.AppCompatActionBar;
51import com.android.layoutlib.bridge.bars.BridgeActionBar;
52import com.android.layoutlib.bridge.bars.Config;
53import com.android.layoutlib.bridge.bars.FrameworkActionBar;
54import com.android.layoutlib.bridge.bars.NavigationBar;
55import com.android.layoutlib.bridge.bars.StatusBar;
56import com.android.layoutlib.bridge.bars.TitleBar;
57import com.android.layoutlib.bridge.impl.binding.FakeAdapter;
58import com.android.layoutlib.bridge.impl.binding.FakeExpandableAdapter;
59import com.android.resources.Density;
60import com.android.resources.ResourceType;
61import com.android.resources.ScreenOrientation;
62import com.android.util.Pair;
63
64import org.xmlpull.v1.XmlPullParserException;
65
66import android.animation.AnimationThread;
67import android.animation.Animator;
68import android.animation.AnimatorInflater;
69import android.animation.LayoutTransition;
70import android.animation.LayoutTransition.TransitionListener;
71import android.app.Fragment_Delegate;
72import android.graphics.Bitmap;
73import android.graphics.Bitmap_Delegate;
74import android.graphics.Canvas;
75import android.graphics.drawable.Drawable;
76import android.preference.Preference_Delegate;
77import android.util.DisplayMetrics;
78import android.util.TypedValue;
79import android.view.AttachInfo_Accessor;
80import android.view.BridgeInflater;
81import android.view.IWindowManager;
82import android.view.IWindowManagerImpl;
83import android.view.Surface;
84import android.view.View;
85import android.view.View.MeasureSpec;
86import android.view.ViewGroup;
87import android.view.ViewGroup.LayoutParams;
88import android.view.ViewGroup.MarginLayoutParams;
89import android.view.ViewParent;
90import android.view.WindowManagerGlobal_Delegate;
91import android.widget.AbsListView;
92import android.widget.AbsSpinner;
93import android.widget.ActionMenuView;
94import android.widget.AdapterView;
95import android.widget.ExpandableListView;
96import android.widget.FrameLayout;
97import android.widget.LinearLayout;
98import android.widget.ListView;
99import android.widget.QuickContactBadge;
100import android.widget.TabHost;
101import android.widget.TabHost.TabSpec;
102import android.widget.TabWidget;
103
104import java.awt.AlphaComposite;
105import java.awt.Color;
106import java.awt.Graphics2D;
107import java.awt.image.BufferedImage;
108import java.util.ArrayList;
109import java.util.List;
110import java.util.Map;
111
112import static com.android.ide.common.rendering.api.Result.Status.ERROR_ANIM_NOT_FOUND;
113import static com.android.ide.common.rendering.api.Result.Status.ERROR_INFLATION;
114import static com.android.ide.common.rendering.api.Result.Status.ERROR_NOT_INFLATED;
115import static com.android.ide.common.rendering.api.Result.Status.ERROR_UNKNOWN;
116import static com.android.ide.common.rendering.api.Result.Status.ERROR_VIEWGROUP_NO_CHILDREN;
117import static com.android.ide.common.rendering.api.Result.Status.SUCCESS;
118
119/**
120 * Class implementing the render session.
121 * <p/>
122 * A session is a stateful representation of a layout file. It is initialized with data coming
123 * through the {@link Bridge} API to inflate the layout. Further actions and rendering can then
124 * be done on the layout.
125 */
126public class RenderSessionImpl extends RenderAction<SessionParams> {
127
128    private static final int DEFAULT_TITLE_BAR_HEIGHT = 25;
129    private static final int DEFAULT_STATUS_BAR_HEIGHT = 25;
130
131    // scene state
132    private RenderSession mScene;
133    private BridgeXmlBlockParser mBlockParser;
134    private BridgeInflater mInflater;
135    private ResourceValue mWindowBackground;
136    private ViewGroup mViewRoot;
137    private FrameLayout mContentRoot;
138    private Canvas mCanvas;
139    private int mMeasuredScreenWidth = -1;
140    private int mMeasuredScreenHeight = -1;
141    private boolean mIsAlphaChannelImage;
142    private boolean mWindowIsFloating;
143    private Boolean mIsThemeAppCompat;
144
145    private int mStatusBarSize;
146    private int mNavigationBarSize;
147    private int mNavigationBarOrientation = LinearLayout.HORIZONTAL;
148    private int mTitleBarSize;
149    private int mActionBarSize;
150
151
152    // information being returned through the API
153    private BufferedImage mImage;
154    private List<ViewInfo> mViewInfoList;
155    private List<ViewInfo> mSystemViewInfoList;
156
157    private static final class PostInflateException extends Exception {
158        private static final long serialVersionUID = 1L;
159
160        public PostInflateException(String message) {
161            super(message);
162        }
163    }
164
165    /**
166     * Creates a layout scene with all the information coming from the layout bridge API.
167     * <p>
168     * This <b>must</b> be followed by a call to {@link RenderSessionImpl#init(long)},
169     * which act as a
170     * call to {@link RenderSessionImpl#acquire(long)}
171     *
172     * @see Bridge#createSession(SessionParams)
173     */
174    public RenderSessionImpl(SessionParams params) {
175        super(new SessionParams(params));
176    }
177
178    /**
179     * Initializes and acquires the scene, creating various Android objects such as context,
180     * inflater, and parser.
181     *
182     * @param timeout the time to wait if another rendering is happening.
183     *
184     * @return whether the scene was prepared
185     *
186     * @see #acquire(long)
187     * @see #release()
188     */
189    @Override
190    public Result init(long timeout) {
191        Result result = super.init(timeout);
192        if (!result.isSuccess()) {
193            return result;
194        }
195
196        SessionParams params = getParams();
197        BridgeContext context = getContext();
198
199
200        RenderResources resources = getParams().getResources();
201        DisplayMetrics metrics = getContext().getMetrics();
202
203        // use default of true in case it's not found to use alpha by default
204        mIsAlphaChannelImage  = getBooleanThemeValue(resources, "windowIsFloating", true, true);
205        // FIXME: Find out why both variables are taking the same value.
206        mWindowIsFloating = getBooleanThemeValue(resources, "windowIsFloating", true, true);
207
208        findBackground(resources);
209        findStatusBar(resources, metrics);
210        findActionBar(resources, metrics);
211        findNavigationBar(resources, metrics);
212
213        // FIXME: find those out, and possibly add them to the render params
214        boolean hasNavigationBar = true;
215        //noinspection ConstantConditions
216        IWindowManager iwm = new IWindowManagerImpl(getContext().getConfiguration(),
217                metrics, Surface.ROTATION_0,
218                hasNavigationBar);
219        WindowManagerGlobal_Delegate.setWindowManagerService(iwm);
220
221        // build the inflater and parser.
222        mInflater = new BridgeInflater(context, params.getLayoutlibCallback());
223        context.setBridgeInflater(mInflater);
224
225        mBlockParser = new BridgeXmlBlockParser(
226                params.getLayoutDescription(), context, false /* platformResourceFlag */);
227
228        return SUCCESS.createResult();
229    }
230
231    /**
232     * Inflates the layout.
233     * <p>
234     * {@link #acquire(long)} must have been called before this.
235     *
236     * @throws IllegalStateException if the current context is different than the one owned by
237     *      the scene, or if {@link #init(long)} was not called.
238     */
239    public Result inflate() {
240        checkLock();
241
242        try {
243
244            SessionParams params = getParams();
245            HardwareConfig hardwareConfig = params.getHardwareConfig();
246            BridgeContext context = getContext();
247            boolean isRtl = Bridge.isLocaleRtl(params.getLocale());
248            int layoutDirection = isRtl ? View.LAYOUT_DIRECTION_RTL : View.LAYOUT_DIRECTION_LTR;
249
250            // the view group that receives the window background.
251            ViewGroup backgroundView;
252
253            if (mWindowIsFloating || params.isForceNoDecor()) {
254                backgroundView = mViewRoot = mContentRoot = new FrameLayout(context);
255                mViewRoot.setLayoutDirection(layoutDirection);
256            } else {
257                int simulatedPlatformVersion = params.getSimulatedPlatformVersion();
258                if (hasSoftwareButtons() && mNavigationBarOrientation == LinearLayout.VERTICAL) {
259                    /*
260                     * This is a special case where the navigation bar is on the right.
261                       +-------------------------------------------------+---+
262                       | Status bar (always)                             |   |
263                       +-------------------------------------------------+   |
264                       | (Layout with background drawable)               |   |
265                       | +---------------------------------------------+ |   |
266                       | | Title/Action bar (optional)                 | |   |
267                       | +---------------------------------------------+ |   |
268                       | | Content, vertical extending                 | |   |
269                       | |                                             | |   |
270                       | +---------------------------------------------+ |   |
271                       +-------------------------------------------------+---+
272
273                       So we create a horizontal layout, with the nav bar on the right,
274                       and the left part is the normal layout below without the nav bar at
275                       the bottom
276                     */
277                    LinearLayout topLayout = new LinearLayout(context);
278                    topLayout.setLayoutDirection(layoutDirection);
279                    mViewRoot = topLayout;
280                    topLayout.setOrientation(LinearLayout.HORIZONTAL);
281
282                    if (Config.showOnScreenNavBar(simulatedPlatformVersion)) {
283                        try {
284                            NavigationBar navigationBar = createNavigationBar(context,
285                                    hardwareConfig.getDensity(), isRtl, params.isRtlSupported(),
286                                    simulatedPlatformVersion);
287                            topLayout.addView(navigationBar);
288                        } catch (XmlPullParserException ignored) {
289                        }
290                    }
291                }
292
293                /*
294                 * we're creating the following layout
295                 *
296                   +-------------------------------------------------+
297                   | Status bar (always)                             |
298                   +-------------------------------------------------+
299                   | (Layout with background drawable)               |
300                   | +---------------------------------------------+ |
301                   | | Title/Action bar (optional)                 | |
302                   | +---------------------------------------------+ |
303                   | | Content, vertical extending                 | |
304                   | |                                             | |
305                   | +---------------------------------------------+ |
306                   +-------------------------------------------------+
307                   | Navigation bar for soft buttons, maybe see above|
308                   +-------------------------------------------------+
309
310                 */
311
312                LinearLayout topLayout = new LinearLayout(context);
313                topLayout.setOrientation(LinearLayout.VERTICAL);
314                topLayout.setLayoutDirection(layoutDirection);
315                // if we don't already have a view root this is it
316                if (mViewRoot == null) {
317                    mViewRoot = topLayout;
318                } else {
319                    int topLayoutWidth =
320                            params.getHardwareConfig().getScreenWidth() - mNavigationBarSize;
321                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
322                            topLayoutWidth, LayoutParams.MATCH_PARENT);
323                    topLayout.setLayoutParams(layoutParams);
324
325                    // this is the case of soft buttons + vertical bar.
326                    // this top layout is the first layout in the horizontal layout. see above)
327                    if (isRtl && params.isRtlSupported()) {
328                        // If RTL is enabled, layoutlib will mirror the layouts. So, add the
329                        // topLayout to the right of Navigation Bar and layoutlib will draw it
330                        // to the left.
331                        mViewRoot.addView(topLayout);
332                    } else {
333                        // Add the top layout to the left of the Navigation Bar.
334                        mViewRoot.addView(topLayout, 0);
335                    }
336                }
337
338                if (mStatusBarSize > 0) {
339                    // system bar
340                    try {
341                        StatusBar statusBar = createStatusBar(context, hardwareConfig.getDensity(),
342                                layoutDirection, params.isRtlSupported(),
343                                simulatedPlatformVersion);
344                        topLayout.addView(statusBar);
345                    } catch (XmlPullParserException ignored) {
346
347                    }
348                }
349
350                LinearLayout backgroundLayout = new LinearLayout(context);
351                backgroundView = backgroundLayout;
352                backgroundLayout.setOrientation(LinearLayout.VERTICAL);
353                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
354                        LayoutParams.MATCH_PARENT, 0);
355                layoutParams.weight = 1;
356                backgroundLayout.setLayoutParams(layoutParams);
357                topLayout.addView(backgroundLayout);
358
359
360                // if the theme says no title/action bar, then the size will be 0
361                if (mActionBarSize > 0) {
362                    BridgeActionBar actionBar = createActionBar(context, params, backgroundLayout);
363                    actionBar.createMenuPopup();
364                    mContentRoot = actionBar.getContentRoot();
365                } else if (mTitleBarSize > 0) {
366                    try {
367                        TitleBar titleBar = createTitleBar(context,
368                                params.getAppLabel(),
369                                simulatedPlatformVersion);
370                        backgroundLayout.addView(titleBar);
371                    } catch (XmlPullParserException ignored) {
372
373                    }
374                }
375
376                // content frame
377                if (mContentRoot == null) {
378                    mContentRoot = new FrameLayout(context);
379                    layoutParams = new LinearLayout.LayoutParams(
380                            LayoutParams.MATCH_PARENT, 0);
381                    layoutParams.weight = 1;
382                    mContentRoot.setLayoutParams(layoutParams);
383                    backgroundLayout.addView(mContentRoot);
384                }
385
386                if (Config.showOnScreenNavBar(simulatedPlatformVersion) &&
387                        mNavigationBarOrientation == LinearLayout.HORIZONTAL &&
388                        mNavigationBarSize > 0) {
389                    // system bar
390                    try {
391                        NavigationBar navigationBar = createNavigationBar(context,
392                                hardwareConfig.getDensity(), isRtl, params.isRtlSupported(),
393                                simulatedPlatformVersion);
394                        topLayout.addView(navigationBar);
395                    } catch (XmlPullParserException ignored) {
396
397                    }
398                }
399            }
400
401
402            // Sets the project callback (custom view loader) to the fragment delegate so that
403            // it can instantiate the custom Fragment.
404            Fragment_Delegate.setLayoutlibCallback(params.getLayoutlibCallback());
405
406            String rootTag = params.getFlag(SessionParamsFlags.FLAG_KEY_ROOT_TAG);
407            boolean isPreference = "PreferenceScreen".equals(rootTag);
408            View view;
409            if (isPreference) {
410                view = Preference_Delegate.inflatePreference(getContext(), mBlockParser,
411                  mContentRoot);
412            } else {
413                view = mInflater.inflate(mBlockParser, mContentRoot);
414            }
415
416            // done with the parser, pop it.
417            context.popParser();
418
419            Fragment_Delegate.setLayoutlibCallback(null);
420
421            // set the AttachInfo on the root view.
422            AttachInfo_Accessor.setAttachInfo(mViewRoot);
423
424            // post-inflate process. For now this supports TabHost/TabWidget
425            postInflateProcess(view, params.getLayoutlibCallback(), isPreference ? view : null);
426
427            // get the background drawable
428            if (mWindowBackground != null) {
429                Drawable d = ResourceHelper.getDrawable(mWindowBackground, context);
430                backgroundView.setBackground(d);
431            }
432
433            return SUCCESS.createResult();
434        } catch (PostInflateException e) {
435            return ERROR_INFLATION.createResult(e.getMessage(), e);
436        } catch (Throwable e) {
437            // get the real cause of the exception.
438            Throwable t = e;
439            while (t.getCause() != null) {
440                t = t.getCause();
441            }
442
443            return ERROR_INFLATION.createResult(t.getMessage(), t);
444        }
445    }
446
447    /**
448     * Renders the scene.
449     * <p>
450     * {@link #acquire(long)} must have been called before this.
451     *
452     * @param freshRender whether the render is a new one and should erase the existing bitmap (in
453     *      the case where bitmaps are reused). This is typically needed when not playing
454     *      animations.)
455     *
456     * @throws IllegalStateException if the current context is different than the one owned by
457     *      the scene, or if {@link #acquire(long)} was not called.
458     *
459     * @see SessionParams#getRenderingMode()
460     * @see RenderSession#render(long)
461     */
462    public Result render(boolean freshRender) {
463        checkLock();
464
465        SessionParams params = getParams();
466
467        try {
468            if (mViewRoot == null) {
469                return ERROR_NOT_INFLATED.createResult();
470            }
471
472            RenderingMode renderingMode = params.getRenderingMode();
473            HardwareConfig hardwareConfig = params.getHardwareConfig();
474
475            // only do the screen measure when needed.
476            boolean newRenderSize = false;
477            if (mMeasuredScreenWidth == -1) {
478                newRenderSize = true;
479                mMeasuredScreenWidth = hardwareConfig.getScreenWidth();
480                mMeasuredScreenHeight = hardwareConfig.getScreenHeight();
481
482                if (renderingMode != RenderingMode.NORMAL) {
483                    int widthMeasureSpecMode = renderingMode.isHorizExpand() ?
484                            MeasureSpec.UNSPECIFIED // this lets us know the actual needed size
485                            : MeasureSpec.EXACTLY;
486                    int heightMeasureSpecMode = renderingMode.isVertExpand() ?
487                            MeasureSpec.UNSPECIFIED // this lets us know the actual needed size
488                            : MeasureSpec.EXACTLY;
489
490                    // We used to compare the measured size of the content to the screen size but
491                    // this does not work anymore due to the 2 following issues:
492                    // - If the content is in a decor (system bar, title/action bar), the root view
493                    //   will not resize even with the UNSPECIFIED because of the embedded layout.
494                    // - If there is no decor, but a dialog frame, then the dialog padding prevents
495                    //   comparing the size of the content to the screen frame (as it would not
496                    //   take into account the dialog padding).
497
498                    // The solution is to first get the content size in a normal rendering, inside
499                    // the decor or the dialog padding.
500                    // Then measure only the content with UNSPECIFIED to see the size difference
501                    // and apply this to the screen size.
502
503                    // first measure the full layout, with EXACTLY to get the size of the
504                    // content as it is inside the decor/dialog
505                    @SuppressWarnings("deprecation")
506                    Pair<Integer, Integer> exactMeasure = measureView(
507                            mViewRoot, mContentRoot.getChildAt(0),
508                            mMeasuredScreenWidth, MeasureSpec.EXACTLY,
509                            mMeasuredScreenHeight, MeasureSpec.EXACTLY);
510
511                    // now measure the content only using UNSPECIFIED (where applicable, based on
512                    // the rendering mode). This will give us the size the content needs.
513                    @SuppressWarnings("deprecation")
514                    Pair<Integer, Integer> result = measureView(
515                            mContentRoot, mContentRoot.getChildAt(0),
516                            mMeasuredScreenWidth, widthMeasureSpecMode,
517                            mMeasuredScreenHeight, heightMeasureSpecMode);
518
519                    // now look at the difference and add what is needed.
520                    if (renderingMode.isHorizExpand()) {
521                        int measuredWidth = exactMeasure.getFirst();
522                        int neededWidth = result.getFirst();
523                        if (neededWidth > measuredWidth) {
524                            mMeasuredScreenWidth += neededWidth - measuredWidth;
525                        }
526                    }
527
528                    if (renderingMode.isVertExpand()) {
529                        int measuredHeight = exactMeasure.getSecond();
530                        int neededHeight = result.getSecond();
531                        if (neededHeight > measuredHeight) {
532                            mMeasuredScreenHeight += neededHeight - measuredHeight;
533                        }
534                    }
535                }
536            }
537
538            // measure again with the size we need
539            // This must always be done before the call to layout
540            measureView(mViewRoot, null /*measuredView*/,
541                    mMeasuredScreenWidth, MeasureSpec.EXACTLY,
542                    mMeasuredScreenHeight, MeasureSpec.EXACTLY);
543
544            // now do the layout.
545            mViewRoot.layout(0, 0, mMeasuredScreenWidth, mMeasuredScreenHeight);
546
547            if (params.isLayoutOnly()) {
548                // delete the canvas and image to reset them on the next full rendering
549                mImage = null;
550                mCanvas = null;
551            } else {
552                AttachInfo_Accessor.dispatchOnPreDraw(mViewRoot);
553
554                // draw the views
555                // create the BufferedImage into which the layout will be rendered.
556                boolean newImage = false;
557
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.getLayoutlibCallback().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 layoutlibCallback 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, LayoutlibCallback layoutlibCallback, View skip)
1265            throws PostInflateException {
1266        if (view == skip) {
1267            return;
1268        }
1269        if (view instanceof TabHost) {
1270            setupTabHost((TabHost) view, layoutlibCallback);
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 = layoutlibCallback.getAdapterBinding(
1290                            listRef, 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, 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, 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(listRef, binding, layoutlibCallback));
1330                        } else {
1331                            ((AbsListView) view).setAdapter(
1332                                    new FakeAdapter(listRef, binding, layoutlibCallback));
1333                        }
1334                    } else if (view instanceof AbsSpinner) {
1335                        ((AbsSpinner) view).setAdapter(
1336                                new FakeAdapter(listRef, binding, layoutlibCallback));
1337                    }
1338                }
1339            }
1340        } else if (isInstanceOf(view, RecyclerViewUtil.CN_RECYCLER_VIEW)) {
1341            RecyclerViewUtil.setAdapter(view, getContext(), getParams());
1342        } else if (view instanceof ViewGroup) {
1343            ViewGroup group = (ViewGroup) view;
1344            final int count = group.getChildCount();
1345            for (int c = 0; c < count; c++) {
1346                View child = group.getChildAt(c);
1347                postInflateProcess(child, layoutlibCallback, skip);
1348            }
1349        }
1350    }
1351
1352    /**
1353     * Check if the object is an instance of a class named {@code className}. This doesn't work
1354     * for interfaces.
1355     */
1356    public static boolean isInstanceOf(Object object, String className) {
1357        Class superClass = object.getClass();
1358        while (superClass != null) {
1359            String name = superClass.getName();
1360            if (name.equals(className)) {
1361                return true;
1362            }
1363            superClass = superClass.getSuperclass();
1364        }
1365        return false;
1366    }
1367
1368    /**
1369     * Sets up a {@link TabHost} object.
1370     * @param tabHost the TabHost to setup.
1371     * @param layoutlibCallback The project callback object to access the project R class.
1372     * @throws PostInflateException
1373     */
1374    private void setupTabHost(TabHost tabHost, LayoutlibCallback layoutlibCallback)
1375            throws PostInflateException {
1376        // look for the TabWidget, and the FrameLayout. They have their own specific names
1377        View v = tabHost.findViewById(android.R.id.tabs);
1378
1379        if (v == null) {
1380            throw new PostInflateException(
1381                    "TabHost requires a TabWidget with id \"android:id/tabs\".\n");
1382        }
1383
1384        if (!(v instanceof TabWidget)) {
1385            throw new PostInflateException(String.format(
1386                    "TabHost requires a TabWidget with id \"android:id/tabs\".\n" +
1387                    "View found with id 'tabs' is '%s'", v.getClass().getCanonicalName()));
1388        }
1389
1390        v = tabHost.findViewById(android.R.id.tabcontent);
1391
1392        if (v == null) {
1393            // TODO: see if we can fake tabs even without the FrameLayout (same below when the frameLayout is empty)
1394            //noinspection SpellCheckingInspection
1395            throw new PostInflateException(
1396                    "TabHost requires a FrameLayout with id \"android:id/tabcontent\".");
1397        }
1398
1399        if (!(v instanceof FrameLayout)) {
1400            //noinspection SpellCheckingInspection
1401            throw new PostInflateException(String.format(
1402                    "TabHost requires a FrameLayout with id \"android:id/tabcontent\".\n" +
1403                    "View found with id 'tabcontent' is '%s'", v.getClass().getCanonicalName()));
1404        }
1405
1406        FrameLayout content = (FrameLayout)v;
1407
1408        // now process the content of the frameLayout and dynamically create tabs for it.
1409        final int count = content.getChildCount();
1410
1411        // this must be called before addTab() so that the TabHost searches its TabWidget
1412        // and FrameLayout.
1413        tabHost.setup();
1414
1415        if (count == 0) {
1416            // Create a dummy child to get a single tab
1417            TabSpec spec = tabHost.newTabSpec("tag")
1418                    .setIndicator("Tab Label", tabHost.getResources()
1419                            .getDrawable(android.R.drawable.ic_menu_info_details, null))
1420                    .setContent(new TabHost.TabContentFactory() {
1421                        @Override
1422                        public View createTabContent(String tag) {
1423                            return new LinearLayout(getContext());
1424                        }
1425                    });
1426            tabHost.addTab(spec);
1427        } else {
1428            // for each child of the frameLayout, add a new TabSpec
1429            for (int i = 0 ; i < count ; i++) {
1430                View child = content.getChildAt(i);
1431                String tabSpec = String.format("tab_spec%d", i+1);
1432                @SuppressWarnings("ConstantConditions")  // child cannot be null.
1433                int id = child.getId();
1434                @SuppressWarnings("deprecation")
1435                Pair<ResourceType, String> resource = layoutlibCallback.resolveResourceId(id);
1436                String name;
1437                if (resource != null) {
1438                    name = resource.getSecond();
1439                } else {
1440                    name = String.format("Tab %d", i+1); // default name if id is unresolved.
1441                }
1442                tabHost.addTab(tabHost.newTabSpec(tabSpec).setIndicator(name).setContent(id));
1443            }
1444        }
1445    }
1446
1447    /**
1448     * Visits a {@link View} and its children and generate a {@link ViewInfo} containing the
1449     * bounds of all the views.
1450     *
1451     * @param view the root View
1452     * @param offset an offset for the view bounds.
1453     * @param setExtendedInfo whether to set the extended view info in the {@link ViewInfo} object.
1454     * @param isContentFrame {@code true} if the {@code ViewInfo} to be created is part of the
1455     *                       content frame.
1456     *
1457     * @return {@code ViewInfo} containing the bounds of the view and it children otherwise.
1458     */
1459    private ViewInfo visit(View view, int offset, boolean setExtendedInfo,
1460            boolean isContentFrame) {
1461        ViewInfo result = createViewInfo(view, offset, setExtendedInfo, isContentFrame);
1462
1463        if (view instanceof ViewGroup) {
1464            ViewGroup group = ((ViewGroup) view);
1465            result.setChildren(visitAllChildren(group, isContentFrame ? 0 : offset,
1466                    setExtendedInfo, isContentFrame));
1467        }
1468        return result;
1469    }
1470
1471    /**
1472     * Visits all the children of a given ViewGroup and generates a list of {@link ViewInfo}
1473     * containing the bounds of all the views. It also initializes the {@link #mViewInfoList} with
1474     * the children of the {@code mContentRoot}.
1475     *
1476     * @param viewGroup the root View
1477     * @param offset an offset from the top for the content view frame.
1478     * @param setExtendedInfo whether to set the extended view info in the {@link ViewInfo} object.
1479     * @param isContentFrame {@code true} if the {@code ViewInfo} to be created is part of the
1480     *                       content frame. {@code false} if the {@code ViewInfo} to be created is
1481     *                       part of the system decor.
1482     */
1483    private List<ViewInfo> visitAllChildren(ViewGroup viewGroup, int offset,
1484            boolean setExtendedInfo, boolean isContentFrame) {
1485        if (viewGroup == null) {
1486            return null;
1487        }
1488
1489        if (!isContentFrame) {
1490            offset += viewGroup.getTop();
1491        }
1492
1493        int childCount = viewGroup.getChildCount();
1494        if (viewGroup == mContentRoot) {
1495            List<ViewInfo> childrenWithoutOffset = new ArrayList<ViewInfo>(childCount);
1496            List<ViewInfo> childrenWithOffset = new ArrayList<ViewInfo>(childCount);
1497            for (int i = 0; i < childCount; i++) {
1498                ViewInfo[] childViewInfo = visitContentRoot(viewGroup.getChildAt(i), offset,
1499                        setExtendedInfo);
1500                childrenWithoutOffset.add(childViewInfo[0]);
1501                childrenWithOffset.add(childViewInfo[1]);
1502            }
1503            mViewInfoList = childrenWithOffset;
1504            return childrenWithoutOffset;
1505        } else {
1506            List<ViewInfo> children = new ArrayList<ViewInfo>(childCount);
1507            for (int i = 0; i < childCount; i++) {
1508                children.add(visit(viewGroup.getChildAt(i), offset, setExtendedInfo,
1509                        isContentFrame));
1510            }
1511            return children;
1512        }
1513    }
1514
1515    /**
1516     * Visits the children of {@link #mContentRoot} and generates {@link ViewInfo} containing the
1517     * bounds of all the views. It returns two {@code ViewInfo} objects with the same children,
1518     * one with the {@code offset} and other without the {@code offset}. The offset is needed to
1519     * get the right bounds if the {@code ViewInfo} hierarchy is accessed from
1520     * {@code mViewInfoList}. When the hierarchy is accessed via {@code mSystemViewInfoList}, the
1521     * offset is not needed.
1522     *
1523     * @return an array of length two, with ViewInfo at index 0 is without offset and ViewInfo at
1524     *         index 1 is with the offset.
1525     */
1526    @NonNull
1527    private ViewInfo[] visitContentRoot(View view, int offset, boolean setExtendedInfo) {
1528        ViewInfo[] result = new ViewInfo[2];
1529        if (view == null) {
1530            return result;
1531        }
1532
1533        result[0] = createViewInfo(view, 0, setExtendedInfo, true);
1534        result[1] = createViewInfo(view, offset, setExtendedInfo, true);
1535        if (view instanceof ViewGroup) {
1536            List<ViewInfo> children = visitAllChildren((ViewGroup) view, 0, setExtendedInfo, true);
1537            result[0].setChildren(children);
1538            result[1].setChildren(children);
1539        }
1540        return result;
1541    }
1542
1543    /**
1544     * Creates a {@link ViewInfo} for the view. The {@code ViewInfo} corresponding to the children
1545     * of the {@code view} are not created. Consequently, the children of {@code ViewInfo} is not
1546     * set.
1547     * @param offset an offset for the view bounds. Used only if view is part of the content frame.
1548     */
1549    private ViewInfo createViewInfo(View view, int offset, boolean setExtendedInfo,
1550            boolean isContentFrame) {
1551        if (view == null) {
1552            return null;
1553        }
1554
1555        ViewInfo result;
1556        if (isContentFrame) {
1557            // The view is part of the layout added by the user. Hence,
1558            // the ViewCookie may be obtained only through the Context.
1559            result = new ViewInfo(view.getClass().getName(),
1560                    getContext().getViewKey(view),
1561                    view.getLeft(), view.getTop() + offset, view.getRight(),
1562                    view.getBottom() + offset, view, view.getLayoutParams());
1563        } else {
1564            // We are part of the system decor.
1565            SystemViewInfo r = new SystemViewInfo(view.getClass().getName(),
1566                    getViewKey(view),
1567                    view.getLeft(), view.getTop(), view.getRight(),
1568                    view.getBottom(), view, view.getLayoutParams());
1569            result = r;
1570            // We currently mark three kinds of views:
1571            // 1. Menus in the Action Bar
1572            // 2. Menus in the Overflow popup.
1573            // 3. The overflow popup button.
1574            if (view instanceof ListMenuItemView) {
1575                // Mark 2.
1576                // All menus in the popup are of type ListMenuItemView.
1577                r.setViewType(ViewType.ACTION_BAR_OVERFLOW_MENU);
1578            } else {
1579                // Mark 3.
1580                ViewGroup.LayoutParams lp = view.getLayoutParams();
1581                if (lp instanceof ActionMenuView.LayoutParams &&
1582                        ((ActionMenuView.LayoutParams) lp).isOverflowButton) {
1583                    r.setViewType(ViewType.ACTION_BAR_OVERFLOW);
1584                } else {
1585                    // Mark 1.
1586                    // A view is a menu in the Action Bar is it is not the overflow button and of
1587                    // its parent is of type ActionMenuView. We can also check if the view is
1588                    // instanceof ActionMenuItemView but that will fail for menus using
1589                    // actionProviderClass.
1590                    ViewParent parent = view.getParent();
1591                    while (parent != mViewRoot && parent instanceof ViewGroup) {
1592                        if (parent instanceof ActionMenuView) {
1593                            r.setViewType(ViewType.ACTION_BAR_MENU);
1594                            break;
1595                        }
1596                        parent = parent.getParent();
1597                    }
1598                }
1599            }
1600        }
1601
1602        if (setExtendedInfo) {
1603            MarginLayoutParams marginParams = null;
1604            LayoutParams params = view.getLayoutParams();
1605            if (params instanceof MarginLayoutParams) {
1606                marginParams = (MarginLayoutParams) params;
1607            }
1608            result.setExtendedInfo(view.getBaseline(),
1609                    marginParams != null ? marginParams.leftMargin : 0,
1610                    marginParams != null ? marginParams.topMargin : 0,
1611                    marginParams != null ? marginParams.rightMargin : 0,
1612                    marginParams != null ? marginParams.bottomMargin : 0);
1613        }
1614
1615        return result;
1616    }
1617
1618    /* (non-Javadoc)
1619     * The cookie for menu items are stored in menu item and not in the map from View stored in
1620     * BridgeContext.
1621     */
1622    @Nullable
1623    private Object getViewKey(View view) {
1624        BridgeContext context = getContext();
1625        if (!(view instanceof MenuView.ItemView)) {
1626            return context.getViewKey(view);
1627        }
1628        MenuItemImpl menuItem;
1629        if (view instanceof ActionMenuItemView) {
1630            menuItem = ((ActionMenuItemView) view).getItemData();
1631        } else if (view instanceof ListMenuItemView) {
1632            menuItem = ((ListMenuItemView) view).getItemData();
1633        } else if (view instanceof IconMenuItemView) {
1634            menuItem = ((IconMenuItemView) view).getItemData();
1635        } else {
1636            menuItem = null;
1637        }
1638        if (menuItem instanceof BridgeMenuItemImpl) {
1639            return ((BridgeMenuItemImpl) menuItem).getViewCookie();
1640        }
1641
1642        return null;
1643    }
1644
1645    private void invalidateRenderingSize() {
1646        mMeasuredScreenWidth = mMeasuredScreenHeight = -1;
1647    }
1648
1649    /**
1650     * Creates the status bar with wifi and battery icons.
1651     */
1652    private StatusBar createStatusBar(BridgeContext context, Density density, int direction,
1653            boolean isRtlSupported, int platformVersion) throws XmlPullParserException {
1654        StatusBar statusBar = new StatusBar(context, density,
1655                direction, isRtlSupported, platformVersion);
1656        statusBar.setLayoutParams(
1657                new LinearLayout.LayoutParams(
1658                        LayoutParams.MATCH_PARENT, mStatusBarSize));
1659        return statusBar;
1660    }
1661
1662    /**
1663     * Creates the navigation bar with back, home and recent buttons.
1664     *
1665     * @param isRtl true if the current locale is right-to-left
1666     * @param isRtlSupported true is the project manifest declares that the application
1667     *        is RTL aware.
1668     */
1669    private NavigationBar createNavigationBar(BridgeContext context, Density density,
1670            boolean isRtl, boolean isRtlSupported, int simulatedPlatformVersion)
1671            throws XmlPullParserException {
1672        NavigationBar navigationBar = new NavigationBar(context,
1673                density, mNavigationBarOrientation, isRtl,
1674                isRtlSupported, simulatedPlatformVersion);
1675        if (mNavigationBarOrientation == LinearLayout.VERTICAL) {
1676            navigationBar.setLayoutParams(new LinearLayout.LayoutParams(mNavigationBarSize,
1677                    LayoutParams.MATCH_PARENT));
1678        } else {
1679            navigationBar.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
1680                    mNavigationBarSize));
1681        }
1682        return navigationBar;
1683    }
1684
1685    private TitleBar createTitleBar(BridgeContext context, String title,
1686            int simulatedPlatformVersion)
1687            throws XmlPullParserException {
1688        TitleBar titleBar = new TitleBar(context, title, simulatedPlatformVersion);
1689        titleBar.setLayoutParams(
1690                new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, mTitleBarSize));
1691        return titleBar;
1692    }
1693
1694    /**
1695     * Creates the action bar. Also queries the project callback for missing information.
1696     */
1697    private BridgeActionBar createActionBar(BridgeContext context, SessionParams params,
1698            ViewGroup parentView) {
1699        if (mIsThemeAppCompat == Boolean.TRUE) {
1700            return new AppCompatActionBar(context, params, parentView);
1701        } else {
1702            return new FrameworkActionBar(context, params, parentView);
1703        }
1704    }
1705
1706    public BufferedImage getImage() {
1707        return mImage;
1708    }
1709
1710    public boolean isAlphaChannelImage() {
1711        return mIsAlphaChannelImage;
1712    }
1713
1714    public List<ViewInfo> getViewInfos() {
1715        return mViewInfoList;
1716    }
1717
1718    public List<ViewInfo> getSystemViewInfos() {
1719        return mSystemViewInfoList;
1720    }
1721
1722    public Map<String, String> getDefaultProperties(Object viewObject) {
1723        return getContext().getDefaultPropMap(viewObject);
1724    }
1725
1726    public void setScene(RenderSession session) {
1727        mScene = session;
1728    }
1729
1730    public RenderSession getSession() {
1731        return mScene;
1732    }
1733}
1734