Android UI结构源码研究

来源:互联网 发布:牧草大数据 编辑:程序博客网 时间:2024/05/21 14:58


android经验相关(android4.3)

        由于之前工作需要,对Android的UI framework做了些许研究,主要针对Android4.3的源码参考晚上别人的一些流程分析,加上自己打log得出的一些理解和经验。特意放上CSDN。



*************************************************************************************


一、当setVisibility(View.GONE);时,android所执行的measure、layout和draw相关操作。


********************************   measure & layout   *******************************
-->View.setFlag()
{
    if (changed & GONE) != 0
        requestLayout();
}


-->View.requestLayout()
{
    //表示本View已经接受了本次requestlayout的请求。
    mPrivateFlags |= PFLAG_FORCE_LAYOUT;


    if (mParent != null && !mParent.isLayoutRequested()) {
        mParent.requestLayout();
    }
}


public boolean isLayoutRequested() {
    return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
}




-->一层一层递归到最上面ViewRootImpl的requestLayout之后,scheduleTraversals


-->ViewRootImpl.requestLayout()
{
    ...


    //mLayoutRequested为true则表示接受当前requestLayout请求。
    mLayoutRequested = true;
    scheduleTraversals();
}




-->ViewRootImpl.performTraversals()
{
    // mStopped means whether is in the stopped state(no longer be active)
    boolean layoutRequested = mLayoutRequested && !mStopped;
    if (layoutRequested) {
        performMeasure();
    }


    final boolean didLayout = layoutRequested && !mStopped;
    if (didLayout) {
        performLayout();
    }
}




-->performMeasure & performLayout


-->到达parent(FrameLayout)时候,onMeasure(int, int)
{
    if (child.getVisibility() != GONE)
        跳过调用本View的measure
}


-->同理parent(FrameLayout),onLayout(boolean,int,int,int,int)
{


    if (child.getVisibility() != GONE) 
        跳过调用本View的layout
}


-->由于本View的meauser和layout没有被调用,也就是从本View开始的View都没有被重新measure和layout
另外,只有layout的时候会mPivateFlags &= ~PFLAG_FORCE_LAYOUT;(也就是完成了之前的layout请求)
此时,(mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;为true,也就是isLayoutRequestd()返回true。


-->此时如果本View的child View继续调用requestLayout的时候,会因为判断if(mParent.isLayoutRequested)返回true而跳过回溯到
ViewRootImpl的请求,因此就等于无法重新measure或者layout


********************************   draw   *******************************
/***


  drawSoftware ver.


***/


-->setFlag 
{
    if (changed & GONE) != 0 {
        ...


            mParent.invalidate(true);


        /*PFLAG_DRAWN表示该View已经完成draw操作,通常在invalidate判断,如果已经设置了该flag,则证明可以invalidate,并
         *把该flag去掉,表示需要重新draw操作。同时在draw操作执行过程中,会把该flag添加上。
         */
        mPrivateFlags |= PFLAG_DRAWN  
    }


    if ((changed & VISIBILITY_MASK) != 0) {
        ...


            mParent.invalidate(true);
    }
}


--->invalidate(boolean invalidateCache)
{
    //不是visibile和没有运行动画中的view要跳过invalidate
    if (skipInvalidate()) {
        return;
    }


    // PFLAG_DRAWN表示是否经过draw,PFLAG_HAS_BOUNDS在layout的时候setFrame设置上
    if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) {


        final AttachInfo ai = mAttachInfo;
        final ViewParent p = mParent;


        if (p != null && ai != null) {
            final Rect r = ai.mTmpInvalRect;
            r.set(0, 0, mRight - mLeft, mBottom - mTop);


            //调用parent的invalidateChid
            //同时把本View的区域作为dirtyRect为参数传入
            p.invalidateChild(this, r);
        }
    }
}


-->ViewGroup.invalidateChild(View, Rect)
{


    do {
        parent = parent.invalidateChildInParent(location, dirty);    
    }while(parent != null);


}


-->ViewGroup.invalidateChildInParent(final int[] location, final Rect dirty)
{
    //这里对dirtyRect进行操作


    //首先进行滑动的位移计算
    dirty.offset(location[CHILD_LEFT_INDEX] - mScrollX,
            location[CHILD_TOP_INDEX] - mScrollY);
    
    //如果没有设上FLAG_CLIP_CHILDREN(在initViewGroup默认设上),则把dirtyRect和自己的区域进行并集操作
    if ((mGroupFlags & FLAG_CLIP_CHILDREN) == 0) {
        dirty.union(0, 0, mRight - mLeft, mBottom - mTop);
    }


    final int left = mLeft;
    final int top = mTop;


    //否则就把dirtyRect和自己的区域进行交集操作,另外,如果发现没有交集,则把当前dirtyRect设为空。
    if ((mGroupFlags & FLAG_CLIP_CHILDREN) == FLAG_CLIP_CHILDREN) {
        if (!dirty.intersect(0, 0, mRight - left, mBottom - top)) {
            dirty.setEmpty();
        }
    }
}


然后就这样一直计算dirtyRect,回溯到ViewRootImpl.invalidateChildParent(),并把参数传递过去。


