欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  科技

Android 源码 图形系统之 relayoutWindow

程序员文章站 2022-03-11 19:02:17
在 《Android 源码 图形系统之请求布局》 一节,分析到 ViewRootImpl 类 performTraversals() 方法内调用 relayoutWindow(…) 方法重新布局窗口时没有继续进一步深入,现在从 relayoutWindow(…) 开始来梳理后续流程。ViewRootImpl 类 relayoutWindow(…) 方法内部最终调用了 Session 类 relayout(…) 方法。mWindowSession 指向相应的代理对象 IWindowSession.Stub....

在 《Android 源码 图形系统之请求布局》 一节,分析到 ViewRootImpl 类 performTraversals() 方法内调用 relayoutWindow(…) 方法重新布局窗口时没有继续进一步深入,现在从 relayoutWindow(…) 开始来梳理后续流程。

ViewRootImpl 类 relayoutWindow(…) 方法内部最终调用了 Session 类 relayout(…) 方法。mWindowSession 指向相应的代理对象 IWindowSession.Stub.Proxy。

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

public final class ViewRootImpl implements ViewParent,
        View.AttachInfo.Callbacks, HardwareRenderer.HardwareDrawCallbacks {
    ......
    // 可以被任何线程访问,必须用锁保护。
    // Surface 永远不能被重新分配或清除(使用Surface.clear())。
    final Surface mSurface = new Surface();
    ......
    private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
            boolean insetsPending) throws RemoteException {

        float appScale = mAttachInfo.mApplicationScale;
        ......
        mPendingConfiguration.seq = 0;
        //Log.d(TAG, ">>>>>> CALLING relayout");
        ......
        int relayoutResult = mWindowSession.relayout(
                mWindow, mSeq, params,
                (int) (mView.getMeasuredWidth() * appScale + 0.5f),
                (int) (mView.getMeasuredHeight() * appScale + 0.5f),
                viewVisibility, insetsPending ? WindowManagerGlobal.RELAYOUT_INSETS_PENDING : 0,
                mWinFrame, mPendingOverscanInsets, mPendingContentInsets, mPendingVisibleInsets,
                mPendingStableInsets, mPendingOutsets, mPendingConfiguration, mSurface);
        //Log.d(TAG, "<<<<<< BACK FROM relayout");
        if (restore) {
            params.restore();
        }

        ......
        return relayoutResult;
    }   
    ......
}

Session 类 relayout(…) 方法实际工作是通过调用 WindowManagerService 类 relayoutWindow(…) 实现的。

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

final class Session extends IWindowSession.Stub
        implements IBinder.DeathRecipient {
    ......
    public 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, Configuration
                    outConfig,
            Surface outSurface) {
        if (false) Slog.d(WindowManagerService.TAG, ">>>>>> ENTERED relayout from "
                + Binder.getCallingPid());
        int res = mService.relayoutWindow(this, window, seq, attrs,
                requestedWidth, requestedHeight, viewFlags, flags,
                outFrame, outOverscanInsets, outContentInsets, outVisibleInsets,
                outStableInsets, outsets, outConfig, outSurface);
        if (false) Slog.d(WindowManagerService.TAG, "<<<<<< EXITING relayout to "
                + Binder.getCallingPid());
        return res;
    }
    ......
}

现在注意一下 outSurface 实参,这个参数是在 ViewRootImpl 类中初始化的,然后跨进程传递。

Surface 类代表由屏幕合成器管理的原始缓冲区的句柄。

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

public class Surface implements Parcelable {
    ......
    // 创建一个空 Surface,稍后将由 readFromParcel() 填充。
    public Surface() {
    }    
    ......
}
  1. 调用 windowForClientLocked(…) 方法查找 WindowState 对象
  2. 从 WindowState 对象成员变量 mWinAnimator 中获取 WindowStateAnimator 对象
  3. 调用 WindowStateAnimator 类 createSurfaceLocked() 获取 SurfaceControl 对象
  4. 从 SurfaceControl 对象中初始化 outSurface

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

