Android 13 WindowContainer 树是如何一步一步创建出来的

1. 引言:为什么要关心 WindowContainer 树

在 Android 13 的窗口系统中,WindowContainer 是整个层级结构的骨架。无论是 Activity、Task、DisplayArea,还是各种类型的窗口,最终都会被组织成一棵以 Root 为根的树。理解这棵树是如何一步一步被创建出来的,是读懂窗口层级、调试多窗口问题、排查焦点与输入分发异常的关键。

本文从 SystemServer 启动 WindowManagerService 开始,沿着源码调用链,逐步还原 Android 13 中 WindowContainer 树的构建过程。

层级结构树查看可以参考我的另一篇文章:android WindowContainer层级树日志以及uml图

2. 核心概念速览

在进入流程之前,先了解几个角色:

  • WindowContainer:所有窗口容器的基类,负责维护父子关系、层级顺序、可见性等。
  • Root :树的根节点,持有 DisplayContent 列表。
  • DisplayContent:对应一个逻辑显示设备,是每个屏幕窗口树的根。
  • DisplayArea :显示区域容器,Android 13 中引入了 DisplayAreaGroup、TaskDisplayArea、Tokens 等分层结构。
  • TaskDisplayArea :它为DisplayContent的孩子,对应着窗口层次的第2层。第2层作为应用层,看它的定义:int APPLICATION_LAYER = 2,应用层的窗口是处于第2层。TaskDisplayArea的孩子是Task类,其实它的孩子类型也可以是TaskDisplayArea。而Task的孩子则可以是ActivityRecord,也可以是Task。
  • Task / TaskFragment:任务容器,承载 Activity 记录。
  • Tokens :代表专门包含WindowTokens的容器,它的孩子是WindowToken,而WindowToken的孩子则为WindowState对象。WindowState是对应着一个窗口的。
  • ImeContainer :它是 输入法 窗口的容器,它的孩子是WindowToken类型。WindowToken的孩子为WindowState类型,而WindowState类型则对应着输入法窗口。
  • ActivityRecord :是对应着应用进程中的Activity的。ActivityRecord是继承WindowToken的,它的孩子类型为WindowState。
  • WindowState:真正的窗口节点,是树的叶子。

3. 起点:SystemServer 启动 WMS

WindowContainer 树的创建起点在 SystemServer 的 startOtherServices() 中。系统会创建 WindowManagerService,并在其构造过程中初始化 Root(这里只是创建了一个空壳),具体在setWindowManager:

java 复制代码
// SystemServer.java(简化)
private void startOtherServices() {
    WindowManagerService wm = WindowManagerService.main(
            context, inputManager, !mFirstBoot, mOnlyCore,
            new PhoneWindowManager(), mActivityManagerService.mActivityTaskManager);

mActivityManagerService.setWindowManager(wm);
    // ...
}

4. 第二步:DisplayContent 的创建

创建DisplayContent,并将其添加成自己Child

java 复制代码
// RootWindowContainer.java
void setWindowManager(WindowManagerService wm) {
    ...

    final Display[] displays = mDisplayManager.getDisplays();
    for (int displayNdx = 0; displayNdx < displays.length; ++displayNdx) {
        final Display display = displays[displayNdx];
        final DisplayContent displayContent = new DisplayContent(display, this);
        addChild(displayContent, POSITION_BOTTOM);
        if (displayContent.mDisplayId == DEFAULT_DISPLAY) {
            mDefaultDisplay = displayContent;
        }
    }
   ...
}

在初始化DisplayContent调用configureSurfaces(实际调用这里surface相关图层配置,因为显示东西都需要Surfaceflinge)

scss 复制代码
// DisplayContent.java
DisplayContent(Display display, RootWindowContainer root) {
    final Transaction pendingTransaction = getPendingTransaction();
    configureSurfaces(pendingTransaction);
    pendingTransaction.apply();
  }

由于第一次进来的时候mDisplayAreaPolicy必定为null,所以会调用instantiate对DisplayArea进行构建