-->ViewRootImpl.invalidateChildInParent(int[] location, Rect dirty)
{


    //ViewRootImpl则把dirty和自己的dirtyRect进行并集
    final Rect localDirty = mDirty;
    localDirty.union(dirty.left, dirty.top, dirty.right, dirty.bottom);




    //如果dirtyRect和自己的View区域存在交集,或者动画过程中,
    //同时没有在performTraversals的执行过程中(!mWillDrawSoon),则会调度一次Traversals
    final boolean intersected = localDirty.intersect(0, 0,
            (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
    if (!intersected) {
        localDirty.setEmpty();
    }
    if (!mWillDrawSoon && (intersected || mIsAnimating)) {
        //调度一次Traversals,让下次执行performTraversals
        //注意:这里和requestLayout不同的是,performTraversals一般都要执行performDraw
        //但如果没有requestLayout过,则不会执行measure和layout(两者一般都会一起执行)
    
        scheduleTraversals();
    }


}


-->ViewRoomImpl.performTraversals()
-->ViewRootImpl.performDraw()
-->ViewRootImpl.draw()
-->ViewRootImpl.drawSoftware(... Rect dirty)
{
    ...


    //把dirtyRect的值传入lockCanvas,通过jni调用返回一个clipRect是dirty的canvas
    int left = dirty.left;
    int top = dirty.top;
    int right = dirty.right;
    int bottom = dirty.bottom;


    canvas = mSurface.lockCanvas(dirty);
   


    ...


    //传入mView的draw(),开始了第一个View的draw调用。
    mView.draw(canvas);
    


}


-->View.draw(canvas) (ViewRootImpl的直接孩子是继承FrameLayout的DecorView)
{
    /*
     * Draw traversal performs several drawing steps which must be executed
     * in the appropriate order:
     *
     *      1. Draw the background
     *      2. If necessary, save the canvas' layers to prepare for fading
     *      3. Draw view's content
     *      4. Draw children
     *      5. If necessary, draw the fading edges and restore layers
     *      6. Draw decorations (scrollbars for instance)
     */


    ...


    dispatchDraw(canvas);


    ...
    
}


-->ViewGroup.dispatchDraw(canvas)
{
    //从这里可见,只有VISIBILE或者在执行动画过程中的View才会被绘制
    if ((flags & FLAG_USE_CHILD_DRAWING_ORDER) == 0) {
        for (int i = 0; i < count; i++) {
            final View child = children[i];
            if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) {
                more |= drawChild(canvas, child, drawingTime);
            }
        }
    } else  {
        for (int i = 0; i < count; i++) {
            final View child = children[getChildDrawingOrder(count, i)];
            if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) {
                more |= drawChild(canvas, child, drawingTime);
            }
        }
    }
}


-->ViewGroup.drawChild(canvas, child, drawingTime)
{
    child.draw(canvas, this, drawingTime);
}