public class WindowManagerService extends IWindowManager.Stub
        implements Watchdog.Monitor, WindowManagerPolicy.WindowManagerFuncs {
    ......
    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, Configuration outConfig,
            Surface outSurface) {
        boolean toBeDisplayed = false;
        boolean inTouchMode;
        boolean configChanged;
        boolean surfaceChanged = false;
        boolean animating;
        boolean hasStatusBarPermission =
                mContext.checkCallingOrSelfPermission(android.Manifest.permission.STATUS_BAR)
                        == PackageManager.PERMISSION_GRANTED;

        long origId = Binder.clearCallingIdentity();

        synchronized(mWindowMap) {
            // 查到对应的 WindowState 对象
            WindowState win = windowForClientLocked(session, client, false);
            if (win == null) {
                return 0;
            }
            // 从 WindowState 对象获取 WindowStateAnimator 对象
            WindowStateAnimator winAnimator = win.mWinAnimator;
            if (viewVisibility != View.GONE && (win.mRequestedWidth != requestedWidth
                    || win.mRequestedHeight != requestedHeight)) {
                win.mLayoutNeeded = true;
                win.mRequestedWidth = requestedWidth;
                win.mRequestedHeight = requestedHeight;
            }
            ......
            // 设置标志位——客户端是否要求推迟对其 Surface 的销毁,直到它明确表示可以。
            winAnimator.mSurfaceDestroyDeferred =
                    (flags&WindowManagerGlobal.RELAYOUT_DEFER_SURFACE_DESTROY) != 0;
            ......
            if (viewVisibility == View.VISIBLE &&
                    (win.mAppToken == null || !win.mAppToken.clientHidden)) {
                ......
                try {
                    if (!win.mHasSurface) {
                        surfaceChanged = true;
                    }
                    SurfaceControl surfaceControl = winAnimator.createSurfaceLocked();
                    if (surfaceControl != null) {
                        outSurface.copyFrom(surfaceControl);
                        if (SHOW_TRANSACTIONS) Slog.i(TAG,
                                "  OUT SURFACE " + outSurface + ": copied");
                    } else {
                        // For some reason there isn't a surface.  Clear the
                        // caller's object so they see the same state.
                        outSurface.release();
                    }
                } catch (Exception e) {
                    mInputMonitor.updateInputWindowsLw(true /*force*/);

                    Slog.w(TAG, "Exception thrown when creating surface for client "
                             + client + " (" + win.mAttrs.getTitle() + ")",
                             e);
                    Binder.restoreCallingIdentity(origId);
                    return 0;
                }
                ......
            } else {
                ......
                outSurface.release();
                if (DEBUG_VISIBILITY) Slog.i(TAG, "Releasing surface in: " + win);
            }
            ......
        }
        ......
        return (inTouchMode ? WindowManagerGlobal.RELAYOUT_RES_IN_TOUCH_MODE : 0)
                | (toBeDisplayed ? WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME : 0)
                | (surfaceChanged ? WindowManagerGlobal.RELAYOUT_RES_SURFACE_CHANGED : 0);
    }
    ......
}

WindowStateAnimator 代表跟踪单个 WindowState 的动画和 Surface 操作。我们主要关注创建 SurfaceControl 对象。

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