typescript 复制代码
// DisplayContent.java
    private void configureSurfaces(Transaction transaction) {
       ...
    
        if (mDisplayAreaPolicy == null) {
            // Setup the policy and build the display area hierarchy.
            // Build the hierarchy only after creating the surface so it is reparented correctly
            mDisplayAreaPolicy = mWmService.getDisplayAreaPolicyProvider().instantiate对(
                    mWmService, this /* content */, this /* root */,
                    mImeWindowsContainer);
        }
   ...
    }

准备TaskDisplayArea,构建HierarchyBuilder对象,并将其与imeContainer设置进去

java 复制代码
//DisplayAreaPolicy.java
static final class DefaultProvider implements DisplayAreaPolicy.Provider {
    @Override
    public DisplayAreaPolicy instantiate(WindowManagerService wmService,
            DisplayContent content, RootDisplayArea root,
            DisplayArea.Tokens imeContainer) {
        //创建特殊的TaskDisplayArea,这里我们前面讲过它是专门来装Activity相关的容器
        final TaskDisplayArea defaultTaskDisplayArea = new TaskDisplayArea(content, wmService,
                "DefaultTaskDisplayArea", FEATURE_DEFAULT_TASK_CONTAINER);
        final List<TaskDisplayArea> tdaList = new ArrayList<>();
        tdaList.add(defaultTaskDisplayArea);

        // Define the features that will be supported under the root of the whole logical
        // display. The policy will build the DisplayArea hierarchy based on this.
        final HierarchyBuilder rootHierarchy = new HierarchyBuilder(root);
        // Set the essential containers (even if the display doesn't support IME).
        //这里同时setImeContainer进行输入法直接容器设置
        rootHierarchy.setImeContainer(imeContainer).setTaskDisplayAreas(tdaList);
        if (content.isTrusted()) {
            //主屏幕肯定进入,也是构成层级关键
            // Only trusted display can have system decorations.
            configureTrustedHierarchyBuilder(rootHierarchy, wmService, content);
        }

        // Instantiate the policy with the hierarchy defined above. This will create and attach
        // all the necessary DisplayAreas to the root.
        return new DisplayAreaPolicyBuilder().setRootHierarchy(rootHierarchy).build(wmService);
    }
less 复制代码
//DisplayAreaPolicy.java
    private void configureTrustedHierarchyBuilder(HierarchyBuilder rootHierarchy,
            WindowManagerService wmService, DisplayContent content) {
        // WindowedMagnification should be on the top so that there is only one surface
        // to be magnified.
        rootHierarchy.addFeature(new Feature.Builder(wmService.mPolicy, "WindowedMagnification",
                FEATURE_WINDOWED_MAGNIFICATION)
                .upTo(TYPE_ACCESSIBILITY_MAGNIFICATION_OVERLAY)
                .except(TYPE_ACCESSIBILITY_MAGNIFICATION_OVERLAY)
                // Make the DA dimmable so that the magnify window also mirrors the dim layer.
                .setNewDisplayAreaSupplier(DisplayArea.Dimmable::new)
                .build());
        if (content.isDefaultDisplay) {
            // Only default display can have cutout.
            // See LocalDisplayAdapter.LocalDisplayDevice#getDisplayDeviceInfoLocked.
            rootHierarchy.addFeature(new Feature.Builder(wmService.mPolicy, "HideDisplayCutout",
                    FEATURE_HIDE_DISPLAY_CUTOUT)
                    .all()
                    .except(TYPE_NAVIGATION_BAR, TYPE_NAVIGATION_BAR_PANEL, TYPE_STATUS_BAR,
                            TYPE_NOTIFICATION_SHADE)
                    .build())
                    .addFeature(new Feature.Builder(wmService.mPolicy, "OneHanded",
                            FEATURE_ONE_HANDED)
                            .all()
                            .except(TYPE_NAVIGATION_BAR, TYPE_NAVIGATION_BAR_PANEL,
                                    TYPE_SECURE_SYSTEM_OVERLAY)
                            .build());
        }
        rootHierarchy
                .addFeature(new Feature.Builder(wmService.mPolicy, "FullscreenMagnification",
                        FEATURE_FULLSCREEN_MAGNIFICATION)
                        .all()
                        .except(TYPE_ACCESSIBILITY_MAGNIFICATION_OVERLAY, TYPE_INPUT_METHOD,
                                TYPE_INPUT_METHOD_DIALOG, TYPE_MAGNIFICATION_OVERLAY,
                                TYPE_NAVIGATION_BAR, TYPE_NAVIGATION_BAR_PANEL)
                        .build())
                .addFeature(new Feature.Builder(wmService.mPolicy, "ImePlaceholder",
                        FEATURE_IME_PLACEHOLDER)
                        .and(TYPE_INPUT_METHOD, TYPE_INPUT_METHOD_DIALOG)
                        .build());
    }
}

