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