-->View.draw(canvas, parent, drawingTime)
{


    // Sets the flag as early as possible to allow draw() implementations
    // to call invalidate() successfully when doing animations
    mPrivateFlags |= PFLAG_DRAWN;


    if (!concatMatrix &&
            (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
                      ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&


            //这里通过把自己View的位置传入canvas来判断是否和clipRect有交集
            //如果没有,则可以直接返回不进行下面的draw调用。
            canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
            
            (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
        mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;


        return more;
    }




    //PFLAG_SKIP_DRAW表示不绘制,通常在ViewGrop.initViewGroup里
    //setFlags(WILL_NOT_DRAW, DRAW_MASK);给默认设上。


    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
        dispatchDraw(canvas);
    } else {
        draw(canvas);
    }


}


//就这样继续返回到最上层的child的绘制了。
//大致情况就是,某个子view进行invalidate调用的时候,通过和parent不断进行并集dirtyRect
//并最终传回给ViewRootImpl调度一次绘制操作,然后从最底层的view开始追溯回本View,同时会
//遍历每个子View,这个时候每个子View会把自己的区域和canvas的裁剪区域进行交集判断,如果
//没有交集就不会进行绘制。




*************************************************************************************


二 、mSurface.lockCanvas()


*************************************************************************************


-->Surface.lockCanvas()


-->android_view_Surface.nativeLockCanvas()
{
    sp<Surface> surface;
    surface->lock()
}


-->Surface.lock()   frameworks/native/libs/gui/Surface.cpp
{
    dequeueBuffer();
}


-->Surface.dequeueBuffer()
{
    mGraphicBufferProducer->dequeueBuffer();
}


-->BpGraphicBufferProducer.dequeueBuffer()   frameworks/native/libs/gui/IGraphicBufferProducder
{
    remote()->transact(DEQUEUE_BUFFER, ...)
}


-->BnGraphicBufferProducer::onTransact() frameworks/native/libs/gui/IGraphicBufferProducder
{
        case DEQUEUE_BUFFER: {
            int result = dequeueBuffer(&buf, &fence, w, h, format, usage);
            return NO_ERROR;
        } break;
}


-->BufferQueue.dequeueBuffer()  frameworks/native/libs/gui/BufferQueue //同一进程不同线程处理不同请求
{
}


*************************************************************************************


三 、应用程序App的Activity初始化过程(包括和SurfaceFlinger进行连接,申请创建Surface,申请绘图数据)(java+cpp)


*************************************************************************************


(步骤1,2,3均在调用onCreate之前)
1、ActivityThread通过Instrumentation创建出Activity之后,调用其attach方法,把之前创建的ContextImpl作为参数赋值(4.3版本待验证)
2、Activity.attach里,把ContextImpl通过attachBaseContext给保存起来(4.3待验证)
3、Activity.attach里调用PolicyManager.makeNewWindow(this);创建PhoneWindow保存到mWindow里,然后调用mWindow.setWindowManager(),
    这样在Window.setWindowManager()里,会通过mContext.getSystemService获取WindowManagerImpl,然后调用
    WindowManagerImpl.createLocalWindowManager来创建一个属于自己的WindowManagerImpl,保存到mWindowManager
(1、2、3步表示保存了ContextImpl,创建了PhoneWindow,WindowManagerImpl)




4、Activity.onCreate中,调用了setContentView(),然后调用getWindow().setContentView(),调用到PhoneWindow.setContentView(),然后PhoneWindow
   就会调用installDecor创建DecorView,令DecorView成为自定义View的父亲。




(步骤5在onResume之后)
5、ActivityThread.handleResumeActivity会调用WindowManager.addView(),也即WindowManagerImpl.addView(),其会调用mGlobal.addView,mGlobal是
    全局静态单例WindowManagerGlobal(主要负责封装不与任何Context关联的系统window manager的交互),WindowManagerGlobal.addView,负责创建
    ViewRootImpl,并且把其与decorView,WindowManager.LayoutParams对象关联,分别放到三个数组mRoots,mViews,mParams,最后会调用
    ViewRootImpl.setView(view, wparams, panelParentView); 然后会调用view.assignParent(this);把ViewRootImpl作为自己的ViewParent


创建Session,用于应用程序进程与WindowManagerService进行通信
6、在ViewRootImpl的构造函数里,调用WindowManagerGlobal.getWindowSession,在getWindowSession里(涉及Binder跨进程通信,底层利用C++的Binder机制)
    ,会通过IWindowManager.Stub.asInterface(ServiceManager.getService("window"));获取WindowManagerService的Binder代理对象,然后调用
    IWindowManager.openSession获取Session,也即调用到WindowManagerServcie.openSession()。(WindowManagerService extends IWindowManager.Stub)


7、WindowManagerService.openSession只是简单的new Session(this, xxx, xxx);然后返回,要注意,返回到应用程序进程端时,获得的对象就是
    IWindowSession.Proxy


创建WindowState,表示window状态,包含了一个IWindow的binder对象,可以与应用程序进程端的Activity组件通信。
8、注意之前在ViewRootImpl的构造函数中,会创建一个W对象,(W extentds IWindow.Stub),保存到mWindow。然后在RootViewImpl.setView()中,会调用
    mWindowSession.addToDisplay(mWindow, xxx);,同理,这是一个Binder的ipc调用,会到Session.addToDisplay(),而addToDisplay只是简单调用
    mService.addWindow(this, window, xxx);,mServices是之前构造Session赋值的WindowManagerService的引用。
9、WindowManager.addWindow,addWindow里有一个简单判断mWindowMap.containsKey(client.asBinder())的来以(client是RootViewImpl传过来的
    IWindow对象)来判断是否已经添加过此window,然后就会构造WindowState(this,session, client, xxx);,然后会调用WindowState.attach来增加
    一个连接SurfaceFlinger的SurfaceSession对象。然后addWindow还做了一大堆调整窗口z轴和位置还有focus的逻辑,略过。


WindowState对象与SurfaceFlinger连接
10、在WindowState对象的构造函数里,把IWindow对象(ViewRootImpl传递过来)保存到mClient中,并且调用c.asBinder().linkToDeath(deatchRecipinet,0)
    来监听该对象销毁的信号。另外,这里创建了一个WindowStateAnimator对象,负责创建并管理SurfaceControl。
11、WindowState.attach,只是简单调用了mSession.windowAddedLocked()。在windowAddedLocked中,mSurfaceSession = new SurfaceSession(),然后添加到
    WindowManagerServices中,mService.mSessions.add(this)。在SurfaceSession的构造函数里,通过nativeCreate的jni调用到c++层,会构造一个
    SurfaceComposerClient(),然后返回到SurfaceSession中。


Activity创建Surface
12、当ViewRootImpl.setView调用时会requestLayout,然后就会进行第一次的traversals,经过VSYNC同步之后调用performTraversals,然后会调用relayoutWindow
    在relayoutWindow中,会调用mWindowSession.relayout(mWindow, ... ,  mSurface),注意mSurface在构造ViewRootImpl中已经初始化new Surface,但内部
    的native对象是无效,这里会调用到Session.relayout,注意这里的Surface对象传递过程是通过在服务进程侧new Surface构造另外一个Surface,然后通过
    readFromParcel/WriteToParcel来实现对象的序列化。
13、Sessioin.relayout()只是简单的调用mService.relayoutWindow(this, window, xxx, outSurface);也就是WindowManagerService.relayoutWindow,其中,
    通过windowForClientLocked(session, client, flase)获取WindowState win,然后获取win.mWinAnimator对象,调用WindowStateAnimator.createSurfaceLocked
14、在WindowStateAnimator.createSurfaceLocked中,会构造mSurfaceControl = new SurfaceControl(mSession.mSurfaceSession, xxx);


15、在SurfaceControl的构造中,会接收SurfaceSession作为参数,内部调用nativeCreate(session,xxx);通过jni调用到c++层,然后会获取SurfaceSession
    之前获取的SurfaceComposerClient,然后调用SurfaceComposerClient::createSurface来想SurfaceFlinger申请一个Layer,同时返回SurfaceControl对象


16、继续在WindowStateAnimator.createSurfaceLocked中,运行了以下代码来设置SurfaceFlinger进程端对应的Layer的值。具体流程见bootanimation例子。
            SurfaceControl.openTransaction();
            mSurfaceControl.setPosition(mSurfaceX, mSurfaceY);
            mSurfaceControl.setLayerStack(mLayerStack);
            mSurfaceControl.setLayer(mAnimLayer);
            mSurfaceControl.setAlpha(0);
            SurfaceControl.closeTransaction();


17、经过以上步骤完成SurfaceControl的初始化后,返回到WindowStateAnimator.createSurfaceLocked中,会调用outSurface.copyFrom(surfaceControl),
    复制一个Surface,Surface.copyFrom会调用jni方法,nativeCreateFromSurfaceControl,而这个方法内部调用SurfaceControl::getSurface获取Surface,然后
    返回到Surface里。


    这样就完成了Surface的初始化。




总结:
1、Activity组件包含了以下内容
(1)PhoneWindow对象,负责构造并管理DecorView,以及窗口外观属性
(2)ViewRootImpl对象,负责创建Surface,与WindowManagerService对象通信,并且负责应用程序View层次的measure,layout,draw
    1)ViewRootImpl对象通过Session(IWindowSession)对象与WindowManagerService通信
    2)WindowManagerService对象通过W(IWindow)对象与ViewRootImpl对象通信
    3) 每个ViewRootImpl对象都有一个属于自己的W对象


