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