1 Surface有关流程梳理
在
ViewRootImpl
的字段中有一个Surface
类型的mSurface
,直接调用了无参的构造函数创建。final Surface mSurface = new Surface();
-
在
ViewRootImpl
的setView()
函数中,通过了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++; }
-
ViewRootImpl
在performTransval()
的处理过程中会调用relayoutWindow()
,最后是调用的IWindowSession
的relayout()
函数。 -
ViewRootImpl
调用Surface
的lockCanvas()
,得到一块画布。 -
ViewRootImpl
调用Surface
的unlockCanvasAndPost()
,释放画布。
-
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
对象时,同时创建了一个native
的SurfaceControl
对象
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
在创建好native
的SurfaceControl
后面,调用了SurfaceController.getSurface()
,SurfaceController
里保存了一个JAVA
层的SurfaceControl
,JAVA
层的SurfaceControl
持有native
层的SurfaceControl
.
传入的的Surface
调用copyFrom()
方法,参数是SurfaceControl
,我们知道,在client
端也就是在viewRootImpl
里面创建的Surface
对象什么都没做,要使用draw
就必须要关联native
的Surface
才能在屏幕上有图像。
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
接口的readFromParcel
和writeFromParcel
.
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
一块区域,然后调用View
的draw
方法绘制,最后释放这个区域。