class WindowStateAnimator {
    ......
    SurfaceControl mSurfaceControl;    
    ......
    SurfaceControl createSurfaceLocked() {
        final WindowState w = mWin;
        if (mSurfaceControl == null) {
            if (DEBUG_ANIM || DEBUG_ORIENTATION) Slog.i(TAG,
                    "createSurface " + this + ": mDrawState=DRAW_PENDING");
            mDrawState = DRAW_PENDING;
            if (w.mAppToken != null) {
                if (w.mAppToken.mAppAnimator.animation == null) {
                    w.mAppToken.allDrawn = false;
                    w.mAppToken.deferClearAllDrawn = false;
                } else {
                    // 当前正在动画中,请保持 allDrawn 的当前状态,直到动画完成。
                    w.mAppToken.deferClearAllDrawn = true;
                }
            }

            mService.makeWindowFreezingScreenIfNeededLocked(w);

            int flags = SurfaceControl.HIDDEN;
            final WindowManager.LayoutParams attrs = w.mAttrs;

            if (mService.isSecureLocked(w)) {
                flags |= SurfaceControl.SECURE;
            }

            int width;
            int height;
            if ((attrs.flags & LayoutParams.FLAG_SCALED) != 0) {
                // 对于一个缩放的 Surface,我们总是需要所要求的大小。
                width = w.mRequestedWidth;
                height = w.mRequestedHeight;
            } else {
                width = w.mCompatFrame.width();
                height = w.mCompatFrame.height();
            }

            // 出了点问题,SurfaceFlinger 不喜欢这样,请尝试还原为合理的值
            if (width <= 0) {
                width = 1;
            }
            if (height <= 0) {
                height = 1;
            }

            float left = w.mFrame.left + w.mXOffset;
            float top = w.mFrame.top + w.mYOffset;

            // 调整 surface inset
            width += attrs.surfaceInsets.left + attrs.surfaceInsets.right;
            height += attrs.surfaceInsets.top + attrs.surfaceInsets.bottom;
            left -= attrs.surfaceInsets.left;
            top -= attrs.surfaceInsets.top;

            if (DEBUG_VISIBILITY) {
                Slog.v(TAG, "Creating surface in session "
                        + mSession.mSurfaceSession + " window " + this
                        + " w=" + width + " h=" + height
                        + " x=" + left + " y=" + top
                        + " format=" + attrs.format + " flags=" + flags);
            }

            // 我们可能会中止,因此请初始化为默认值。
            mSurfaceShown = false;
            mSurfaceLayer = 0;
            mSurfaceAlpha = 0;
            mSurfaceX = 0;
            mSurfaceY = 0;
            w.mLastSystemDecorRect.set(0, 0, 0, 0);
            mHasClipRect = false;
            mClipRect.set(0, 0, 0, 0);
            mLastClipRect.set(0, 0, 0, 0);

            // 设置具有初始尺寸的 surface control。
            try {
                mSurfaceW = width;
                mSurfaceH = height;

                final boolean isHwAccelerated = (attrs.flags &
                        WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0;
                final int format = isHwAccelerated ? PixelFormat.TRANSLUCENT : attrs.format;
                if (!PixelFormat.formatHasAlpha(attrs.format)
                        && attrs.surfaceInsets.left == 0
                        && attrs.surfaceInsets.top == 0
                        && attrs.surfaceInsets.right == 0
                        && attrs.surfaceInsets.bottom  == 0) {
                    flags |= SurfaceControl.OPAQUE;
                }

                mSurfaceFormat = format;
                if (DEBUG_SURFACE_TRACE) {
                    mSurfaceControl = new SurfaceTrace(
                            mSession.mSurfaceSession,
                            attrs.getTitle().toString(),
                            width, height, format, flags);
                } else {
                    // 创建 SurfaceControl 对象
                    mSurfaceControl = new SurfaceControl(
                        mSession.mSurfaceSession,
                        attrs.getTitle().toString(),
                        width, height, format, flags);
                }

                w.mHasSurface = true;

                if (SHOW_TRANSACTIONS || SHOW_SURFACE_ALLOC) {
                    Slog.i(TAG, "  CREATE SURFACE "
                            + mSurfaceControl + " IN SESSION "
                            + mSession.mSurfaceSession
                            + ": pid=" + mSession.mPid + " format="
                            + attrs.format + " flags=0x"
                            + Integer.toHexString(flags)
                            + " / " + this);
                }
            } catch (OutOfResourcesException e) {
                w.mHasSurface = false;
                Slog.w(TAG, "OutOfResourcesException creating surface");
                mService.reclaimSomeSurfaceMemoryLocked(this, "create", true);
                mDrawState = NO_SURFACE;
                return null;
            } catch (Exception e) {
                w.mHasSurface = false;
                Slog.e(TAG, "Exception creating surface", e);
                mDrawState = NO_SURFACE;
                return null;
            }

            if (WindowManagerService.localLOGV) {
                Slog.v(TAG, "Got surface: " + mSurfaceControl
                        + ", set left=" + w.mFrame.left + " top=" + w.mFrame.top
                        + ", animLayer=" + mAnimLayer);
            }

            if (SHOW_LIGHT_TRANSACTIONS) {
                Slog.i(TAG, ">>> OPEN TRANSACTION createSurfaceLocked");
                WindowManagerService.logSurface(w, "CREATE pos=("
                        + w.mFrame.left + "," + w.mFrame.top + ") ("
                        + w.mCompatFrame.width() + "x" + w.mCompatFrame.height()
                        + "), layer=" + mAnimLayer + " HIDE", null);
            }

            // 开始一个新的事务并应用位置和偏移
            SurfaceControl.openTransaction();
            try {
                mSurfaceX = left;
                mSurfaceY = top;

                try {
                    mSurfaceControl.setPosition(left, top);
                    mSurfaceLayer = mAnimLayer;
                    final DisplayContent displayContent = w.getDisplayContent();
                    if (displayContent != null) {
                        mSurfaceControl.setLayerStack(displayContent.getDisplay().getLayerStack());
                    }
                    mSurfaceControl.setLayer(mAnimLayer);
                    mSurfaceControl.setAlpha(0);
                    mSurfaceShown = false;
                } catch (RuntimeException e) {
                    Slog.w(TAG, "Error creating surface in " + w, e);
                    mService.reclaimSomeSurfaceMemoryLocked(this, "create-init", true);
                }
                mLastHidden = true;
            } finally {
                // 事务关闭
                SurfaceControl.closeTransaction();
                if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG,
                        "<<< CLOSE TRANSACTION createSurfaceLocked");
            }
            if (WindowManagerService.localLOGV) Slog.v(
                    TAG, "Created surface " + this);
        }
        return mSurfaceControl;
    }
    ......
}