2、WindowManagerService对于每个Activity组件(注意:WindowManagerService与SurfaceFlinger不同进程!)
(1)对于所有属于同一个应用程序进程都是同一个Session对象
(2)对于不同的ViewRootImpl都有不同的WindowState对象
(3)WindowState对象内部享有相同的Session,因此只有一个SurfaceSession对象,也就是确保只会连接到SurfaceFlinger一次
(4)由于WindowState对象不同,所以会另外创建SurfaceControl和Surface






////////////////////////////////
Java的Binder接口(与C++类似)


以ActivityManager例子(利用aidl可以依靠工具自动生成以下三个步骤,之后Service端只要extends IActivityManager.Stub实现)


1、接口定义
frameworks/base/core/java/android/app/IActivityManager.java
public interface IActivityManager extends android.os.IInterface {


//declare interface
    public int startActivity(IApplicationThread caller, String callingPackage,
            Intent intent, String resolvedType, IBinder resultTo, String resultWho,
            int requestCode, int flags, String profileFile,
            ParcelFileDescriptor profileFd, Bundle options) throws RemoteException;


....
}


2、本地对象定义(Service端)
public abstract class ActivityManagerNative extends Binder implements IActivityManager
{
    //实现asBinder、onTranscat、、asInterface
    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
        throws RemoteException {
            switch (code) {
                case START_ACTIVITY_TRANSACTION:
                    {
                        data.enforceInterface(IActivityManager.descriptor);
                        IBinder b = data.readStrongBinder();
                        IApplicationThread app = ApplicationThreadNative.asInterface(b);
                        String callingPackage = data.readString();
                        Intent intent = Intent.CREATOR.createFromParcel(data);
                        String resolvedType = data.readString();
                        IBinder resultTo = data.readStrongBinder();
                        String resultWho = data.readString();
                        int requestCode = data.readInt();
                        int startFlags = data.readInt();
                        String profileFile = data.readString();
                        ParcelFileDescriptor profileFd = data.readInt() != 0
                            ? data.readFileDescriptor() : null;
                        Bundle options = data.readInt() != 0
                            ? Bundle.CREATOR.createFromParcel(data) : null;
                        int result = startActivity(app, callingPackage, intent, resolvedType,
                                resultTo, resultWho, requestCode, startFlags,
                                profileFile, profileFd, options);
                        reply.writeNoException();
                        reply.writeInt(result);
                        return true;
                    }


                    ....
            }
        }


    static public IActivityManager asInterface(IBinder obj) {
        if (obj == null) {
            return null;
        }
        IActivityManager in =
            (IActivityManager)obj.queryLocalInterface(descriptor);
        if (in != null) {
            return in;
        }


        return new ActivityManagerProxy(obj);
    }


    public IBinder asBinder() {
        return this;
    }
}


3、代理对象定义(client端)
class ActivityManagerProxy implements IActivityManager
{
    //通过Parcel实现所有接口
   public int startActivity(IApplicationThread caller, String callingPackage, Intent intent,
            String resolvedType, IBinder resultTo, String resultWho, int requestCode,
            int startFlags, String profileFile,
            ParcelFileDescriptor profileFd, Bundle options) throws RemoteException {
        Parcel data = Parcel.obtain();
        Parcel reply = Parcel.obtain();
        data.writeInterfaceToken(IActivityManager.descriptor);
        data.writeStrongBinder(caller != null ? caller.asBinder() : null);
        data.writeString(callingPackage);
        intent.writeToParcel(data, 0);
        data.writeString(resolvedType);
        data.writeStrongBinder(resultTo);
        data.writeString(resultWho);
        data.writeInt(requestCode);
        data.writeInt(startFlags);
        data.writeString(profileFile);
        if (profileFd != null) {
            data.writeInt(1);
            profileFd.writeToParcel(data, Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
        } else {
            data.writeInt(0);
        }
        if (options != null) {
            data.writeInt(1);
            options.writeToParcel(data, 0);
        } else {
            data.writeInt(0);
        }
        mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0);
        reply.readException();
        int result = reply.readInt();
        reply.recycle();
        data.recycle();
        return result;
    }


   ......
}




*************************************************************************************


四、bootanimation与SurfaceFlinger进行通信(纯cpp层)


*************************************************************************************




/////////////////////////////////////////////////


(1)bootanimation与SurfaceFlinger进行连接


/////////////////////////////////////////////////


SurfaceFlinger运行在Android的系统进程内,一般的应用程序需要通过Binder进行跨进程通信。
其中主要SurfaceComposerClient具体封装了连接的过程。


