《深入理解Android卷 I》- 第八章 - Surface- 读书笔记-part2

1 Surface有关流程梳理

  • ViewRootImpl的字段中有一个Surface类型的mSurface,直接调用了无参的构造函数创建。final Surface mSurface = new Surface();

  • ViewRootImplsetView()函数中,通过了IWindowSession跨进程与WindowManagerService中的Session交互,调用了IWindowSession.addToDisplay()函数。

    调用流程:

    frameworks/base/services/core/java/com/android/server/wm/Session.java

    @Override
        public int addToDisplay(IWindow window, int seq, WindowManager.LayoutParams attrs,
                int viewVisibility, int displayId, Rect outContentInsets, Rect outStableInsets,
                Rect outOutsets, InputChannel outInputChannel) {
              //WindowManagerService.addWindow
            return mService.addWindow(this, window, seq, attrs, viewVisibility, displayId,
                    outContentInsets, outStableInsets, outOutsets, outInputChannel);
        }
    

    frameworks/base/services/core/java/com/android/server/wm/WindowManagerService.java

    public int addWindow(Session session, IWindow client, int seq,
                WindowManager.LayoutParams attrs, int viewVisibility, int displayId,
                Rect outContentInsets, Rect outStableInsets, Rect outOutsets,
                InputChannel outInputChannel) {
           ...//
    
            synchronized(mWindowMap) {
               ...//
                boolean addToken = false;
                WindowToken token = mTokenMap.get(attrs.token);
                AppWindowToken atoken = null;
                if (token == null) {
                    ...//
                    token = new WindowToken(this, attrs.token, -1, false);
                    addToken = true;
                      ..//
                }
             ..//
               WindowState win = new WindowState(this, session, client, token, attachedWindow, appOp[0], seq, attrs, viewVisibility, displayContent);
              ..//
               //重要的函数
              win.attach();
              ...//
            }
            if (reportNewConfig) {
                sendNewConfiguration();
            }
            Binder.restoreCallingIdentity(origId);
    
            return res;
        }
    
    

    frameworks/base/services/core/java/com/android/server/wm/WindowState.java

    void attach() {
          //Session
        mSession.windowAddedLocked();
    }
    

    frameworks/base/services/core/java/com/android/server/wm/Session.java

    void windowAddedLocked() {
            if (mSurfaceSession == null) {
              //创建了一个SurfaceSeesion对象
                mSurfaceSession = new SurfaceSession();
               
                mService.mSessions.add(this);
                if (mLastReportedAnimatorScale != mService.getCurrentAnimatorScale()) {
                    mService.dispatchNewAnimatorScaleLocked(this);
                }
            }
            mNumWindow++;
        }
    
    • ViewRootImplperformTransval()的处理过程中会调用relayoutWindow(),最后是调用的IWindowSessionrelayout()函数。
    • ViewRootImpl调用SurfacelockCanvas(),得到一块画布。
    • ViewRootImpl调用SurfaceunlockCanvasAndPost(),释放画布。

2 surface的转化

通过梳理,在performTransval()中会与WindowManagerServic交互

frameworks/base/services/core/java/com/android/server/wm/Session.java

ublic int relayout(IWindow window, int seq, WindowManager.LayoutParams attrs,
            int requestedWidth, int requestedHeight, int viewFlags,
            int flags, Rect outFrame, Rect outOverscanInsets, Rect outContentInsets,
            Rect outVisibleInsets, Rect outStableInsets, Rect outsets, Rect outBackdropFrame,
            Configuration outConfig, Surface outSurface) {
      
        int res = mService.relayoutWindow(this, window, seq, attrs,
                requestedWidth, requestedHeight, viewFlags, flags,
                outFrame, outOverscanInsets, outContentInsets, outVisibleInsets,
                outStableInsets, outsets, outBackdropFrame, outConfig, outSurface);
     
        return res;
    }

这个函数本身没有任何实际操作,实际操作对象时WindowManagerService