创建一个名为 name 的 Surface。

Surface 创建标志指定要创建的 Surface 类型以及某些选项,例如是否可以假定该 Surface 为不透明 Surface 以及是否应首先隐藏。 在创建 Surface 时,应始终设置 HIDDEN 标志,以确保在配置了 Surface 的所有属性之前不会过早使它们可见。

优良作法是先创建带有指定的 HIDDEN 标志的 Surface ,打开一个事务,设置 Surface 层,层堆栈,alpha 和位置,并在适当时调用 show,然后关闭该事务。

  1. session Surface 会话,不能为 null。
  2. name Surface 名称,不能为 null。
  3. w Surface 初始宽度。
  4. h Surface 初始高度。
  5. flags Surface 创建标志。在创建标记中应始终包含 HIDDEN。

SurfaceControl 构造函数中调用了 nativeCreate(…) 去创建 Surface。

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

public class SurfaceControl {
    ......
    private static native long nativeCreate(SurfaceSession session, String name,
            int w, int h, int format, int flags)
            throws OutOfResourcesException;    
    ......
    public SurfaceControl(SurfaceSession session,
            String name, int w, int h, int format, int flags)
                    throws OutOfResourcesException {
        if (session == null) {
            throw new IllegalArgumentException("session must not be null");
        }
        if (name == null) {
            throw new IllegalArgumentException("name must not be null");
        }

        if ((flags & SurfaceControl.HIDDEN) == 0) {
            Log.w(TAG, "Surfaces should always be created with the HIDDEN flag set "
                    + "to ensure that they are not made visible prematurely before "
                    + "all of the surface's properties have been configured.  "
                    + "Set the other properties and make the surface visible within "
                    + "a transaction.  New surface name: " + name,
                    new Throwable());
        }

        mName = name;
        mNativeObject = nativeCreate(session, name, w, h, format, flags);
        if (mNativeObject == 0) {
            throw new OutOfResourcesException(
                    "Couldn't allocate SurfaceControl native object");
        }

        mCloseGuard.open("release");
    }    
    ......
}
  1. 调用 android_view_SurfaceSession_getClient(…) 获取 SurfaceComposerClient 对象
  2. 调用 SurfaceComposerClient 类 createSurface(…) 方法获取 Native SurfaceControl 对象
  3. Native SurfaceControl 对象强引用计数加一,触发其 onFirstRef(…) 函数调用

frameworks/base/core/jni/android_view_SurfaceControl.cpp

static jlong nativeCreate(JNIEnv* env, jclass clazz, jobject sessionObj,
        jstring nameStr, jint w, jint h, jint format, jint flags) {
    ScopedUtfChars name(env, nameStr);
    sp<SurfaceComposerClient> client(android_view_SurfaceSession_getClient(env, sessionObj));
    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());
}

mClient 指向 BpSurfaceComposerClient 对象,调用其 createSurface(…) 方法,最终会在 Bn 端实现 Client 中调用 createSurface(…) 方法。最后创建了 Native SurfaceControl 对象,并将其返回。

frameworks/native/libs/gui/SurfaceComposerClient.cpp

sp<SurfaceControl> SurfaceComposerClient::createSurface(
        const String8& name,
        uint32_t w,
        uint32_t h,
        PixelFormat format,
        uint32_t flags)
{
    sp<SurfaceControl> sur;
    if (mStatus == NO_ERROR) {
        sp<IBinder> handle;
        sp<IGraphicBufferProducer> gbp;
        status_t err = mClient->createSurface(name, w, h, format, flags,
                &handle, &gbp);
        ALOGE_IF(err, "SurfaceComposerClient::createSurface error %s", strerror(-err));
        if (err == NO_ERROR) {
            sur = new SurfaceControl(this, handle, gbp);
        }
    }
    return sur;
}

必须从 GL 线程调用 createSurface,以便它可以访问 GL 上下文。