Feature在创建时就是根据upTo、except、all、and这些方法来决定它对应哪些窗口层级的

  • WindowedMagnification 0-31
  • HideDisplayCutout 0-14 16 18-23 26-35
  • OneHanded 0-23 26-32 34-35
  • FullscreenMagnification 0-12 15-23 26-27 29-31 33-35
  • ImePlaceholder 13-14

回到DisplayAreaPolicyBuilder().setRootHierarchy(rootHierarchy).build(wmService)

scss 复制代码
//DisplayAreaPolicyBuilder
Result build(WindowManagerService wmService) {
    validate();

    // Attach DA group roots to screen hierarchy before adding windows to group hierarchies.
    mRootHierarchyBuilder.build(mDisplayAreaGroupHierarchyBuilders);
    List<RootDisplayArea> displayAreaGroupRoots = new ArrayList<>(
            mDisplayAreaGroupHierarchyBuilders.size());
    for (int i = 0; i < mDisplayAreaGroupHierarchyBuilders.size(); i++) {
        HierarchyBuilder hierarchyBuilder = mDisplayAreaGroupHierarchyBuilders.get(i);
        hierarchyBuilder.build();
        displayAreaGroupRoots.add(hierarchyBuilder.mRoot);
    }
    // Use the default function if it is not specified otherwise.
    if (mSelectRootForWindowFunc == null) {
        mSelectRootForWindowFunc = new DefaultSelectRootForWindowFunction(
                mRootHierarchyBuilder.mRoot, displayAreaGroupRoots);
    }
    return new Result(wmService, mRootHierarchyBuilder.mRoot, displayAreaGroupRoots,
            mSelectRootForWindowFunc, mSelectTaskDisplayAreaFunc);
}
scss 复制代码
/**
 * Builds the {@link DisplayArea} hierarchy below root. And adds the roots of those
 * {@link HierarchyBuilder} as children.
 */