class SurfaceComposerClient : public RefBase


因此,SurfaceComposerClient通过第一次构造时,通过


sp<SurfaceComposerClient>  session = new SurfaceComposerClient()


时会调用
-->SurfaceComposerClient::onFirstRef() //frameworks/native/libs/gui/SurfaceComposerClient.cpp
{
    //这里获取的sp<ISurfaceComposer>是BpSurfaceComposer的子类
    sp<ISurfaceComposer> sm(ComposerService::getComposerService());
    
    if (sm != 0) {
        
        sp<ISurfaceComposerClient> conn = sm->createConnection();
        if (conn != 0) {
            mClient = conn;
            mStatus = NO_ERROR;
        }
    }
    
}


然后就获取了sp<ISurfaceComposerClient>  mClient; 也就是通过Binder与SurfaceFlinger通信


展开分析
sp<ISurfaceComposer> sm(ComposerService::getComposerService());


-->/*static*/ sp<ISurfaceComposer> ComposerService::getComposerService() //frameworks/native/libs/gui/SurfaceComposerClient.cpp
{
    //ComposerService的ctor会调用connectLocked()
    ComposerService& instance = ComposerService::getInstance();
    Mutex::Autolock _l(instance.mLock);


    if (instance.mComposerService == NULL) {
        //尝试重新连接
        ComposerService::getInstance().connectLocked();
    }
    return instance.mComposerService;
}


-->void ComposerService::connectLocked() //frameworks/native/libs/gui/SurfaceComposerClient.cpp
{
    //尝试获取SurfaceFlinger服务,另外
    //sp<ISurfaceComposer> mComposerService;
    //SurfaceFlinger继承于BnSurfaceComposer,BnSurfaceComposer继承于BnInterface<ISurfaceComposer>


    /*
    *
    *注意:Bnxxx, Bpxxx是利用Binder机制派生出来的类,n表示native也就是服务端的,p表示proxy
    *一般Bnxxx类负责重载onTransact, Bp负责调用remote()->transact(....)进行跨进程通信。
    *
    */


    //这里获取到的mComposerService属于BpSurfaceComposer。
    const String16 name("SurfaceFlinger");
    while (getService(name, &mComposerService) != NO_ERROR) {
        usleep(250000);
    }
    assert(mComposerService != NULL);


    ...
}


getService展开:
-->template<typename INTERFACE>
status_t getService(const String16& name, sp<INTERFACE>* outService)  //frameworks/native/include/binder/IServiceManager.h
{
    //defaultServiceManager()大概为
    // if(gDefaultServiceManager != NULL ) return gDefaultServiceManager;
    // gDefaultServiceManager = new BpServiceManager(new BpBinder(0));  其中0表示远程接口句柄值为0
    //return gDefaultServiceManager;
    
    const sp<IServiceManager> sm = defaultServiceManager();
    if (sm != NULL) {
        //暂时忽略sm->gerService...
        *outService = interface_cast<INTERFACE>(sm->getService(name));
        
        if ((*outService) != NULL) return NO_ERROR;
    }
    return NAME_NOT_FOUND;
}


-->template<typename INTERFACE>
inline sp<INTERFACE> interface_cast(const sp<IBinder>& obj)
{
    //INTERFACE::asInterface由宏IMPLEMENT_META_INTERFACE实现
    //并最终调用new Bp##INTERFACE(obj)生成Bpxxx的类返回。
    return INTERFACE::asInterface(obj);
}




sp<ISurfaceComposerClient> conn = sm->createConnection();展开
-->virtual sp<ISurfaceComposerClient> BpSurfaceComposer::createConnection()  //frameworks/native/libs/gui/ISurfaceComposer.cpp
{
    uint32_t n;
    Parcel data, reply;
    data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
    
    //这里向BnSurfaceComposerClient发送消息。
    remote()->transact(BnSurfaceComposer::CREATE_CONNECTION, data, &reply);
   
    //同理,这里的interface_cast生成BpSurfaceComposerClient
    return interface_cast<ISurfaceComposerClient>(reply.readStrongBinder());
}


-->status_t BnSurfaceComposer::onTransact(
    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)  //frameworks/native/libs/gui/ISurfaceComposer.cpp
{
    switch(code) {
        case CREATE_CONNECTION: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            
            //这里会调用会SurfaceFlinger的createConnection
            //其中返回的参数为Client : public BnSurfaceComposerClient
            sp<IBinder> b = createConnection()->asBinder();
            
            reply->writeStrongBinder(b);
        } break;
      
    ...
    
    }


    ...
}


-->sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()    //frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp
{
    //这里创建了Client并返回
    //class Client : public BnSurfaceComposerClient


    sp<ISurfaceComposerClient> bclient;
    sp<Client> client(new Client(this));
    status_t err = client->initCheck();
    if (err == NO_ERROR) {
        bclient = client;
    }
    return bclient;
}




//简单来说,就是通过SurfaceComposerClient的onFirstRef,也就是第一次增加引用计数时,
//通过Binder机制和SurfaceFlinger建立连接,获取BpSurfaceComposerClient指针。




/////////////////////////////////////////////////


(2)bootanimation请求SurfaceFlinger创建Surface


/////////////////////////////////////////////////


    通常,一个应用程序可以拥有多个窗口(通常是Acitivity),每个窗口都要请求SurfaceFlinger创建对应的