Client::createSurface(…) 方法内部定义了一个 MessageCreateLayer 类,其内部定义了 handler() 方法,handler() 方法内部调用了 SurfaceFlinger 类的 createLayer(…) 方法。

首先创建一个 MessageCreateLayer 对象,然后将它 post 到消息队列同步处理,最后得到结果 result 状态返回值。

frameworks/native/services/surfaceflinger/Client.cpp

status_t Client::createSurface(
        const String8& name,
        uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
        sp<IBinder>* handle,
        sp<IGraphicBufferProducer>* gbp)
{
    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();
}

SurfaceFlinger::postMessageSync(…) 就是将消息 post 到 MessageQueue 中,然后调用 wait() 方法等待消息处理结束后返回,达到同步的目的。

frameworks/native/services/surfaceflinger/SurfaceFlinger.h

class SurfaceFlinger : public BnSurfaceComposer,
                       private IBinder::DeathRecipient,
                       private HWComposer::EventHandler
{
public:
    ......
    // post a synchronous message to the main thread
    status_t postMessageSync(const sp<MessageBase>& msg, nsecs_t reltime = 0, uint32_t flags = 0);
    ......
}

下面是 SurfaceFlinger::postMessageSync(…) 方法具体实现,实际上后两个参数都为 0。

frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp

status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
        nsecs_t reltime, uint32_t /* flags */) {
    status_t res = mEventQueue.postMessage(msg, reltime);
    if (res == NO_ERROR) {
        msg->wait();
    }
    return res;
}

mEventQueue 是一个 MessageQueue 类型变量,这个 MessageQueue 定义在 frameworks/native/services/surfaceflinger/ 下。经过上面分析不难得出走 else 分支。注意入参 messageHandler,它指向了 MessageCreateLayer 对象。

frameworks/native/services/surfaceflinger/MessageQueue.cpp

status_t MessageQueue::postMessage(
        const sp<MessageBase>& messageHandler, nsecs_t relTime)
{
    const Message dummyMessage;
    if (relTime > 0) {
        mLooper->sendMessageDelayed(relTime, messageHandler, dummyMessage);
    } else {
        mLooper->sendMessage(messageHandler, dummyMessage);
    }
    return NO_ERROR;
}

Android 源码 图形系统之 relayoutWindow

MessageCreateLayer 类继承了 MessageBase。MessageBase 类内部定义了成员变量 barrier,这个屏障显然是用来实现同步的。结合上面分析, handler() 纯虚函数实现在 MessageCreateLayer 类中。

frameworks/native/services/surfaceflinger/MessageQueue.h

class MessageBase : public MessageHandler
{
public:
    MessageBase();

    // return true if message has a handler
    virtual bool handler() = 0;

    // waits for the handler to be processed
    void wait() const { barrier.wait(); }

protected:
    virtual ~MessageBase();

private:
    virtual void handleMessage(const Message& message);

    mutable Barrier barrier;
};

回到 SurfaceFlinger,其 run() 方法会处理消息,确切的说 run() 方法内最终会调用 Looper 轮询消息并处理。run() 方法体内部一个无限循环调用了 waitForEvent() 方法。

frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp

void SurfaceFlinger::run() {
    do {
        waitForEvent();
    } while (true);
}

waitForEvent() 方法内部调用了 MessageQueue 类 waitMessage() 方法。

frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp

void SurfaceFlinger::waitForEvent() {
    mEventQueue.waitMessage();
}

waitMessage() 内部调用了 Looper 类 pollOnce(…) 轮询消息,内部最终会调用 MessageHandler 类 handleMessage(…) 方法处理消息。

frameworks/native/services/surfaceflinger/MessageQueue.cpp

void MessageQueue::waitMessage() {
    do {
        IPCThreadState::self()->flushCommands();
        int32_t ret = mLooper->pollOnce(-1);
        switch (ret) {
            case Looper::POLL_WAKE:
            case Looper::POLL_CALLBACK:
                continue;
            case Looper::POLL_ERROR:
                ALOGE("Looper::POLL_ERROR");
            case Looper::POLL_TIMEOUT:
                // timeout (should not happen)
                continue;
            default:
                // should not happen
                ALOGE("Looper::pollOnce() returned unknown status %d", ret);
                continue;
        }
    } while (true);
}

现在来看 handleMessage(…) 实现,其内部果然调用了 handler() 方法,并且最后把屏障打开了,使得 SurfaceFlinger::postMessageSync(…) 方法得以返回。