private void build(@Nullable List<HierarchyBuilder> displayAreaGroupHierarchyBuilders) {
    final WindowManagerPolicy policy = mRoot.mWmService.mPolicy;
    final int maxWindowLayerCount = policy.getMaxWindowLayer() + 1;
    final DisplayArea.Tokens[] displayAreaForLayer =
            new DisplayArea.Tokens[maxWindowLayerCount];
    final Map<Feature, List<DisplayArea<WindowContainer>>> featureAreas =
            new ArrayMap<>(mFeatures.size());
    for (int i = 0; i < mFeatures.size(); i++) {
        featureAreas.put(mFeatures.get(i), new ArrayList<>());
    }

    // This method constructs the layer hierarchy with the following properties:
    // (1) Every feature maps to a set of DisplayAreas
    // (2) After adding a window, for every feature the window's type belongs to,
    //     it is a descendant of one of the corresponding DisplayAreas of the feature.
    // (3) Z-order is maintained, i.e. if z-range(area) denotes the set of layers of windows
    //     within a DisplayArea:
    //      for every pair of DisplayArea siblings (a,b), where a is below b, it holds that
    //      max(z-range(a)) <= min(z-range(b))
    //
    // The algorithm below iteratively creates such a hierarchy:
    //  - Initially, all windows are attached to the root.
    //  - For each feature we create a set of DisplayAreas, by looping over the layers
    //    - if the feature does apply to the current layer, we need to find a DisplayArea
    //      for it to satisfy (2)
    //      - we can re-use the previous layer's area if:
    //         the current feature also applies to the previous layer, (to satisfy (3))
    //         and the last feature that applied to the previous layer is the same as
    //           the last feature that applied to the current layer (to satisfy (2))
    //      - otherwise we create a new DisplayArea below the last feature that applied
    //        to the current layer

    PendingArea[] areaForLayer = new PendingArea[maxWindowLayerCount];
    final PendingArea root = new PendingArea(null, 0, null);
    Arrays.fill(areaForLayer, root);

    // Create DisplayAreas to cover all defined features.
    final int size = mFeatures.size();
    for (int i = 0; i < size; i++) {
        // Traverse the features with the order they are defined, so that the early defined
        // feature will be on the top in the hierarchy.
        final Feature feature = mFeatures.get(i);
        PendingArea featureArea = null;
        for (int layer = 0; layer < maxWindowLayerCount; layer++) {
            if (feature.mWindowLayers[layer]) {
                // This feature will be applied to this window layer.
                //
                // We need to find a DisplayArea for it:
                // We can reuse the existing one if it was created for this feature for the
                // previous layer AND the last feature that applied to the previous layer is
                // the same as the feature that applied to the current layer (so they are ok
                // to share the same parent DisplayArea).
                if (featureArea == null || featureArea.mParent != areaForLayer[layer]) {
                    // No suitable DisplayArea:
                    // Create a new one under the previous area (as parent) for this layer.
                    featureArea = new PendingArea(feature, layer, areaForLayer[layer]);
                    areaForLayer[layer].mChildren.add(featureArea);
                }
                areaForLayer[layer] = featureArea;
            } else {
                // This feature won't be applied to this window layer. If it needs to be
                // applied to the next layer, we will need to create a new DisplayArea for
                // that.
                featureArea = null;
            }
        }
    }

    // Create Tokens as leaf for every layer.
    PendingArea leafArea = null;
    int leafType = LEAF_TYPE_TOKENS;
    for (int layer = 0; layer < maxWindowLayerCount; layer++) {
        int type = typeOfLayer(policy, layer);
        // Check whether we can reuse the same Tokens with the previous layer. This happens
        // if the previous layer is the same type as the current layer AND there is no
        // feature that applies to only one of them.
        if (leafArea == null || leafArea.mParent != areaForLayer[layer]
                || type != leafType) {
            // Create a new Tokens for this layer.
            leafArea = new PendingArea(null /* feature */, layer, areaForLayer[layer]);
            areaForLayer[layer].mChildren.add(leafArea);
            leafType = type;
            if (leafType == LEAF_TYPE_TASK_CONTAINERS) {
                // We use the passed in TaskDisplayAreas for task container type of layer.
                // Skip creating Tokens even if there is no TDA.
                addTaskDisplayAreasToApplicationLayer(areaForLayer[layer]);
                addDisplayAreaGroupsToApplicationLayer(areaForLayer[layer],
                        displayAreaGroupHierarchyBuilders);
                leafArea.mSkipTokens = true;
            } else if (leafType == LEAF_TYPE_IME_CONTAINERS) {
                // We use the passed in ImeContainer for ime container type of layer.
                // Skip creating Tokens even if there is no ime container.
                leafArea.mExisting = mImeContainer;
                leafArea.mSkipTokens = true;
            }
        }
        leafArea.mMaxLayer = layer;
    }
    root.computeMaxLayer();

    // We built a tree of PendingAreas above with all the necessary info to represent the
    // hierarchy, now create and attach real DisplayAreas to the root.
    root.instantiateChildren(mRoot, displayAreaForLayer, 0, featureAreas);

    // Notify the root that we have finished attaching all the DisplayAreas. Cache all the
    // feature related collections there for fast access.
    mRoot.onHierarchyBuilt(mFeatures, displayAreaForLayer, featureAreas);
}

这里的PendingArea是构建DisplayArea层级树过程中的临时数据结构,这个创建过程主要是为父子结点形成树结构。root.instantiateChildren(mRoot, displayAreaForLayer, 0, featureAreas)将PendingArea转换为DisplayArea,并挂载到DisplayContent。到此完成了整个 WindowContainer层级结构树初始化创建