Surface, 简单来说,就是通过SurfaceComposerClient请求SurfaceFlinger服务创建Surface,在此过程中,
在SurfaceFlinger服务进程侧创建了Layer对象,并且Layer对象内部创建了SurfaceFlingerConsumer以及
为其使用的SurfaceTextureLayer(继承于BufferQueue),并且也创建了对应的id对象Handle(同时会在析构时调用
mFlinger->onLayerDestoryed),并且Handle和SurfaceTexturelayer作为Binder的代理对象返回给应用程序
进程侧。同时,应用程序进程侧会以Handle和SurfaceTextureLayer两个对象来构造SurfaceControl对象,并且
同时请求SurfaceControl对象创建Surface对象。


具体调用过程:


-->sp<SurfaceControl> SurfaceComposerClient::createSurface(         //frameworks/native/libs/gui/SurfaceComposerClient.cpp
        const String8& name,
        uint32_t w,
        uint32_t h,
        PixelFormat format,
        uint32_t flags)
{
    sp<SurfaceControl> sur;
    sp<IBinder> handle;
    sp<IGraphicBufferProducer> gbp;


    ...
    //通过mClient(Client)代理Binder对象,请求SurfaceFlinger服务进程侧创建Surface
    mClient->createSurface(name, w, h, format, flags,
            &handle, &gbp);


    ...


    //获取了代理Binder对象handle、gbp(SurfaceTextureLayer),构造SurfaceControl对象并返回。
    sur = new SurfaceControl(this, handle, gbp);


    return sur;
}


//////////////////////////////////
mClient->createSurface()展开


//服务进程侧的Client
-->status_t Client::createSurface(                              //frameworks/native/services/surfaceflinger/Client.cpp
        const String8& name,
        uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
        sp<IBinder>* handle,
        sp<IGraphicBufferProducer>* gbp)
{


    //Client和SurfaceFlinger处于同一进程不同线程,
    //因此这里进行一个同步操作,效果等同于同一线程调用
    //flinger->createLayer()
    
    class MessageCreateLayer : public MessageBase {
        SurfaceFlinger* flinger;
        Client* client;
        sp<IBinder>* handle;
        sp<IGraphicBufferProducer>* gbp;
        status_t result;
        const String8& name;
        uint32_t w, h;
        PixelFormat format;
        uint32_t flags;
    public:
        MessageCreateLayer(SurfaceFlinger* flinger,
                const String8& name, Client* client,
                uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
                sp<IBinder>* handle,
                sp<IGraphicBufferProducer>* gbp)
            : flinger(flinger), client(client),
              handle(handle), gbp(gbp),
              name(name), w(w), h(h), format(format), flags(flags) {
        }
        status_t getResult() const { return result; }
        virtual bool handler() {
            result = flinger->createLayer(name, client, w, h, format, flags,
                    handle, gbp);
            return true;
        }
    };


    sp<MessageBase> msg = new MessageCreateLayer(mFlinger.get(),
            name, this, w, h, format, flags, handle, gbp);


    mFlinger->postMessageSync(msg);


    return static_cast<MessageCreateLayer*>( msg.get() )->getResult();
}




-->status_t SurfaceFlinger::createLayer(                    //frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp
        const String8& name,
        const sp<Client>& client,
        uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
        sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
{


    ...


    status_t result = NO_ERROR;


    sp<Layer> layer;


    switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
        case ISurfaceComposerClient::eFXSurfaceNormal:
            result = createNormalLayer(client,
                    name, w, h, flags, format,
                    handle, gbp, &layer);
            break;
    ...
    
    }


    if (result == NO_ERROR) {
        //创建成功后,添加到把对象添加到Client端,并请求一次调度。
        addClientLayer(client, *handle, *gbp, layer);
        setTransactionFlags(eTransactionNeeded);
    }


    return result;
}




-->status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
        const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
        sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
{
    ...


    //创建Layer对象,Layer对象内部创建SurfaceTextureLayer和SurfaceFlingerConsumer
    *outLayer = new Layer(this, client, name, w, h, flags);
    status_t err = (*outLayer)->setBuffers(w, h, format, flags);
    if (err == NO_ERROR) {


        //获取id对象Handle和BufferQueue对象(也就是Layer内部创建的SurfaceTextureLayer对象)
        *handle = (*outLayer)->getHandle();
        *gbp = (*outLayer)->getBufferQueue();
    }


    ...


    return err;
}


-->void Layer::onFirstRef()                 //frameworks/native/services/surfaceflinger/Layer.cpp
{
    //Layer对象第一次引用时进行初始化
    //创建SurfaceTextureLayer和SurfaceFlingerConsumer,并进行必要的初始化。
    
    // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
    sp<BufferQueue> bq = new SurfaceTextureLayer(mFlinger);


    mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(mTextureName, true,
            GL_TEXTURE_EXTERNAL_OES, false, bq);


    mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
    mSurfaceFlingerConsumer->setFrameAvailableListener(this);
    mSurfaceFlingerConsumer->setSynchronousMode(true);
    mSurfaceFlingerConsumer->setName(mName);


    ...


    mSurfaceFlingerConsumer->setDefaultMaxBufferCount(3);


    ...
}


-->status_t Layer::setBuffers( uint32_t w, uint32_t h,             //frameworks/native/services/surfaceflinger/Layer.cpp
                            PixelFormat format, uint32_t flags)
{


    //对mSurfaceFlingerConsumer进行初始化


    // this surfaces pixel format
    PixelFormatInfo info;
    status_t err = getPixelFormatInfo(format, &info);


    uint32_t const maxSurfaceDims = min(
            mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());


    mFormat = format;


    mSecure = (flags & ISurfaceComposerClient::eSecure) ? true : false;
    mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
    mOpaqueLayer = (flags & ISurfaceComposerClient::eOpaque);
    mCurrentOpacity = getOpacityForFormat(format);


    mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
    mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
    mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));


    return NO_ERROR;
}


