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