SurfaceFlinger图层创建

继续接着上面分析在执行root.instantiateChildren后执行addChild,再执行setParent,最后执行到

scss 复制代码
//WindowContainer.java
void onParentChanged(ConfigurationContainer newParent, ConfigurationContainer oldParent,
        PreAssignChildLayersCallback callback) {
    super.onParentChanged(newParent, oldParent);
    if (mParent == null) {
        return;
    }

    if (mSurfaceControl == null) {
        // If we don't yet have a surface, but we now have a parent, we should
        // build a surface.
        createSurfaceControl(false /*force*/);
    } else {
        // If we have a surface but a new parent, we just need to perform a reparent. Go through
        // surface animator such that hierarchy is preserved when animating, i.e.
        // mSurfaceControl stays attached to the leash and we just reparent the leash to the
        // new parent.
        reparentSurfaceControl(getSyncTransaction(), mParent.mSurfaceControl);
    }

    if (callback != null) {
        callback.onPreAssignChildLayers();
    }

    // Either way we need to ask the parent to assign us a Z-order.
    mParent.assignChildLayers();
    scheduleAnimation();
}

第一次进来mSurfaceControl肯定为null,所以执行createSurfaceControl

scss 复制代码
//WindowContainer.java
void createSurfaceControl(boolean force) {
    setInitialSurfaceControlProperties(makeSurface());
}

在这里执行了makeSurface()方法,对SurfaceControl构建进行参数设置

scss 复制代码
SurfaceControl.Builder makeChildSurface(WindowContainer child) {
    final WindowContainer p = getParent();
    // Give the parent a chance to set properties. In hierarchy v1 we rely
    // on this to set full-screen dimensions on all our Surface-less Layers.
    return p.makeChildSurface(child)
            .setParent(mSurfaceControl);
}

最后在setInitialSurfaceControlProperties创建出对应SurfaceControl

scss 复制代码
void setInitialSurfaceControlProperties(SurfaceControl.Builder b) {
    setSurfaceControl(b.setCallsite("WindowContainer.setInitialSurfaceControlProperties").build());
    if (showSurfaceOnCreation()) {
        getSyncTransaction().show(mSurfaceControl);
    }
    updateSurfacePositionNonOrganized();
}

我们可以得出结论在addChild时候其实都会触发WindowContainer.onParentChanged,从而触发DisplayContent中创建对应的SurfaceControl。

SurfaceControl应用端使用

csharp 复制代码
//WindowManagerService.java
   public int relayoutWindow(Session session, IWindow client, LayoutParams attrs,
            int requestedWidth, int requestedHeight, int viewVisibility, int flags,
            ClientWindowFrames outFrames, MergedConfiguration mergedConfiguration,
            SurfaceControl outSurfaceControl, InsetsState outInsetsState,
            InsetsSourceControl[] outActiveControls, Bundle outSyncIdBundle) {
            ...
              // Create surfaceControl before surface placement otherwise layout will be skipped
            // (because WS.isGoneForLayout() is true when there is no surface.
            if (shouldRelayout) {
                try {
                    result = createSurfaceControl(outSurfaceControl, result, win, winAnimator);
                } catch (Exception e) {
                    displayContent.getInputMonitor().updateInputWindowsLw(true /*force*/);

                    ProtoLog.w(WM_ERROR,
                            "Exception thrown when creating surface for client %s (%s). %s",
                            client, win.mAttrs.getTitle(), e);
                    Binder.restoreCallingIdentity(origId);
                    return 0;
                }
            }
...
}
        
csharp 复制代码
private int createSurfaceControl(SurfaceControl outSurfaceControl, int result,
        WindowState win, WindowStateAnimator winAnimator) {
    if (!win.mHasSurface) {
        result |= RELAYOUT_RES_SURFACE_CHANGED;
    }

    WindowSurfaceController surfaceController;
    try {
        Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "createSurfaceControl");
        surfaceController = winAnimator.createSurfaceLocked();
    } finally {
        Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
    }
    if (surfaceController != null) {
        surfaceController.getSurfaceControl(outSurfaceControl);
        ProtoLog.i(WM_SHOW_TRANSACTIONS, "OUT SURFACE %s: copied", outSurfaceControl);

    } else {
        // For some reason there isn't a surface.  Clear the
        // caller's object so they see the same state.
        ProtoLog.w(WM_ERROR, "Failed to create surface control for %s", win);
        outSurfaceControl.release();
    }

    return result;
}