-->sp<IBinder> Layer::getHandle() {


    //返回一个Handle对象(Binder代理)作为id用途,
    //LayerCleaner确保在析构的时候调用flinger->onLayerDestroyed(mLayer)


    class Handle : public BBinder, public LayerCleaner {
        wp<const Layer> mOwner;
    public:
        Handle(const sp<SurfaceFlinger>& flinger, const sp<Layer>& layer)
            : LayerCleaner(flinger, layer), mOwner(layer) {
        }
    };


    return new Handle(mFlinger, this);
}


-->sp<BufferQueue> Layer::getBufferQueue() const {
    //这里返回的是Layer.onFirstRef里构造的SurfaceTextureLayer对象.


    return mSurfaceFlingerConsumer->getBufferQueue();
}


-->void SurfaceFlinger::addClientLayer(const sp<Client>& client,
        const sp<IBinder>& handle,
        const sp<IGraphicBufferProducer>& gbc,
        const sp<Layer>& lbc)
{
    // attach this layer to the client
    client->attachLayer(handle, lbc);


    // add this layer to the current state list
    Mutex::Autolock _l(mStateLock);


    //这里添加到一个Vector对象里,方便以后绘制按照Z轴顺序
    mCurrentState.layersSortedByZ.add(lbc);
    mGraphicBufferProducerList.add(gbc->asBinder());
}


-->void Client::attachLayer(const sp<IBinder>& handle, const sp<Layer>& layer)
{
    Mutex::Autolock _l(mLock);
    //添加到一个Key-value的vector对象内
    mLayers.add(handle, layer);
}
//////////////////////////////////


//////////////////////////////////
new SurfaceControl
应用程序进程侧的构造


-->SurfaceControl::SurfaceControl(                  //frameworks/native/libs/gui/SurfaceControl.cpp
        const sp<SurfaceComposerClient>& client, 
        const sp<IBinder>& handle,
        const sp<IGraphicBufferProducer>& gbp)
    : mClient(client), mHandle(handle), mGraphicBufferProducer(gbp)
{
}


-->sp<Surface> SurfaceControl::getSurface() const    //frameworks/native/libs/gui/SurfaceControl.cpp
{
    Mutex::Autolock _l(mLock);
    if (mSurfaceData == 0) {
        mSurfaceData = new Surface(mGraphicBufferProducer);
    }
    return mSurfaceData;
}


-->Surface::Surface(                                //frameworks/native/libs/gui/Surface.cpp
        const sp<IGraphicBufferProducer>& bufferProducer)
    : mGraphicBufferProducer(bufferProducer)
{


    //初始化OpenGl回调的函数指针
    ANativeWindow::setSwapInterval  = hook_setSwapInterval;
    ANativeWindow::dequeueBuffer    = hook_dequeueBuffer;
    ANativeWindow::cancelBuffer     = hook_cancelBuffer;
    ANativeWindow::queueBuffer      = hook_queueBuffer;
    ANativeWindow::query            = hook_query;
    ANativeWindow::perform          = hook_perform;


    ANativeWindow::dequeueBuffer_DEPRECATED = hook_dequeueBuffer_DEPRECATED;
    ANativeWindow::cancelBuffer_DEPRECATED  = hook_cancelBuffer_DEPRECATED;
    ANativeWindow::lockBuffer_DEPRECATED    = hook_lockBuffer_DEPRECATED;
    ANativeWindow::queueBuffer_DEPRECATED   = hook_queueBuffer_DEPRECATED;


    //初始化OpenGl的值
    const_cast<int&>(ANativeWindow::minSwapInterval) = 0;
    const_cast<int&>(ANativeWindow::maxSwapInterval) = 1;


    //其他成员变量初始化
    ...
}




/////////////////////////////////////////////////


BootAnimation创建Surface过程总结(纯cpp):


/////////////////////////////////////////////////


应用程序进程对象:
1、SurfaceComposerClient
创建:
    直接new SurfaceComposerClient
作用:
(1)负责与SurfaceFlinger连接,
    通过getService获取SurfaceFlinger的ISurfaceComposer的binder指针,然后createConnection(),获得ISurfaceComposerClient(mClient)
(2)负责创建SurfaceControl
    调用mClient->createSurface(),获取handle(IBinder)、gbp(IGraphicBufferProducer),然后new SurfaceControl(this,handle,gbp)
(3)提供静态方法,可以在对于整个应用程序进程提供同一的提交Surface变更操作。
    如openGlobalTransaction/closeGlobalTransaction,用来提交Surface的setAlpha/setLayer/setMatrix等操作到服务进程端。
    内部实现是依靠一个静态类Composer,通过获取服务SurfaceFlinger的Binder指针,调用ISurfaceComposer::setTransactionState实现,参数里包含
    Client来区别每个应用程序进程。




2、SurfaceControl
创建:
    由SurfaceComposerClient.createSurface中直接new SurfaceControl
作用:
(1)配合SurfaceComposerClient,利用ISurfaceComposerClient设置窗口的属性
    setLayer,setAlpha,set**等
    例:
    SurfaceComposerClient::openGlobalTransaction();
    control->setLayer(0x40000000);
    SurfaceComposerClient::closeGlobalTransaction();
    ---最终通过ISurfaceComposer::setTransactionState,调用到SurfaceFlinger服务端,找到对应的Layer,然后调用Layer.setLayer