frameworks/native/services/surfaceflinger/MessageQueue.cpp

void MessageBase::handleMessage(const Message&) {
    this->handler();
    barrier.open();
};

现在继续分析 SurfaceFlinger 类 createLayer(…) 方法。

  1. 根据不同类型创建不同的层 Layer
  2. 调用 addClientLayer(…) 方法添加层到 Client

frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp

status_t SurfaceFlinger::createLayer(
        const String8& name,
        const sp<Client>& client,
        uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
        sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
{
    //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
    if (int32_t(w|h) < 0) {
        ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
                int(w), int(h));
        return BAD_VALUE;
    }

    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;
        case ISurfaceComposerClient::eFXSurfaceDim:
            result = createDimLayer(client,
                    name, w, h, flags,
                    handle, gbp, &layer);
            break;
        default:
            result = BAD_VALUE;
            break;
    }

    if (result != NO_ERROR) {
        return result;
    }

    result = addClientLayer(client, *handle, *gbp, layer);
    if (result != NO_ERROR) {
        return result;
    }

    setTransactionFlags(eTransactionNeeded);
    return result;
}

SurfaceFlinger::createNormalLayer(…) 方法中创建了 Layer(普通层)对象。

SurfaceFlinger::createDimLayer(…) 方法中创建了 LayerDim(模糊层)对象。

handle(指向 Binder 代理对象) 和 gbp(指向 GraphicBufferProducer 代理对象)赋值都会从层中获取。

frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp

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)
{
    // 初始化 Surface
    switch (format) {
    case PIXEL_FORMAT_TRANSPARENT:
    case PIXEL_FORMAT_TRANSLUCENT:
        format = PIXEL_FORMAT_RGBA_8888;
        break;
    case PIXEL_FORMAT_OPAQUE:
        format = PIXEL_FORMAT_RGBX_8888;
        break;
    }

    *outLayer = new Layer(this, client, name, w, h, flags);
    status_t err = (*outLayer)->setBuffers(w, h, format, flags);
    if (err == NO_ERROR) {
        *handle = (*outLayer)->getHandle();
        *gbp = (*outLayer)->getProducer();
    }

    ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
    return err;
}

status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
        const String8& name, uint32_t w, uint32_t h, uint32_t flags,
        sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
{
    *outLayer = new LayerDim(this, client, name, w, h, flags);
    *handle = (*outLayer)->getHandle();
    *gbp = (*outLayer)->getProducer();
    return NO_ERROR;
}

最后来分析一下调用 addClientLayer(…) 方法添加层到 Client。

  1. 将层添加到 layersSortedByZ(Z-Order) 中
  2. 将 gbc Binder 对象添加到 mGraphicBufferProducerList 中
  3. 将层 attach 到客户端

frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp

status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
        const sp<IBinder>& handle,
        const sp<IGraphicBufferProducer>& gbc,
        const sp<Layer>& lbc)
{
    // 将此层添加到当前状态列表中
    {
        Mutex::Autolock _l(mStateLock);
        if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
            return NO_MEMORY;
        }
        mCurrentState.layersSortedByZ.add(lbc);
        mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
    }

    // 将此层 attach 到客户端
    client->attachLayer(handle, lbc);

    return NO_ERROR;
}

Client::attachLayer(…) 方法仅仅将 handle 作为 key,layer 作为 value 添加到向量中。

frameworks/native/services/surfaceflinger/Client.cpp

void Client::attachLayer(const sp<IBinder>& handle 作为 key,, const sp<Layer>& layer)
{
    Mutex::Autolock _l(mLock);
    mLayers.add(handle, layer);
}

Android 源码 图形系统之 relayoutWindow

现在回头继续分析创建 Native SurfaceControl 对象。使用实参初始化了 mClient、mHandle 和 mGraphicBufferProducer 三个成员变量。

frameworks/native/libs/gui/SurfaceControl.cpp

SurfaceControl::SurfaceControl(
        const sp<SurfaceComposerClient>& client,
        const sp<IBinder>& handle,
        const sp<IGraphicBufferProducer>& gbp)
    : mClient(client), mHandle(handle), mGraphicBufferProducer(gbp)
{
}

到此为止,后面继续分析 Layer 的创建,以及 outSurface 初始化(调用其 copyFrom(…) 方法,入参是 SurfaceControl 对象)。

本文地址:https://blog.csdn.net/tyyj90/article/details/107989608

相关标签: Android源码