frameworks/base/services/core/java/com/android/server/wm/WindowManagerService.java

 public int relayoutWindow(Session session, IWindow client, int seq,
            WindowManager.LayoutParams attrs, int requestedWidth,
            int requestedHeight, int viewVisibility, int flags,
            Rect outFrame, Rect outOverscanInsets, Rect outContentInsets,
            Rect outVisibleInsets, Rect outStableInsets, Rect outOutsets, Rect outBackdropFrame,
            Configuration outConfig, Surface outSurface) {
        ...//

        long origId = Binder.clearCallingIdentity();
        synchronized(mWindowMap) {
            WindowState win = windowForClientLocked(session, client, false);
           ...//

            if (viewVisibility == View.VISIBLE &&
                    (win.mAppToken == null || !win.mAppToken.clientHidden)) {
                result = relayoutVisibleWindow(outConfig, result, win, winAnimator, attrChanges,
                        oldVisibility);
                try {
                  //创建sufaceControl
                    result = createSurfaceControl(outSurface, result, win, winAnimator);
                } catch (Exception e) {
                   ...//
                }
               ..//
            }
        return result;
    }

7.0的源码这部分非常复杂,就光一个本地的surface对象的创建都找了天才找到,而且还是多层封装

frameworks/base/services/core/java/com/android/server/wm/WindowManagerService.java

private int createSurfaceControl(Surface outSurface, int result, WindowState win,
            WindowStateAnimator winAnimator) {
        if (!win.mHasSurface) {
            result |= RELAYOUT_RES_SURFACE_CHANGED;
        }
        //创建WindowSurfaceController对象
        WindowSurfaceController surfaceController = winAnimator.createSurfaceLocked();
        if (surfaceController != null) {
            //这里面才是原书中的copyFrom()
            surfaceController.getSurface(outSurface);          
        } else {
            // For some reason there isn't a surface.  Clear the
            // caller's object so they see the same state.
            outSurface.release();
        }
        return result;
    }
void getSurface(Surface outSurface) {
    outSurface.copyFrom(mSurfaceControl);
}

然而还是没有找到surface的创建,那么一定是在surfaceController对中了。

frameworks/base/services/core/java/com/android/server/wm/WindowStateAnimator.java

WindowSurfaceController createSurfaceLocked() {
        final WindowState w = mWin;
        if (w.hasSavedSurface()) {
            return mSurfaceController;
        }
        if (mSurfaceController != null) {
            return mSurfaceController;
        }
        w.setHasSurface(false);
        ..//
        // We may abort, so initialize to defaults.
        mLastSystemDecorRect.set(0, 0, 0, 0);
        mHasClipRect = false;
        mClipRect.set(0, 0, 0, 0);
        mLastClipRect.set(0, 0, 0, 0);
        try{
            ...//
            //创建WindowSurfaceController实例
            mSurfaceController = new WindowSurfaceController(mSession.mSurfaceSession,
                    attrs.getTitle().toString(),
                    width, height, format, flags, this);

            w.setHasSurface(true);

           
        } catch (OutOfResourcesException e) {
            mService.reclaimSomeSurfaceMemoryLocked(this, "create", true);
            mDrawState = NO_SURFACE;
            return null;
        } catch (Exception e) {
            mDrawState = NO_SURFACE;
            return null;
        }

        // Start a new transaction and apply position & offset.
        final int layerStack = w.getDisplayContent().getDisplay().getLayerStack();
        mSurfaceController.setPositionAndLayer(mTmpSize.left, mTmpSize.top, layerStack, mAnimLayer);
        mLastHidden = true;

        return mSurfaceController;
    }

真是深啊,继续看下去

frameworks/base/services/core/java/com/android/server/wm/WindowSurfaceController.java

public WindowSurfaceController(SurfaceSession s,
            String name, int w, int h, int format, int flags, WindowStateAnimator animator) {
        mAnimator = animator;

        mSurfaceW = w;
        mSurfaceH = h;

        title = name;

        // For opaque child windows placed under parent windows,
        // we use a special SurfaceControl which mirrors commands
        // to a black-out layer placed one Z-layer below the surface.
        // This prevents holes to whatever app/wallpaper is underneath.
        //如果是childwindow那么进这个分支,里面最终还是会穿件一个surfaceControl对象
        if (animator.mWin.isChildWindow() &&
                animator.mWin.mSubLayer < 0) {
            mSurfaceControl = new SurfaceControlWithBackground(s,
                    name, w, h, format, flags);
        } else if (DEBUG_SURFACE_TRACE) {
            mSurfaceControl = new SurfaceTrace(
                    s, name, w, h, format, flags);
        } else {
          //关注这个
            mSurfaceControl = new SurfaceControl(
                    s, name, w, h, format, flags);
        }
    }

frameworks/base/services/core/java/com/android/server/wm/SurfaceControl.java

  public SurfaceControl(SurfaceSession session,
            String name, int w, int h, int format, int flags)
                    throws OutOfResourcesException {
      ...//
        
        mName = name;
        //创建本地surface对象
        mNativeObject = nativeCreate(session, name, w, h, format, flags);
        if (mNativeObject == 0) {
            throw new OutOfResourcesException(
                    "Couldn't allocate SurfaceControl native object");
        }
        mCloseGuard.open("release");
    }

现在终于找到了。继续返回原书中。

WindowManagerService中创建的本地surface,然后将信息拷贝到outSurface中,也就是ViewRootImpl中的Surface

2.1 JNI层

原书中提及了Surface的构造,7.0代码中Surface的操作应该都移到了native中,无参构造中什么都没做,就是默认的构造函数。

SurfaceSession的构造,在前面的梳理过程中知道,在调用WindowManagerService.addWindow()中,创建了一个SurfaceSession对象。采用new的方式创建。

frameworks/base/core/java/android/view/SurfaceSession.java

public SurfaceSession() {
  //调用native函数
        mNativeClient = nativeCreate();
}

frameworks/base/core/jni/android_view_SurfaceSession.cpp

static jlong nativeCreate(JNIEnv* env, jclass clazz) {
    //创建了一个SurfaceComposerClient
    SurfaceComposerClient* client = new SurfaceComposerClient();
    client->incStrong((void*)nativeCreate);
    return reinterpret_cast<jlong>(client);
}

2.1.1 Surface JNI

WindowManagerService.relayoutWindow()过程中,创建SurfaceControl对象时,同时创建了一个nativeSurfaceControl对象

frameworks/base/core/jni/android_view_SurfaceContrl.cpp

static jlong nativeCreate(JNIEnv* env, jclass clazz, jobject sessionObj,
        jstring nameStr, jint w, jint h, jint format, jint flags) {
    ScopedUtfChars name(env, nameStr);
  //先创建了一个SurfaceComposerClient
    sp<SurfaceComposerClient> client(android_view_SurfaceSession_getClient(env, sessionObj));
  //通过SurfaceComposerClient创建native SurfaceControl
    sp<SurfaceControl> surface = client->createSurface(
            String8(name.c_str()), w, h, format, flags);
    if (surface == NULL) {
        jniThrowException(env, OutOfResourcesException, NULL);
        return 0;
    }
    surface->incStrong((void *)nativeCreate);
    return reinterpret_cast<jlong>(surface.get());
}

2.1.2 copyFrom

在创建好nativeSurfaceControl后面,调用了SurfaceController.getSurface(),SurfaceController里保存了一个JAVA层的SurfaceControl,JAVA层的SurfaceControl持有native层的SurfaceControl.

传入的的Surface调用copyFrom()方法,参数是SurfaceControl,我们知道,在client端也就是在viewRootImpl里面创建的Surface对象什么都没做,要使用draw就必须要关联nativeSurface才能在屏幕上有图像。

frameworks/core/java/android/view/Surface.java

 public void copyFrom(SurfaceControl other) {
        ..//
        long surfaceControlPtr = other.mNativeObject;
        ...///
         //创建了一个native surface
        long newNativeObject = nativeCreateFromSurfaceControl(surfaceControlPtr);

        synchronized (mLock) {
            if (mNativeObject != 0) {
                nativeRelease(mNativeObject);
            }
            //这个函数中做了Java层也native层关联
            setNativeObjectLocked(newNativeObject);
        }
    }

frameworks/core/java/android/view/Surface.java

private void setNativeObjectLocked(long ptr) {
        if (mNativeObject != ptr) {
            if (mNativeObject == 0 && ptr != 0) {
                mCloseGuard.open("release");
            } else if (mNativeObject != 0 && ptr == 0) {
                mCloseGuard.close();
            }
          //保存本地surface对象
            mNativeObject = ptr;
            mGenerationId += 1;
            if (mHwuiContext != null) {
                mHwuiContext.updateSurface();
            }
        }
    }

通过上面的操作就将本身没有什么作用的ViewRootImpl中的Surface填充了数据。就可以使用draw相关的调用了。

当然,最后还是通过binder通信交换数据,通过Parcelable接口的readFromParcelwriteFromParcel.

3 Surface和图画

通过与WindowManagerService交互,构造好了Surface,记下来就进入了draw的流程,在perfromTraversals()代码走到了performDraw(),最后去到了drawSoftware()

frameworks/base/core/java/android/view/ViewRootImpl.java

private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int xoff, int yoff,
            boolean scalingRequired, Rect dirty) {

        // Draw with software renderer.
        final Canvas canvas;
        try {
            final int left = dirty.left;
            final int top = dirty.top;
            final int right = dirty.right;
            final int bottom = dirty.bottom;
            //得到一个canvas
            canvas = mSurface.lockCanvas(dirty);

            // The dirty rectangle can be modified by Surface.lockCanvas()
            //noinspection ConstantConditions
            if (left != dirty.left || top != dirty.top || right != dirty.right
                    || bottom != dirty.bottom) {
                attachInfo.mIgnoreDirtyState = true;
            }

            // TODO: Do this in native
            canvas.setDensity(mDensity);
        } catch (Surface.OutOfResourcesException e) {
            handleOutOfResourcesException(e);
            return false;
        } catch (IllegalArgumentException e) {
            Log.e(mTag, "Could not lock surface", e);
            // Don't assume this is due to out of memory, it could be
            // something else, and if it is something else then we could
            // kill stuff (or ourself) for no reason.
            mLayoutRequested = true;    // ask wm for a new surface next time.
            return false;
        }

        try {

            // If this bitmap's format includes an alpha channel, we
            // need to clear it before drawing so that the child will
            // properly re-composite its drawing on a transparent
            // background. This automatically respects the clip/dirty region
            // or
            // If we are applying an offset, we need to clear the area
            // where the offset doesn't appear to avoid having garbage
            // left in the blank areas.
            if (!canvas.isOpaque() || yoff != 0 || xoff != 0) {
                canvas.drawColor(0, PorterDuff.Mode.CLEAR);
            }

            dirty.setEmpty();
            mIsAnimating = false;
            mView.mPrivateFlags |= View.PFLAG_DRAWN;

            try {
                canvas.translate(-xoff, -yoff);
                if (mTranslator != null) {
                    mTranslator.translateCanvas(canvas);
                }
                canvas.setScreenDensity(scalingRequired ? mNoncompatDensity : 0);
                attachInfo.mSetIgnoreDirtyState = false;
                //绘制方法调用
                mView.draw(canvas);

                drawAccessibilityFocusedDrawableIfNeeded(canvas);
            } finally {
                if (!attachInfo.mSetIgnoreDirtyState) {
                    // Only clear the flag if it was not set during the mView.draw() call
                    attachInfo.mIgnoreDirtyState = false;
                }
            }
        } finally {
            try {
                //释放canvas
                surface.unlockCanvasAndPost(canvas);
            } catch (IllegalArgumentException e) {
                mLayoutRequested = true;    // ask wm for a new surface next time.
                //noinspection ReturnInsideFinallyBlock
                return false;
            }
        }
        return true;
    }

这里就看出来了。软件方式绘制,就是通过surface lock一块区域,然后调用Viewdraw方法绘制,最后释放这个区域。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,117评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,963评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,897评论 0 240
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,805评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,208评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,535评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,797评论 2 311
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,493评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,215评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,477评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,988评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,325评论 2 252
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,971评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,055评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,807评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,544评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,455评论 2 266

推荐阅读更多精彩内容