(2)负责创建Surface
    mSurfaceData = new Surface(mGraphicBufferProducer); (mGraphicBufferProducer即SurfaceTextureLayer : public BufferQueue)


3、Surface
创建:
    由SurfaceControl.getSurface中直接new Surface
作用:
(1)真正的绘制类,通过dequeueBuffer/queueBuffer来获取/提交图形数据(pixel)


ViewRootImpl的drawSoftware就是通过Surafce::lock以及Surface::unlockAndPost来获取/提交图形数据


//////////////////////////////////////
服务(SurfaceFlinger)进程对象:
1、Client(ISurfaceComposerClient)
创建:
    由SurfaceFlinger.createConnection直接new Client(this)
作用:
(1)返回应用程序侧对象之一,主要负责Surface的构造和管理
    应用程序端通过Binder调用到SurfaceFlinger的方法,createSurface等


2、Layer
创建:
    由SurfaceFlinger.createNormalLayer直接new Layer(this, client, name, w, h, flags);
作用:
(1)创建SurfaceTextureLayer(BufferQueue),以及SurfaceFlingerConsumer
    在Layer.onFirstRef()中,
    sp<BufferQueue>bq = new SurfaceTextureLayer(mFlinger); 
    mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(mTextureName, true, ..., .., bq);
    mSurfaceFlingerConsumer->setFrameAvailableListener(this);
    这样,consumer里包含一个bufferqueue,并且Layer监听着可用图像数据的消息。


(2)负责通知SurfaceFlinger更新屏幕
    当应用程序通过Skia完成Rasterazation(光栅化)后,则会调用Surface::queueBuffer把图像数据提交。这时候会调用到BufferQueue::queueBuffer,
    然后会调用onFrameAvailabel通知Layer,
    Layer就会调用mFlinger->signalLayerUpdate();SurfaceFlinger等待VSYNC同步好后,就会把图像数据composite到屏幕上


3、SurfaceTextureLayer(BufferQueue)
创建:
    由Layer::onFirstRef()中直接new SurfaceTextLayer(mFlinger);
作用:
(1)负责管理GraphicBuffer队列,GraphicBuffer就是图像数据的封装类
    BufferSlot mSlots[NUM_BUFFER_SLOTS]; //Surface内部有保存一份类似的bufferslot,纪录已经分配的buffer
    根据数组里每个buffer的状态管理和分配出对应的buffer
(2)分配Buffer
    分配Buffer是通过gralloc模块进行分配,具体通过GraphicsBufferAlloc来new GraphicBuffer


4、SurfaceFlingerConsumer(GLConsumer)
创建:
    由Layer::onFirstRef()中直接new SurfaceFlingerConsumer
作用:
 * GLConsumer consumes buffers of graphics data from a BufferQueue,
 * and makes them available to OpenGL as a texture.
 *
 * A typical usage pattern is to set up the GLConsumer with the
 * desired options, and call updateTexImage() when a new frame is desired.
 * If a new frame is available, the texture will be updated.  If not,
 * the previous contents are retained.
 *
 * By default, the texture is attached to the GL_TEXTURE_EXTERNAL_OES
 * texture target, in the EGL context of the first thread that calls
 * updateTexImage().
 *
 * This class was previously called SurfaceTexture.


    当SurfaceFlinger::handlePageFlip调用时(VSYNC后通知SurfaceFlinger更新),Layer::latchBuffer会调用
    SurfaceFlingerConsumer::updateTexImage利用GL合成图层。而updateTexImage会调用内部的BufferQueue::acquireBuffer获得对应的
    等待合成的GraphicBuffer进行合成。


5、GraphicBuffer
创建:
    由GraphicBufferAlloc来直接new GraphicBuffer
作用:
(1)可以跨进程返回给应用进程侧
    这是通过public Flattenable来继承Flattenable,然后重载flatten和unflatten来在Binder的onTranscation和transcat方法调用,
    flatten和unflatten主要通过GraphicMapper把内存映射到应用进程侧。
(2)可以申请对应的宽度w,高度h和像素格式format所需要的图像数据内存
    这是通过GraphicBufferAllocator分配,其中GraphicBufferAllocator是利用gralloc模块进行分配


//mGraphicBufferAlloc通过ComposerService::getComposerService()获得SurfaceFlinger的binder接口
//然后调用createGBraphicBufferAlloc在服务进程侧创建了GraphicBufferAlloc对象,
//然后,这里同样通过binder机制,在进程服务侧创建了GrahpicBuffer对象,并且此时利用了gralloc模块分配了匿名内存
//然后binder对象返回的时候,BpGraphicBufferAlloc(应用进程侧)创建了size为0的GraphicBuffer对象,然后通过Pracel::read方法
//把进程服务侧创建的内存复制到应用进程侧的这个对象上
mGraphicBufferAlloc->createGraphicBuffer();






另外,关于VSYNC(Vertical Sync)垂直同步:
Android 4.1里对于CPU、GPU处理完图层后合成到Display的过程中的优化,严格按照Display的刷新频率进行同步的优化。
主要在SurfaceFlinger里成员HWComposer *mHwc;封装了部分逻辑。SurfaceFlinger通过private继承了HWComposer::EventHandler来接收来自HWComposer的
回调onVSyncReceived,此时SurfaceFlinger内部通过EventThread::onVSyncReceived与自身的Thread Loop进行同步(not very clear..)。


*************************************************************************************************************************************








0 0