调用createSurfaceControl

csharp 复制代码
private int createSurfaceControl(SurfaceControl outSurfaceControl, int result,
            WindowState win, WindowStateAnimator winAnimator) {
        if (!win.mHasSurface) {
            result |= RELAYOUT_RES_SURFACE_CHANGED;
        }

        WindowSurfaceController surfaceController;
        try {
            Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "createSurfaceControl");
            surfaceController = winAnimator.createSurfaceLocked();
        } finally {
            Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
        }
        if (surfaceController != null) {
            surfaceController.getSurfaceControl(outSurfaceControl);
            ProtoLog.i(WM_SHOW_TRANSACTIONS, "OUT SURFACE %s: copied", outSurfaceControl);

        } else {
            // For some reason there isn't a surface.  Clear the
            // caller's object so they see the same state.
            ProtoLog.w(WM_ERROR, "Failed to create surface control for %s", win);
            outSurfaceControl.release();
        }

        return result;
    }
scss 复制代码
 WindowSurfaceController createSurfaceLocked() {
    ...
  mSurfaceController = new WindowSurfaceController(attrs.getTitle().toString(), format,
                    flags, this, attrs.type);
    ...
}

最后进行创建

ini 复制代码
WindowSurfaceController(String name, int format, int flags, WindowStateAnimator animator,
            int windowType) {
        mAnimator = animator;

        title = name;

        mService = animator.mService;
        final WindowState win = animator.mWin;
        mWindowType = windowType;
        mWindowSession = win.mSession;

        Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "new SurfaceControl");
        final SurfaceControl.Builder b = win.makeSurface()
                .setParent(win.getSurfaceControl())
                .setName(name)
                .setFormat(format)
                .setFlags(flags)
                .setMetadata(METADATA_WINDOW_TYPE, windowType)
                .setMetadata(METADATA_OWNER_UID, mWindowSession.mUid)
                .setMetadata(METADATA_OWNER_PID, mWindowSession.mPid)
                .setCallsite("WindowSurfaceController");//此时其实还是属于Container,因为DisplayerContent创建

        final boolean useBLAST = mService.mUseBLAST && ((win.getAttrs().privateFlags
                & WindowManager.LayoutParams.PRIVATE_FLAG_USE_BLAST) != 0);

        if (useBLAST) {
            b.setBLASTLayer();//非常关键,变成非Container
        }

        mSurfaceControl = b.build();

        Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
    }
相关推荐
zhangphil1 小时前
Android产品级图库/相册应用关键性能瓶颈:媒体数据聚合
android
StarsGreen2 小时前
Android系统相关命令介绍
android·windows
传奇开心果编程2 小时前
【六大移动UI框架比较学与练】第4课:列表与滚动——懒加载、复用与状态保持实战对照
android·flutter·react native·ios·swiftui·移动开发·android jetpack
恋猫de小郭2 小时前
Flutter 奇葩 Bug:错过一次合成,后续每帧的 Raster 都顺带变慢?
android·前端·flutter
三少爷的鞋4 小时前
一段 Kotlin 协程代码,藏着 5 个问题:你能发现几个?
android
棒棒的唐4 小时前
发一个用本地AI(openclaw)写的调用本地llama.cpp服务对话,并按指定要求识别图片的PHP类
android·php·llama
_祝你今天愉快14 小时前
Android 事件传递机制:[二] 手写模拟事件分发
android
东坡大表哥21 小时前
【Ubuntu】Ubuntu 20.04 LTS → 22.04 LTS 升级实录
android·linux·ubuntu
不要试图纠正别人1 天前
IdleHandler 一次都不跑,问题不在主线程忙
android·性能优化