当前位置:   article > 正文

安卓焦点窗口切换_activity切源,请求焦点

activity切源,请求焦点

一、背景

我们经常会遇到一种Application does not hava focused windowANR异常,这种异常一般是没有焦点窗口FocusedWindow导致,且这类异常只会发生在key事件的派发,因为key事件是需要找到一个焦点窗口然后再派发,而触摸事件只需要找到当前显示的窗口即可

焦点窗口设定

焦点窗口是指当前正在与用户交互的窗口,该窗口负责接收键事件和触摸事件。当启动新的Activity、添加新的窗口、移除旧窗口、分屏来回操作时,都会涉及到焦点窗口的更新。

WMS只管理窗口,无法确定是否有窗口盖住当前画面 SurfaceFlinger管理显示,最贴近于用户看到的画面,可以知道可以知道是否有窗口盖住当前画面,根据真实的显示窗口设置对应的window信息给InputDispatcher

关键日志

1.window

在dumpsys window中查看mCurrentFocus和mFocusedApp,也可以通过如下shell命令来查看当前的FocusWindow:

mCurrentFocus=Window{f96644 u0 NotificationShade}

mFocusedApp=ActivityRecord{e9566ee u0 com.android.launcher3/.uioverrides.QuickstepLauncher} t12}

mCurrentFocus指的是当前的焦点窗口

mFocusedApp指的是当前的焦点Activity

  1. $ adb shell dumpsys window d | grep "mCurrentFocus"
  2. mCurrentFocus=Window{135c912 mode=0 rootTaskId=4 u0 com.example.myapplication/com.example.myapplication.MainActivity}

InputWindow是指能接收input事件的窗口,当WMS中状态发生变化后,会将所有符合条件的窗口设置给底层InputFlinger中,在派发事件时,将对从这些窗口中选择目标窗口进行派发,这些窗口就是InputWindow。焦点窗口只有一个,但InputWindow可以有多个。

2.SurfaceFlinger

在dumpsys SurfaceFlinger中查看 HWC layers

  1. Display 4619827259835644672 (active) HWC layers:
  2. ---------------------------------------------------------------------------------------------------------------------------------------------------------------
  3. Layer name
  4. Z | Window Type | Comp Type | Transform | Disp Frame (LTRB) | Source Crop (LTRB) | Frame Rate (Explicit) (Seamlessness) [Focused]
  5. ---------------------------------------------------------------------------------------------------------------------------------------------------------------
  6. com.example.mysystemdialog/com.example.mysystemdialog.MainActivity#118
  7. rel 0 | 1 | CLIENT | 0 | 0 0 1440 2960 | 0.0 0.0 1440.0 2960.0 | [*]
  8. ---------------------------------------------------------------------------------------------------------------------------------------------------------------
  9. StatusBar#75
  10. rel 0 | 2000 | CLIENT | 0 | 0 0 1440 84 | 0.0 0.0 1440.0 84.0 | [ ]
  11. ---------------------------------------------------------------------------------------------------------------------------------------------------------------
  12. NavigationBar0#74
  13. rel 0 | 2019 | CLIENT | 0 | 0 2792 1440 2960 | 0.0 0.0 1440.0 168.0 | [ ]
  14. ---------------------------------------------------------------------------------------------------------------------------------------------------------------

[Focused]这一列有带[*]号,则说明是焦点窗口

3.input

在dumpsys input中查看FocusedApplications和FocusedWindows

  1. FocusedApplications:
  2. displayId=0, name='ActivityRecord{e9566ee u0 com.android.launcher3/.uioverrides.QuickstepLauncher} t12}', dispatchingTimeout=5000ms
  3. FocusedWindows:
  4. displayId=0, name='f96644 NotificationShade'

如果发生ANR,焦点窗口以dumpsys input为主

  1. Input Dispatcher State at time of last ANR:
  2. ANR:
  3. Time:......
  4. Reason:......
  5. Window:......
  6. FocusedApplications:......
  7. FocusedWindows: <none>

4.eventlog

  1. 11-27 16:15:58.902 3932 4137 I input_focus: [Focus request 5e78d93 com.android.mms/com.android.mms.ui.MmsTabActivity,reason=UpdateInputWindows]
  2. 11-27 16:15:58.922 3932 6384 I input_focus: [Focus receive :5e78d93 com.android.mms/com.android.mms.ui.MmsTabActivity,reason=setFocusedWindow]
  3. 11-27 16:15:59.027 3932 4436 I input_focus: [Focus entering 5e78d93 com.android.mms/com.android.mms.ui.MmsTabActivity (server),reason=Window became focusable. Previous reason: NOT_VISIBLE]

requestentering正常情况下是一一对应,打印了entering则表示真正的焦点已经进入到对应的窗口

发生Application does not hava focused window时,一般request 有打印,我们可以通过是否有entering的打印来分析

1.entering部分有打印,代表焦点已经在input里面,但是仍然有ANR,就需要从input等方面分析 2.entering部分未打印,代表input没有被触发焦点窗口设置到input,需排查SurfaceFlinger或WMS

焦点切换三部log打印位置

java层InputMonitor.java的requestFocus(); // "Focus request"

native层InputDispatcher.cpp的setFocusedWindow(),binder线程; // "Focus receive"

native层InputDispatcher.cpp的dispatchFocusLocked(),InputDispatcher线程 // "Focus " + ("entering " : "leaving ")

二、Focused Window的更新

启动App时更新inputInfo/请求焦点窗口流程:

App主线程调ViewRootImpl.java的relayoutWindow();然后调用到Wms的relayoutWindow(),窗口布局流程。

 代码路径:framework/services/core/java/com/android/server/wm/WindowManagerService.java

  1. public int relayoutWindow(Session session, IWindow client, LayoutParams attrs,
  2. int requestedWidth, int requestedHeight, int viewVisibility, int flags,
  3. ClientWindowFrames outFrames, MergedConfiguration mergedConfiguration,
  4. SurfaceControl outSurfaceControl, InsetsState outInsetsState,
  5. InsetsSourceControl[] outActiveControls, Bundle outSyncIdBundle) {
  6. ......
  7. synchronized (mGlobalLock) {
  8. ......
  9. if (focusMayChange) {
  10. if (updateFocusedWindowLocked(UPDATE_FOCUS_NORMAL, true /*updateInputWindows*/)) {
  11. imMayMove = false;
  12. }
  13. }
  14. ......
  15. Binder.restoreCallingIdentity(origId);
  16. //返回result
  17. return result;
  18. }

焦点窗口的更新,通过WMS#updateFocusedWindowLocked()方法开始,下面从这个方法开始,看下整个更新流程。

2.1 WMS#updateFocusedWindowLocked()

代码路径:framework/services/core/java/com/android/server/wm/WindowManagerService.java

  1. boolean updateFocusedWindowLocked(int mode, boolean updateInputWindows) {
  2. Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "wmUpdateFocus");
  3. // 进入RootWindowContainer中
  4. boolean changed = mRoot.updateFocusedWindowLocked(mode, updateInputWindows);
  5. Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
  6. return changed;
  7. }

其中,第一个参数mode表示更新焦点窗口时所处的阶段,共有五个参数:

  1. // 表示正常更新
  2. static final int UPDATE_FOCUS_NORMAL = 0;
  3. // 表示此次更新焦点窗口发生在window layer分配之前
  4. static final int UPDATE_FOCUS_WILL_ASSIGN_LAYERS = 1;
  5. // 表示此次更新焦点窗口发生在进行放置Surface过程中,在performSurfacePlacement()时
  6. static final int UPDATE_FOCUS_PLACING_SURFACES = 2;
  7. // 表示此次更新焦点窗口发生在进行放置Surface之前
  8. static final int UPDATE_FOCUS_WILL_PLACE_SURFACES = 3;
  9. // 表示此次更新焦点窗口发生在焦点窗口移除后
  10. static final int UPDATE_FOCUS_REMOVING_FOCUS = 4;

如在Window添加过程的addWindow()方法中,更新焦点窗口发生在分配窗口layer流程之前,因此使用UPDATE_FOCUS_WILL_ASSIGN_LAYERS作为第一个参数,表示此次更新时,还没有分配layer。 针对不同阶段,会有不同的操作。

第二个参数表示是否同步更新InputWindow,一般在调用的地方会写死

 

2.2 RootWindowContainer#updateFocusedWindowLocked

代码路径:frameworks/base/services/core/java/com/android/server/wm/RootWindowContainer.java

  1. /**
  2. * Updates the children's focused window and the top focused display if needed.
  3. */
  4. boolean updateFocusedWindowLocked(int mode, boolean updateInputWindows) {
  5. // 存储了当前焦点窗口的Pid和ActivityRecord的Map映射
  6. mTopFocusedAppByProcess.clear();
  7. boolean changed = false;
  8. int topFocusedDisplayId = INVALID_DISPLAY;
  9. // Go through the children in z-order starting at the top-most
  10. // 遍历DisplayContent
  11. for (int i = mChildren.size() - 1; i >= 0; --i) {
  12. final DisplayContent dc = mChildren.get(i);
  13. // 针对每个DisplayContent,进行焦点窗口更新
  14. changed |= dc.updateFocusedWindowLocked(mode, updateInputWindows, topFocusedDisplayId);
  15. // 更新全局焦点窗口
  16. final WindowState newFocus = dc.mCurrentFocus;
  17. if (newFocus != null) {
  18. final int pidOfNewFocus = newFocus.mSession.mPid;
  19. if (mTopFocusedAppByProcess.get(pidOfNewFocus) == null) {
  20. mTopFocusedAppByProcess.put(pidOfNewFocus, newFocus.mActivityRecord);
  21. }
  22. if (topFocusedDisplayId == INVALID_DISPLAY) {
  23. topFocusedDisplayId = dc.getDisplayId();
  24. }
  25. } else if (topFocusedDisplayId == INVALID_DISPLAY && dc.mFocusedApp != null) {
  26. // The top-most display that has a focused app should still be the top focused
  27. // display even when the app window is not ready yet (process not attached or
  28. // window not added yet).
  29. topFocusedDisplayId = dc.getDisplayId();
  30. }
  31. }
  32. if (topFocusedDisplayId == INVALID_DISPLAY) {
  33. topFocusedDisplayId = DEFAULT_DISPLAY;
  34. }
  35. // 更新mTopFocusedDisplayId,表示焦点屏幕
  36. if (mTopFocusedDisplayId != topFocusedDisplayId) {
  37. mTopFocusedDisplayId = topFocusedDisplayId;
  38. mWmService.mInputManager.setFocusedDisplay(topFocusedDisplayId);
  39. mWmService.mPolicy.setTopFocusedDisplay(topFocusedDisplayId);
  40. mWmService.mAccessibilityController.setFocusedDisplay(topFocusedDisplayId);
  41. ProtoLog.d(WM_DEBUG_FOCUS_LIGHT, "New topFocusedDisplayId=%d", topFocusedDisplayId);
  42. }
  43. return changed;
  44. }

这里会遍历DisplayContent,并在每个DisplayContent中进行更新,然后将更新的结果返回给DisplayContent#mCurrentFocus变量,该变量表示全局的焦点窗口。同时更新mTopFocusedDisplayId变量,表示当前焦点屏(即焦点窗口所在的屏)。

2.3 DisplayContent#updateFocusedWindowLocked

代码路径:frameworks/base/services/core/java/com/android/server/wm/DisplayContent.java

  1. boolean updateFocusedWindowLocked(int mode, boolean updateInputWindows,
  2. int topFocusedDisplayId) {
  3. // 不要自动将焦点重新分配离开应该保持焦点的应用程序窗口。
  4. // findFocusedWindow` 将始终抓取瞬态启动的应用程序,因为它位于“顶部”
  5. // 会造成不匹配,所以早点出去。
  6. if (mCurrentFocus != null && mTransitionController.shouldKeepFocus(mCurrentFocus)
  7. // 这只是保持焦点,所以如果焦点应用程序已被显式更改(例如通过 setFocusedTask),请不要提前退出。
  8. && mFocusedApp != null && mCurrentFocus.isDescendantOf(mFocusedApp)
  9. && mCurrentFocus.isVisible() && mCurrentFocus.isFocusable()) {
  10. ProtoLog.v(WM_DEBUG_FOCUS, "Current transition prevents automatic focus change");
  11. return false;
  12. }
  13. // 寻找焦点窗口
  14. WindowState newFocus = findFocusedWindowIfNeeded(topFocusedDisplayId);
  15. if (mCurrentFocus == newFocus) {
  16. return false;
  17. }
  18. boolean imWindowChanged = false;
  19. final WindowState imWindow = mInputMethodWindow;
  20. if (imWindow != null) {
  21. // 更新IME target窗口
  22. final WindowState prevTarget = mImeLayeringTarget;
  23. //获取新的IME Target窗口
  24. final WindowState newTarget = computeImeTarget(true /* updateImeTarget*/);
  25. imWindowChanged = prevTarget != newTarget;
  26. if (mode != UPDATE_FOCUS_WILL_ASSIGN_LAYERS
  27. && mode != UPDATE_FOCUS_WILL_PLACE_SURFACES) {
  28. //进行window layer的分配
  29. assignWindowLayers(false /* setLayoutNeeded */);
  30. }
  31. // IME target窗口发生变化,重新获取一次焦点窗口
  32. if (imWindowChanged) {
  33. mWmService.mWindowsChanged = true;
  34. setLayoutNeeded();
  35. newFocus = findFocusedWindowIfNeeded(topFocusedDisplayId);
  36. }
  37. }
  38. ProtoLog.d(WM_DEBUG_FOCUS_LIGHT, "Changing focus from %s to %s displayId=%d Callers=%s",
  39. mCurrentFocus, newFocus, getDisplayId(), Debug.getCallers(4));
  40. //记录旧焦点窗口
  41. final WindowState oldFocus = mCurrentFocus;
  42. // 更新新焦点窗口
  43. mCurrentFocus = newFocus;
  44. if (newFocus != null) {
  45. // 这两个列表用于记录ANR状态,表示自从焦点窗口为空时添加和移除的窗口
  46. mWinAddedSinceNullFocus.clear();
  47. mWinRemovedSinceNullFocus.clear();
  48. if (newFocus.canReceiveKeys()) {
  49. // Displaying a window implicitly causes dispatching to be unpaused.
  50. // This is to protect against bugs if someone pauses dispatching but
  51. // forgets to resume.
  52. // 设置焦点窗口所在mToken.paused属性为false
  53. newFocus.mToken.paused = false;
  54. }
  55. }
  56. getDisplayPolicy().focusChangedLw(oldFocus, newFocus);
  57. mAtmService.mBackNavigationController.onFocusChanged(newFocus);
  58. // IME target窗口发生变化,且旧焦点窗口非输入法窗口时
  59. if (imWindowChanged && oldFocus != mInputMethodWindow) {
  60. // Focus of the input method window changed. Perform layout if needed.
  61. if (mode == UPDATE_FOCUS_PLACING_SURFACES) {
  62. performLayout(true /*initial*/, updateInputWindows);
  63. } else if (mode == UPDATE_FOCUS_WILL_PLACE_SURFACES) {
  64. // Client will do the layout, but we need to assign layers
  65. // for handleNewWindowLocked() below.
  66. assignWindowLayers(false /* setLayoutNeeded */);
  67. }
  68. }
  69. // 向InputMonitor中设置焦点窗口
  70. if (mode != UPDATE_FOCUS_WILL_ASSIGN_LAYERS) {
  71. // If we defer assigning layers, then the caller is responsible for doing this part.
  72. getInputMonitor().setInputFocusLw(newFocus, updateInputWindows);
  73. }
  74. // 为IME窗口进行调整
  75. adjustForImeIfNeeded();
  76. updateKeepClearAreas();
  77. // We may need to schedule some toast windows to be removed. The toasts for an app that
  78. // does not have input focus are removed within a timeout to prevent apps to redress
  79. // other apps' UI.
  80. scheduleToastWindowsTimeoutIfNeededLocked(oldFocus, newFocus);
  81. if (mode == UPDATE_FOCUS_PLACING_SURFACES) {
  82. pendingLayoutChanges |= FINISH_LAYOUT_REDO_ANIM;
  83. }
  84. // Notify the accessibility manager for the change so it has the windows before the newly
  85. // focused one starts firing events.
  86. // TODO(b/151179149) investigate what info accessibility service needs before input can
  87. // dispatch focus to clients.
  88. if (mWmService.mAccessibilityController.hasCallbacks()) {
  89. mWmService.mH.sendMessage(PooledLambda.obtainMessage(
  90. this::updateAccessibilityOnWindowFocusChanged,
  91. mWmService.mAccessibilityController));
  92. }
  93. return true;
  94. }

上述方法中:

  1. 通过findFocusedWindowIfNeeded()方法寻找焦点窗口;

  2. 根据焦点窗口的变化,更新Input Target窗口;

  3. 更新全局焦点窗口对象mCurrentFocus;

  4. 根据更新的不同阶段做不同处理。

  5. 向InputMonitor中设置焦点窗口setInputFocusLw

下面看下如何寻找到焦点窗口。

2.4.DisplayContent#findFocusedWindowIfNeeded()

代码路径:frameworks/base/services/core/java/com/android/server/wm/DisplayContent.java

  1. /**
  2. * Looking for the focused window on this display if the top focused display hasn't been
  3. * found yet (topFocusedDisplayId is INVALID_DISPLAY) or per-display focused was allowed.
  4. *
  5. * @param topFocusedDisplayId Id of the top focused display.
  6. * @return The focused window or null if there isn't any or no need to seek.
  7. */
  8. WindowState findFocusedWindowIfNeeded(int topFocusedDisplayId) {
  9. return (hasOwnFocus() || topFocusedDisplayId == INVALID_DISPLAY)
  10. ? findFocusedWindow() : null;
  11. }

当topFocusedDisplayId为INVALID_DISPLAY时,认为当前焦点display没有焦点窗口,需要寻找重新确认,所以又继续执行findFocusedWindow()方法寻找

代码路径:frameworks/base/services/core/java/com/android/server/wm/DisplayContent.java

  1. /**
  2. * Find the focused window of this DisplayContent. The search takes the state of the display
  3. * content into account
  4. * @return The focused window, null if none was found.
  5. */
  6. WindowState findFocusedWindow() {
  7. mTmpWindow = null;
  8. // 遍历windowstate mFindFocusedWindow会在找到新的焦点窗口时填充 mTmpWindow。
  9. forAllWindows(mFindFocusedWindow, true /* traverseTopToBottom */);
  10. if (mTmpWindow == null) {
  11. ProtoLog.v(WM_DEBUG_FOCUS_LIGHT, "findFocusedWindow: No focusable windows, display=%d",
  12. getDisplayId());
  13. return null;
  14. }
  15. return mTmpWindow;
  16. }

该方法中,会遍历所有WindowState,然后将寻找到的WindowState赋值给mTmpWindow,并返回给WMS。接下来看下这个mFindFocusedWindow函数接口对象

代码路径:frameworks/base/services/core/java/com/android/server/wm/DisplayContent.java

  1. /**
  2. *用于查找给定窗口的聚焦窗口的 lambda 函数。
  3. 如果找到聚焦窗口,则lambda返回true,否则返回 false。
  4. 如果找到焦点窗口,它将被存储在mTmpWindow中。
  5. */
  6. private final ToBooleanFunction<WindowState> mFindFocusedWindow = w -> {
  7. // 当前处于前台的ActivityRecord
  8. final ActivityRecord focusedApp = mFocusedApp;
  9. ProtoLog.v(WM_DEBUG_FOCUS, "Looking for focus: %s, flags=%d, canReceive=%b, reason=%s",
  10. w, w.mAttrs.flags, w.canReceiveKeys(),
  11. w.canReceiveKeysReason(false /* fromUserTouch */));
  12. // 如果窗口无法接收key事件,则不能作为焦点窗口,返回false
  13. if (!w.canReceiveKeys()) {
  14. return false;
  15. }
  16. // When switching the app task, we keep the IME window visibility for better
  17. // transitioning experiences.
  18. // However, in case IME created a child window or the IME selection dialog without
  19. // dismissing during the task switching to keep the window focus because IME window has
  20. // higher window hierarchy, we don't give it focus if the next IME layering target
  21. // doesn't request IME visible.
  22. if (w.mIsImWindow && w.isChildWindow() && (mImeLayeringTarget == null
  23. || !mImeLayeringTarget.isRequestedVisible(ime()))) {
  24. return false;
  25. }
  26. if (w.mAttrs.type == TYPE_INPUT_METHOD_DIALOG && mImeLayeringTarget != null
  27. && !mImeLayeringTarget.isRequestedVisible(ime())
  28. && !mImeLayeringTarget.isVisibleRequested()) {
  29. return false;
  30. }
  31. final ActivityRecord activity = w.mActivityRecord;
  32. // 如果前台没有Activity,则此次WindowState将作为焦点窗口返回
  33. if (focusedApp == null) {
  34. ProtoLog.v(WM_DEBUG_FOCUS_LIGHT,
  35. "findFocusedWindow: focusedApp=null using new focus @ %s", w);
  36. mTmpWindow = w;
  37. return true;
  38. }
  39. // 如果前台Activity是不可获焦的,则此次WindowState将作为焦点窗口返回
  40. if (!focusedApp.windowsAreFocusable()) {
  41. // Current focused app windows aren't focusable...
  42. ProtoLog.v(WM_DEBUG_FOCUS_LIGHT, "findFocusedWindow: focusedApp windows not"
  43. + " focusable using new focus @ %s", w);
  44. mTmpWindow = w;
  45. return true;
  46. }
  47. // Descend through all of the app tokens and find the first that either matches
  48. // win.mActivityRecord (return win) or mFocusedApp (return null).
  49. // 如果当前WindowState由ActivityRecord管理,且非StartingWindow,
  50. //则当前台Activity在当前WindowState所属Activity之上时,不存在焦点窗口
  51. if (activity != null && w.mAttrs.type != TYPE_APPLICATION_STARTING) {
  52. if (focusedApp.compareTo(activity) > 0) {
  53. // App root task below focused app root task. No focus for you!!!
  54. ProtoLog.v(WM_DEBUG_FOCUS_LIGHT,
  55. "findFocusedWindow: Reached focused app=%s", focusedApp);
  56. mTmpWindow = null;
  57. return true;
  58. }
  59. // 如果Activity当前嵌入到焦点任务中,则
  60. // 除非 Activity 与 FocusedApp 位于同一 TaskFragment 上,否则无法获得焦点。
  61. TaskFragment parent = activity.getTaskFragment();
  62. if (parent != null && parent.isEmbedded()) {
  63. if (activity.getTask() == focusedApp.getTask()
  64. && activity.getTaskFragment() != focusedApp.getTaskFragment()) {
  65. return false;
  66. }
  67. }
  68. }
  69. // 不满足以上条件,则此次WindowState将作为焦点窗口返回
  70. ProtoLog.v(WM_DEBUG_FOCUS_LIGHT, "findFocusedWindow: Found new focus @ %s", w);
  71. mTmpWindow = w;
  72. return true;
  73. };
  1. 如果WindowState不能接收Input事件,则不能作为焦点窗口;

  2. 如果没有前台Activity,则当前WindowState作为焦点窗口返回;

  3. 如果前台Activity是不可获焦状态,则当前WindowState作为焦点窗口返回;

  4. 如果当前WindowState由ActivityRecord管理,且该WindowState不是Staring Window类型,那么当前台Activity在当前WindowState所属Activity之上时,不存在焦点窗口;

  5. 如果Activity当前嵌入到焦点任务中,则除非 Activity与FocusedApp位于同一TaskFragment上,否则无法获得焦点。

  6. 如果以上条件都不满足,则当前WindowState作为焦点窗口返回;

接下来看一下canReceiveKeys这个函数

代码路径:frameworks/base/services/core/java/com/android/server/wm/WindowState.java

  1. public boolean canReceiveKeys(boolean fromUserTouch) {
  2. if (mActivityRecord != null && mTransitionController.shouldKeepFocus(mActivityRecord)) {
  3. // 在瞬态启动期间,瞬态隐藏窗口不可见
  4. // 或在顶部,但保持可聚焦,因此可以接收密钥。
  5. return true;
  6. }
  7. // 可见或处于addWindow()~relayout之间
  8. final boolean canReceiveKeys = isVisibleRequestedOrAdding()
  9. // 客户端View可见 // 退出动画执行完毕
  10. && (mViewVisibility == View.VISIBLE) && !mRemoveOnExit
  11. // 没有FLAG_NOT_FOCUSABLE标记
  12. && ((mAttrs.flags & WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) == 0)
  13. // mActivityRecord为null或者其可获焦
  14. && (mActivityRecord == null || mActivityRecord.windowsAreFocusable(fromUserTouch))
  15. // 可以接受touch事件
  16. && (mActivityRecord == null || mActivityRecord.getTask() == null
  17. || !mActivityRecord.getTask().getRootTask().shouldIgnoreInput());
  18. if (!canReceiveKeys) {
  19. return false;
  20. }
  21. // 除非用户故意触摸显示器,否则不允许不受信任的虚拟显示器接收密钥。
  22. return fromUserTouch || getDisplayContent().isOnTop()
  23. || getDisplayContent().isTrusted();
  24. }

如果一个WindowState可以接受Input事件,需要同时满足多个条件:

  1. isVisibleRequestedOrAdding()方法为true,表示该WindowState可见或处于添加过程中:

  2. mViewVisibility属性为View.VISIBLE,表示客户端View可见;

  3. mRemoveOnExit为false,表示WindowState的退出动画不存在;

  4. mAttrs.flags中不存在FLAG_NOT_FOCUSABLE标记,该标记如果设置,表示该窗口为不可获焦窗口;

  5. mActivityRecord为null或者mActivityRecord可获焦;

  6. shouldIgnoreInput()方法为false,表示可以接受Touch事件。

isVisibleRequestedOrAdding()方法用来判断该WindowState可见或处于添加过程中:

代码路径:frameworks/base/services/core/java/com/android/server/wm/WindowState.java

  1. /**
  2. * Is this window capable of being visible (policy and content), in a visible part of the
  3. * hierarchy, and, if an activity window, the activity is visible-requested. Note, this means
  4. * if the activity is going-away, this will be {@code false} even when the window is visible.
  5. *
  6. * The 'adding' part refers to the period of time between IWindowSession.add() and the first
  7. * relayout() -- which, for activities, is the same as visibleRequested.
  8. *
  9. * TODO(b/206005136): This is very similar to isVisibleRequested(). Investigate merging them.
  10. */
  11. boolean isVisibleRequestedOrAdding() {
  12. final ActivityRecord atoken = mActivityRecord;
  13. // Surface已经创建,说明relayout()已经执行
  14. return (mHasSurface
  15. // relayout()未执行,且客户端View可见状态
  16. || (!mRelayoutCalled && mViewVisibility == View.VISIBLE))
  17. // 如果是子窗口,其副窗口的mHidden属性为false
  18. && isVisibleByPolicy() && !isParentWindowHidden()
  19. // mActivityRecord为null,或者其mVisibleRequested为true
  20. && (atoken == null || atoken.isVisibleRequested())
  21. // 没有执行退出动画 //且Surface没有进行销毁
  22. && !mAnimatingExit && !mDestroying;
  23. }

如果以上条件都满足,则返回true。

shouldIgnoreInput() 方法用来判断该WindowState是否能够接收touch事件

  1. boolean shouldIgnoreInput() {
  2. //是否支持靠背功能 是否是固定窗口下 且不是Display上的焦点根任务
  3. if (mAtmService.mHasLeanbackFeature && inPinnedWindowingMode()
  4. && !isFocusedRootTaskOnDisplay()) {
  5. // 防止画中画根任务接收电视上的输入
  6. return true;
  7. }
  8. return false;
  9. }

如果遇到找不到焦点窗口的情况:比如log发现窗口已经是onresume的状态,但是焦点窗口一直未请求切换到此窗口可以查看如下这条log,主要是打印canReceiveKeys为何false的原因(那个属性不对)canReceiveKeysReason此方法

  1. private final ToBooleanFunction<WindowState> mFindFocusedWindow = w -> {
  2. final ActivityRecord focusedApp = mFocusedApp;
  3. ProtoLog.v(WM_DEBUG_FOCUS, "Looking for focus: %s, flags=%d, canReceive=%b, reason=%s",
  4. w, w.mAttrs.flags, w.canReceiveKeys(),
  5. w.canReceiveKeysReason(false /* fromUserTouch */));
  6. if (!w.canReceiveKeys()) {
  7. return false;
  8. ......
  9. }
  10. }

代码路径:frameworks/base/services/core/java/com/android/server/wm/WindowState.java

  1. /** Returns {@code true} if this window desires key events. */
  2. boolean canReceiveKeys() {
  3. return canReceiveKeys(false /* fromUserTouch */);
  4. }
  5. public String canReceiveKeysReason(boolean fromUserTouch) {
  6. return "fromTouch= " + fromUserTouch
  7. + " isVisibleRequestedOrAdding=" + isVisibleRequestedOrAdding()
  8. + " mViewVisibility=" + mViewVisibility
  9. + " mRemoveOnExit=" + mRemoveOnExit
  10. + " flags=" + mAttrs.flags
  11. + " appWindowsAreFocusable="
  12. + (mActivityRecord == null || mActivityRecord.windowsAreFocusable(fromUserTouch))
  13. + " canReceiveTouchInput=" + canReceiveTouchInput()
  14. + " displayIsOnTop=" + getDisplayContent().isOnTop()
  15. + " displayIsTrusted=" + getDisplayContent().isTrusted()
  16. + " transitShouldKeepFocus=" + (mActivityRecord != null
  17. && mTransitionController.shouldKeepFocus(mActivityRecord));
  18. }

然后我们回到mFindFocusedWindow接口对象中,其他条件就不一一说明,最终从DisplayContent中自顶向下寻找到的第一个满足条件的窗口,将作为新的焦点窗口后,接下来更新Display#mCurrentFocus变量,表示当前焦点窗口。

三、InputWindows的更新

找到焦点窗口后,回到DisplayContent的updateFocusedWindowLocked方法中继续往下走 执行到此处会进行InputWindows的更新

代码路径:frameworks/base/services/core/java/com/android/server/wm/DisplayContent.java

  1. boolean updateFocusedWindowLocked(int mode, boolean updateInputWindows,
  2. int topFocusedDisplayId) {
  3. //..........详细看上面....
  4. // 向InputMonitor中设置焦点窗口
  5. if (mode != UPDATE_FOCUS_WILL_ASSIGN_LAYERS) {
  6. // If we defer assigning layers, then the caller is responsible for doing this part.
  7. getInputMonitor().setInputFocusLw(newFocus, updateInputWindows);
  8. }
  9. //.........
  10. }

 

3.1 InputMonitor#updateInputWindowsLw()

代码路径:frameworks/base/services/core/java/com/android/server/wm/InputMonitor.java

  1. void setInputFocusLw(WindowState newWindow, boolean updateInputWindows) {
  2. ProtoLog.v(WM_DEBUG_FOCUS_LIGHT, "Input focus has changed to %s display=%d",
  3. newWindow, mDisplayId);
  4. //这里log打印要切到那个窗口
  5. // 更新当前焦点窗口
  6. final IBinder focus = newWindow != null ? newWindow.mInputChannelToken : null;
  7. if (focus == mInputFocus) {
  8. return;
  9. }
  10. if (newWindow != null && newWindow.canReceiveKeys()) {
  11. // Displaying a window implicitly causes dispatching to be unpaused.
  12. // This is to protect against bugs if someone pauses dispatching but
  13. // forgets to resume.
  14. newWindow.mToken.paused = false;
  15. }
  16. // 更新当前焦点窗口 使mUpdateInputWindowsNeeded设置为true
  17. setUpdateInputWindowsNeededLw();
  18. // 更新所有inputwindow
  19. if (updateInputWindows) {
  20. updateInputWindowsLw(false /*force*/);
  21. }
  22. }

以上过程伴随日志:

WindowManager: Input focus has changed to Window{a44139a u0 NotificationShade} display=0

  1. void setUpdateInputWindowsNeededLw() {
  2. mUpdateInputWindowsNeeded = true;
  3. }

3.2.InputMonitor#updateInputWindowsLw()

代码路径:frameworks/base/services/core/java/com/android/server/wm/InputMonitor.java

  1. /* Updates the cached window information provided to the input dispatcher. */
  2. void updateInputWindowsLw(boolean force) {
  3. if (!force && !mUpdateInputWindowsNeeded) {
  4. return;
  5. }
  6. scheduleUpdateInputWindows();
  7. }

在该方法中,只有当强制更新或者mUpdateInputWindowsNeeded值为true时(在setUpdateInputWindowsNeededLw设置为true),才会进行InputWindows的更新

之后将执行scheduleUpdateInputWindows()方法,在这个方法中,会post一个Runnable对象mUpdateInputWindows,在mHandler所在的android.anim线程中执行更新流程:

代码路径:frameworks/base/services/core/java/com/android/server/wm/InputMonitor.java

  1. private void scheduleUpdateInputWindows() {
  2. //检查窗口是否被移除
  3. if (mDisplayRemoved) {
  4. return;
  5. }
  6. //mUpdateInputWindowsPending只是用来保证post执行不被重复执行,配合锁实现
  7. if (!mUpdateInputWindowsPending) {
  8. mUpdateInputWindowsPending = true;
  9. mHandler.post(mUpdateInputWindows);
  10. }
  11. }

代码路径:frameworks/base/services/core/java/com/android/server/wm/InputMonitor.java

  1. private class UpdateInputWindows implements Runnable {
  2. @Override
  3. public void run() {
  4. synchronized (mService.mGlobalLock) {
  5. // 重置变量
  6. //将mUpdateInputWindowsPending 设置为false,准备执行下一次同步
  7. mUpdateInputWindowsPending = false;
  8. mUpdateInputWindowsNeeded = false;
  9. //没有display的话return
  10. if (mDisplayRemoved) {
  11. return;
  12. }
  13. // Populate the input window list with information about all of the windows that
  14. // could potentially receive input.
  15. // As an optimization, we could try to prune the list of windows but this turns
  16. // out to be difficult because only the native code knows for sure which window
  17. // currently has touch focus.
  18. // If there's a drag in flight, provide a pseudo-window to catch drag input
  19. // 是否正在拖拽
  20. final boolean inDrag = mService.mDragDropController.dragDropActiveLocked();
  21. // 在默认显示上添加所有窗口。
  22. mUpdateInputForAllWindowsConsumer.updateInputWindows(inDrag);
  23. }
  24. }
  25. }
  26. private final UpdateInputWindows mUpdateInputWindows = new UpdateInputWindows();

接下来执行mUpdateInputForAllWindowsConsumer.updateInputWindows()方法。

3.3.mUpdateInputForAllWindowsConsumer.updateInputWindows()

在该方法中,首先会确认是否存在几类特殊的InputConsumer。InputConsumer用于读取事件,每个窗口对应的客户端都会通过InputConsumer来读取和消费事件,一般情况下,ViewRootImpl在添加窗口过程中,会在注册InputEventReceiver时自动创建InputConsumer对象。此处的特殊InputConsumer则是对一些系统UI显式地进行了创建:

代码路径:frameworks/base/services/core/java/com/android/server/wm/InputMonitor.java

  1. private void updateInputWindows(boolean inDrag) {
  2. Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "updateInputWindows");
  3. // 显式创建的特殊InputConsumer对象
  4. // 用于处理Nav相关input事件
  5. mPipInputConsumer = getInputConsumer(INPUT_CONSUMER_PIP);
  6. // 用于处理壁纸相关input事件
  7. mWallpaperInputConsumer = getInputConsumer(INPUT_CONSUMER_WALLPAPER);
  8. // 用于处理最近的动画输入相关input事件
  9. mRecentsAnimationInputConsumer = getInputConsumer(INPUT_CONSUMER_RECENTS_ANIMATION);
  10. mAddPipInputConsumerHandle = mPipInputConsumer != null;
  11. mAddWallpaperInputConsumerHandle = mWallpaperInputConsumer != null;
  12. mAddRecentsAnimationInputConsumerHandle = mRecentsAnimationInputConsumer != null;
  13. // 重置mInputTransaction
  14. resetInputConsumers(mInputTransaction);
  15. // 如果处于活动状态,则更新最近的输入消费者层
  16. final ActivityRecord activeRecents = getWeak(mActiveRecentsActivity);
  17. if (mAddRecentsAnimationInputConsumerHandle && activeRecents != null
  18. && activeRecents.getSurfaceControl() != null
  19. WindowContainer layer = getWeak(mActiveRecentsLayerRef);
  20. layer = layer != null ? layer : activeRecents;
  21. // Handle edge-case for SUW where windows don't exist yet
  22. if (layer.getSurfaceControl() != null) {
  23. final WindowState targetAppMainWindow = activeRecents.findMainWindow();
  24. if (targetAppMainWindow != null) {
  25. targetAppMainWindow.getBounds(mTmpRect);
  26. mRecentsAnimationInputConsumer.mWindowHandle.touchableRegion.set(mTmpRect);
  27. }
  28. mRecentsAnimationInputConsumer.show(mInputTransaction, layer);
  29. mAddRecentsAnimationInputConsumerHandle = false;
  30. }
  31. }
  32. // 遍历窗口更新inputInfo
  33. mDisplayContent.forAllWindows(this, true /* traverseTopToBottom */);
  34. //调用到Focus Request
  35. updateInputFocusRequest(mRecentsAnimationInputConsumer);
  36. // 将mInputTransaction合并到mPendingTransaction上进行提交
  37. if (!mUpdateInputWindowsImmediately) {
  38. mDisplayContent.getPendingTransaction().merge(mInputTransaction);
  39. mDisplayContent.scheduleAnimation();
  40. }
  41. Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
  42. }

然后,接mDisplayContent.forAllWindows 将发起所有WindowState的遍历,mUpdateInputForAllWindowsConsumer本身是一个Consumer接口对象,因此会回调accept()方法对每个WindowState进行处理:

代码路径:frameworks/base/services/core/java/com/android/server/wm/WindowContainer.java

  1. boolean forAllWindows(ToBooleanFunction<WindowState> callback, boolean traverseTopToBottom) {
  2. if (traverseTopToBottom) {
  3. for (int i = mChildren.size() - 1; i >= 0; --i) {
  4. if (mChildren.get(i).forAllWindows(callback, traverseTopToBottom)) {
  5. return true;
  6. }
  7. }
  8. } else {
  9. final int count = mChildren.size();
  10. for (int i = 0; i < count; i++) {
  11. if (mChildren.get(i).forAllWindows(callback, traverseTopToBottom)) {
  12. return true;
  13. }
  14. }
  15. }
  16. return false;
  17. }

代码路径:frameworks/base/services/core/java/com/android/server/wm/WindowState.java

  1. private boolean applyInOrderWithImeWindows(ToBooleanFunction<WindowState> callback,
  2. boolean traverseTopToBottom) {
  3. if (traverseTopToBottom) {
  4. if (applyImeWindowsIfNeeded(callback, traverseTopToBottom)
  5. || callback.apply(this)) {
  6. return true;
  7. }
  8. } else {
  9. if (callback.apply(this)
  10. || applyImeWindowsIfNeeded(callback, traverseTopToBottom)) {
  11. return true;
  12. }
  13. }
  14. return false;
  15. }

代码路径:frameworks/base/services/core/java/com/android/server/wm/WindowContainer.java

  1. @Override
  2. public boolean apply(WindowState w) {
  3. mConsumer.accept(w);
  4. return false;
  5. }

代码路径:frameworks/base/services/core/java/com/android/server/wm/InputMonitor.java

  1. @Override
  2. public void accept(WindowState w) {
  3. // 获取WindowState的InputWindowHandle对象
  4. //WindowState里保存着InputWindowHandle,每次复用,判断changes,减少同步
  5. final InputWindowHandleWrapper inputWindowHandle = w.mInputWindowHandle;
  6. //判断窗口mInputChannelToken是否为空;窗口是否销毁;窗口是否可以接受input事件
  7. if (w.mInputChannelToken == null || w.mRemoved || !w.canReceiveTouchInput()) {
  8. if (w.mWinAnimator.hasSurface()) {
  9. // 确保输入信息无法接收输入事件。可以省略
  10. // 遮挡检测取决于类型或是否是可信覆盖。
  11. populateOverlayInputInfo(inputWindowHandle, w);
  12. setInputWindowInfoIfNeeded(mInputTransaction,
  13. w.mWinAnimator.mSurfaceController.mSurfaceControl, inputWindowHandle);
  14. return;
  15. }
  16. // 跳过此窗口,因为它不可能接收输入。
  17. return;
  18. }
  19. // 最近任务是否存在
  20. final RecentsAnimationController recentsAnimationController =
  21. mService.getRecentsAnimationController();
  22. final boolean shouldApplyRecentsInputConsumer = recentsAnimationController != null
  23. && recentsAnimationController.shouldApplyInputConsumer(w.mActivityRecord);
  24. if (mAddRecentsAnimationInputConsumerHandle && shouldApplyRecentsInputConsumer) {
  25. if (recentsAnimationController.updateInputConsumerForApp(
  26. mRecentsAnimationInputConsumer.mWindowHandle)) {
  27. final DisplayArea targetDA =
  28. recentsAnimationController.getTargetAppDisplayArea();
  29. if (targetDA != null) {
  30. mRecentsAnimationInputConsumer.reparent(mInputTransaction, targetDA);
  31. mRecentsAnimationInputConsumer.show(mInputTransaction, MAX_VALUE - 2);
  32. mAddRecentsAnimationInputConsumerHandle = false;
  33. }
  34. }
  35. }
  36. // 处理处于PIP模式时的input事件
  37. if (w.inPinnedWindowingMode()) {
  38. if (mAddPipInputConsumerHandle) {
  39. final Task rootTask = w.getTask().getRootTask();
  40. mPipInputConsumer.mWindowHandle.replaceTouchableRegionWithCrop(
  41. rootTask.getSurfaceControl());
  42. final DisplayArea targetDA = rootTask.getDisplayArea();
  43. // We set the layer to z=MAX-1 so that it's always on top.
  44. if (targetDA != null) {
  45. mPipInputConsumer.layout(mInputTransaction, rootTask.getBounds());
  46. mPipInputConsumer.reparent(mInputTransaction, targetDA);
  47. mPipInputConsumer.show(mInputTransaction, MAX_VALUE - 1);
  48. mAddPipInputConsumerHandle = false;
  49. }
  50. }
  51. }
  52. // mWallpaperInputConsumer处理壁纸input事件
  53. if (mAddWallpaperInputConsumerHandle) {
  54. if (w.mAttrs.type == TYPE_WALLPAPER && w.isVisible()) {
  55. mWallpaperInputConsumer.mWindowHandle
  56. .replaceTouchableRegionWithCrop(null /* use this surface's bounds */);
  57. // Add the wallpaper input consumer above the first visible wallpaper.
  58. mWallpaperInputConsumer.show(mInputTransaction, w);
  59. mAddWallpaperInputConsumerHandle = false;
  60. }
  61. }
  62. // 是否处于拖拽过程中
  63. if (mInDrag && w.isVisible() && w.getDisplayContent().isDefaultDisplay) {
  64. mService.mDragDropController.sendDragStartedIfNeededLocked(w);
  65. }
  66. // 注册密钥拦截信息
  67. mService.mKeyInterceptionInfoForToken.put(w.mInputChannelToken,
  68. w.getKeyInterceptionInfo());
  69. if (w.mWinAnimator.hasSurface()) {
  70. // 填充InputWindowHandle
  71. populateInputWindowHandle(inputWindowHandle, w);
  72. //提交inputWindowHandle
  73. setInputWindowInfoIfNeeded(mInputTransaction,
  74. w.mWinAnimator.mSurfaceController.mSurfaceControl, inputWindowHandle);
  75. }
  76. }

以上方法中:

  1. 首先会对几类特殊InputConsumer进行单独处理;

  2. 然后填充InputWindowHandle对象(populateInputWindowHandle);

  3. 最后将InputWindowHandle对象设置给Transaction对象(setInputWindowInfoIfNeeded),并在事物提交后,由SurfaceFlinger设置给InputDispatcher中。

3.4.InputMonitor#populateInputWindowHandle()

在该方法中,会将WindowState的部分属性填充给inputWindowHandle:

代码路径:frameworks/base/services/core/java/com/android/server/wm/InputMonitor.java

  1. @VisibleForTesting
  2. void populateInputWindowHandle(final InputWindowHandleWrapper inputWindowHandle,
  3. final WindowState w) {
  4. // Add a window to our list of input windows.
  5. inputWindowHandle.setInputApplicationHandle(w.mActivityRecord != null
  6. ? w.mActivityRecord.getInputApplicationHandle(false /* update */) : null);
  7. inputWindowHandle.setToken(w.mInputChannelToken);
  8. inputWindowHandle.setDispatchingTimeoutMillis(w.getInputDispatchingTimeoutMillis());
  9. inputWindowHandle.setTouchOcclusionMode(w.getTouchOcclusionMode());
  10. inputWindowHandle.setPaused(w.mActivityRecord != null && w.mActivityRecord.paused);
  11. inputWindowHandle.setWindowToken(w.mClient);
  12. inputWindowHandle.setName(w.getName());
  13. // Update layout params flags to force the window to be not touch modal. We do this to
  14. // restrict the window's touchable region to the task even if it requests touches outside
  15. // its window bounds. An example is a dialog in primary split should get touches outside its
  16. // window within the primary task but should not get any touches going to the secondary
  17. // task.
  18. int flags = w.mAttrs.flags;
  19. if (w.mAttrs.isModal()) {
  20. flags = flags | FLAG_NOT_TOUCH_MODAL;
  21. }
  22. inputWindowHandle.setLayoutParamsFlags(flags);
  23. inputWindowHandle.setInputConfigMasked(
  24. InputConfigAdapter.getInputConfigFromWindowParams(
  25. w.mAttrs.type, flags, w.mAttrs.inputFeatures),
  26. InputConfigAdapter.getMask());
  27. final boolean focusable = w.canReceiveKeys()
  28. && (mDisplayContent.hasOwnFocus() || mDisplayContent.isOnTop());
  29. inputWindowHandle.setFocusable(focusable);
  30. final boolean hasWallpaper = mDisplayContent.mWallpaperController.isWallpaperTarget(w)
  31. && !mService.mPolicy.isKeyguardShowing()
  32. && w.mAttrs.areWallpaperTouchEventsEnabled();
  33. inputWindowHandle.setHasWallpaper(hasWallpaper);
  34. // Surface insets are hardcoded to be the same in all directions
  35. // and we could probably deprecate the "left/right/top/bottom" concept.
  36. // we avoid reintroducing this concept by just choosing one of them here.
  37. inputWindowHandle.setSurfaceInset(w.mAttrs.surfaceInsets.left);
  38. inputWindowHandle.setScaleFactor(w.mGlobalScale != 1f ? (1f / w.mGlobalScale) : 1f);
  39. boolean useSurfaceBoundsAsTouchRegion = false;
  40. SurfaceControl touchableRegionCrop = null;
  41. final Task task = w.getTask();
  42. if (task != null) {
  43. if (task.isOrganized() && task.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
  44. // If the window is in a TaskManaged by a TaskOrganizer then most cropping will
  45. // be applied using the SurfaceControl hierarchy from the Organizer. This means
  46. // we need to make sure that these changes in crop are reflected in the input
  47. // windows, and so ensure this flag is set so that the input crop always reflects
  48. // the surface hierarchy. However, we only want to set this when the client did
  49. // not already provide a touchable region, so that we don't ignore the one provided.
  50. if (w.mTouchableInsets != TOUCHABLE_INSETS_REGION) {
  51. useSurfaceBoundsAsTouchRegion = true;
  52. }
  53. if (w.mAttrs.isModal()) {
  54. TaskFragment parent = w.getTaskFragment();
  55. touchableRegionCrop = parent != null ? parent.getSurfaceControl() : null;
  56. }
  57. } else if (task.cropWindowsToRootTaskBounds() && !w.inFreeformWindowingMode()) {
  58. touchableRegionCrop = task.getRootTask().getSurfaceControl();
  59. }
  60. }
  61. inputWindowHandle.setReplaceTouchableRegionWithCrop(useSurfaceBoundsAsTouchRegion);
  62. inputWindowHandle.setTouchableRegionCrop(touchableRegionCrop);
  63. if (!useSurfaceBoundsAsTouchRegion) {
  64. w.getSurfaceTouchableRegion(mTmpRegion, w.mAttrs);
  65. inputWindowHandle.setTouchableRegion(mTmpRegion);
  66. }
  67. }

填充完毕InputWindowHandle后,调用setInputWindowInfoIfNeeded()方法

下面简单看一下InputWindowHandleWrapper这个类

代码路径:frameworks/base/services/core/java/com/android/server/wm/InputWindowHandleWrapper.java

  1. //InputWindowHandle的包装类
  2. class InputWindowHandleWrapper {
  3. //所有的信息都设置到 mHandle 变量中
  4. private final @NonNull InputWindowHandle mHandle;
  5. boolean isChanged() {
  6. return mChanged;
  7. }
  8. //......
  9. void setTouchableRegion(Region region) {
  10. if (mHandle.touchableRegion.equals(region)) {
  11. return;
  12. }
  13. mHandle.touchableRegion.set(region);
  14. mChanged = true;
  15. }
  16. void applyChangesToSurface(@NonNull SurfaceControl.Transaction t, @NonNull SurfaceControl sc) {
  17. t.setInputWindowInfo(sc, mHandle);
  18. mChanged = false;
  19. }
  20. //......
  21. }

代码路径:frameworks/base/core/java/android/view/InputWindowHandle.java

  1. public final class InputWindowHandle {
  2. @Retention(RetentionPolicy.SOURCE)
  3. @IntDef(flag = true, value = {
  4. InputConfig.DEFAULT,
  5. InputConfig.NO_INPUT_CHANNEL,
  6. InputConfig.NOT_FOCUSABLE,
  7. InputConfig.NOT_TOUCHABLE,
  8. InputConfig.PREVENT_SPLITTING,
  9. InputConfig.DUPLICATE_TOUCH_TO_WALLPAPER,
  10. InputConfig.IS_WALLPAPER,
  11. InputConfig.PAUSE_DISPATCHING,
  12. InputConfig.TRUSTED_OVERLAY,
  13. InputConfig.WATCH_OUTSIDE_TOUCH,
  14. InputConfig.SLIPPERY,
  15. InputConfig.DISABLE_USER_ACTIVITY,
  16. InputConfig.SPY,
  17. InputConfig.INTERCEPTS_STYLUS,
  18. })
  19. public InputApplicationHandle inputApplicationHandle;
  20. // The window name.
  21. public String name;
  22. public long dispatchingTimeoutMillis;
  23. public int frameLeft;
  24. public int frameTop;
  25. public int frameRight;
  26. public int frameBottom;
  27. // Window touchable region.
  28. public final Region touchableRegion = new Region();
  29. public int touchOcclusionMode = TouchOcclusionMode.BLOCK_UNTRUSTED;
  30. }

3.5.InputMonitor#setInputWindowInfoIfNeeded()

回到updateInputWindows()方法的,调用setInputWindowInfoIfNeeded将填充好的InputWindowHandle最终通过通过SurfaceFlinger设置给了InputDispatcher

代码路径:frameworks/base/services/core/java/com/android/server/wm/InputMonitor.java

  1. @VisibleForTesting
  2. static void setInputWindowInfoIfNeeded(SurfaceControl.Transaction t, SurfaceControl sc,
  3. InputWindowHandleWrapper inputWindowHandle) {
  4. if (DEBUG_INPUT) {
  5. Slog.d(TAG_WM, "Update InputWindowHandle: " + inputWindowHandle);
  6. }
  7. if (inputWindowHandle.isChanged()) {
  8. inputWindowHandle.applyChangesToSurface(t, sc);
  9. }
  10. }

代码路径:frameworks/base/services/core/java/com/android/server/wm/InputWindowHandleWrapper.java

  1. void applyChangesToSurface(@NonNull SurfaceControl.Transaction t, @NonNull SurfaceControl sc) {
  2. t.setInputWindowInfo(sc, mHandle);
  3. mChanged = false;
  4. }

代码路径:frameworks/base/core/java/android/view/SurfaceControl.java

  1. /**
  2. * @hide
  3. */
  4. public Transaction setInputWindowInfo(SurfaceControl sc, InputWindowHandle handle) {
  5. //检查条件
  6. checkPreconditions(sc);
  7. nativeSetInputWindowInfo(mNativeObject, sc.mNativeObject, handle);
  8. return this;
  9. }

代码路径:frameworks/base/core/jni/android_view_SurfaceControl.cpp

  1. static void nativeSetInputWindowInfo(JNIEnv* env, jclass clazz, jlong transactionObj,
  2. jlong nativeObject, jobject inputWindow) {
  3. auto transaction = reinterpret_cast<SurfaceComposerClient::Transaction*>(transactionObj);
  4. sp<NativeInputWindowHandle> handle = android_view_InputWindowHandle_getHandle(
  5. env, inputWindow);
  6. handle->updateInfo();
  7. auto ctrl = reinterpret_cast<SurfaceControl *>(nativeObject);
  8. transaction->setInputWindowInfo(ctrl, *handle->getInfo());
  9. }

代码路径:frameworks/native/libs/gui/SurfaceComposerClient.cpp

// native层也有对应的surfacecontrol,刚刚封装的WindowInfo也被传递进来

  1. SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setInputWindowInfo(
  2. const sp<SurfaceControl>& sc, const WindowInfo& info) {
  3. //获取surfaceControl对应的layer_state_t(surfaceflinger的一个图层)
  4. layer_state_t* s = getLayerState(sc);
  5. if (!s) {
  6. mStatus = BAD_INDEX;
  7. return *this;
  8. }
  9. // 把对应的WindowInfo数据设置相应的参数给layer_state_t,就是surface里面的layer
  10. s->windowInfoHandle = new WindowInfoHandle(info);
  11. //在SurfaceFlinger会按照flag来解析改变数据
  12. s->what |= layer_state_t::eInputInfoChanged;
  13. return *this;
  14. }

代码路径:frameworks/native/libs/gui/SurfaceComposerClient.cpp

  1. layer_state_t* SurfaceComposerClient::Transaction::getLayerState(const sp<SurfaceControl>& sc) {
  2. auto handle = sc->getLayerStateHandle();
  3. if (mComposerStates.count(handle) == 0) {
  4. // we don't have it, add an initialized layer_state to our list
  5. ComposerState s;
  6. s.state.surface = handle;
  7. s.state.layerId = sc->getLayerId();
  8. //用于执行apply时,把所有的layer操作一起同步到底层SurfaceFlinger
  9. mComposerStates[handle] = s;
  10. }
  11. return &(mComposerStates[handle].state);
  12. }

后续统一apply(); BpBn调setClientStateLocked()时eInputInfoChanged更新inputInfo;

3.6 InputMonitor#updateInputFocusRequest

再回到InputMonitor#updateInputWindows中

代码路径:frameworks/base/services/core/java/com/android/server/wm/InputMonitor.java

  1. private void updateInputWindows(boolean inDrag) {
  2. Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "updateInputWindows");
  3. // 显式创建的特殊InputConsumer对象
  4. // 用于处理Nav相关input事件
  5. mPipInputConsumer = getInputConsumer(INPUT_CONSUMER_PIP);
  6. // 用于处理壁纸相关input事件
  7. mWallpaperInputConsumer = getInputConsumer(INPUT_CONSUMER_WALLPAPER);
  8. // 用于处理最近的动画输入相关input事件
  9. mRecentsAnimationInputConsumer = getInputConsumer(INPUT_CONSUMER_RECENTS_ANIMATION);
  10. mAddPipInputConsumerHandle = mPipInputConsumer != null;
  11. mAddWallpaperInputConsumerHandle = mWallpaperInputConsumer != null;
  12. mAddRecentsAnimationInputConsumerHandle = mRecentsAnimationInputConsumer != null;
  13. // 重置mInputTransaction
  14. resetInputConsumers(mInputTransaction);
  15. // 如果处于活动状态,则更新最近的输入消费者层
  16. final ActivityRecord activeRecents = getWeak(mActiveRecentsActivity);
  17. if (mAddRecentsAnimationInputConsumerHandle && activeRecents != null
  18. && activeRecents.getSurfaceControl() != null
  19. WindowContainer layer = getWeak(mActiveRecentsLayerRef);
  20. layer = layer != null ? layer : activeRecents;
  21. // Handle edge-case for SUW where windows don't exist yet
  22. if (layer.getSurfaceControl() != null) {
  23. final WindowState targetAppMainWindow = activeRecents.findMainWindow();
  24. if (targetAppMainWindow != null) {
  25. targetAppMainWindow.getBounds(mTmpRect);
  26. mRecentsAnimationInputConsumer.mWindowHandle.touchableRegion.set(mTmpRect);
  27. }
  28. mRecentsAnimationInputConsumer.show(mInputTransaction, layer);
  29. mAddRecentsAnimationInputConsumerHandle = false;
  30. }
  31. }
  32. // 遍历窗口更新inputInfo
  33. mDisplayContent.forAllWindows(this, true /* traverseTopToBottom */);
  34. //调用到Focus Request
  35. updateInputFocusRequest(mRecentsAnimationInputConsumer);
  36. // 将mInputTransaction合并到mPendingTransaction上进行提交
  37. if (!mUpdateInputWindowsImmediately) {
  38. mDisplayContent.getPendingTransaction().merge(mInputTransaction);
  39. mDisplayContent.scheduleAnimation();
  40. }
  41. Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
  42. }

接下先来看一下updateInputFocusRequest是如何打印“Focus request ”这条log的

代码路径:frameworks/base/services/core/java/com/android/server/wm/InputMonitor.java

  1. /**
  2. * Called when the current input focus changes.
  3. */
  4. private void updateInputFocusRequest(InputConsumerImpl recentsAnimationInputConsumer) {
  5. final WindowState focus = mDisplayContent.mCurrentFocus;
  6. //......
  7. final IBinder focusToken = focus != null ? focus.mInputChannelToken : null;
  8. if (focusToken == null) {
  9. if (recentsAnimationInputConsumer != null
  10. && recentsAnimationInputConsumer.mWindowHandle != null
  11. && mInputFocus == recentsAnimationInputConsumer.mWindowHandle.token) {
  12. // Avoid removing input focus from recentsAnimationInputConsumer.
  13. // When the recents animation input consumer has the input focus,
  14. // mInputFocus does not match to mDisplayContent.mCurrentFocus. Making it to be
  15. // a special case, that do not remove the input focus from it when
  16. // mDisplayContent.mCurrentFocus is null. This special case should be removed
  17. // once recentAnimationInputConsumer is removed.
  18. return;
  19. }
  20. // 当应用程序获得焦点但其窗口尚未显示时,请从当前窗口中删除输入焦点
  21. // 这强制输入焦点匹配 mDisplayContent.mCurrentFocus
  22. // 但是,如果发现更多特殊情况,即输入焦点和 mDisplayContent.mCurrentFocus 预计不匹配,
  23. //则需要检查如何以及何时撤销焦点的整个逻辑。
  24. if (mDisplayContent.mFocusedApp != null && mInputFocus != null) {
  25. ProtoLog.v(WM_DEBUG_FOCUS_LIGHT, "App %s is focused,"
  26. + " but the window is not ready. Start a transaction to remove focus from"
  27. + " the window of non-focused apps.",
  28. mDisplayContent.mFocusedApp.getName());
  29. EventLog.writeEvent(LOGTAG_INPUT_FOCUS, "Requesting to set focus to null window",
  30. "reason=UpdateInputWindows");
  31. //从具有输入焦点的当前窗口中移除输入焦点。
  32. //仅当当前聚焦的应用程序没有响应并且当前聚焦的窗口不属于当前聚焦的应用程序时才应调用。
  33. mInputTransaction.removeCurrentInputFocus(mDisplayId);
  34. }
  35. mInputFocus = null;
  36. return;
  37. }
  38. //如果当前焦点窗口没有surface或者当前窗口无法聚焦则return
  39. if (!focus.mWinAnimator.hasSurface() || !focus.mInputWindowHandle.isFocusable()) {
  40. ProtoLog.v(WM_DEBUG_FOCUS_LIGHT, "Focus not requested for window=%s"
  41. + " because it has no surface or is not focusable.", focus);
  42. mInputFocus = null;
  43. return;
  44. }
  45. requestFocus(focusToken, focus.getName());
  46. }
  47. //将包装出来的InputChannelToken(focusToken)信息向native层进行同步
  48. private void requestFocus(IBinder focusToken, String windowName) {
  49. if (focusToken == mInputFocus) {
  50. return;
  51. }
  52. mInputFocus = focusToken;
  53. //输入焦点请求时间 用于anr的计算
  54. mInputFocusRequestTimeMillis = SystemClock.uptimeMillis();
  55. mInputTransaction.setFocusedWindow(mInputFocus, windowName, mDisplayId);
  56. //在这里打印要请求进入的窗口Focus request
  57. EventLog.writeEvent(LOGTAG_INPUT_FOCUS, "Focus request " + windowName,
  58. "reason=UpdateInputWindows");
  59. ProtoLog.v(WM_DEBUG_FOCUS_LIGHT, "Focus requested for window=%s", windowName);
  60. }

接着看mInputTransaction.setFocusedWindow 这个方法

代码路径:frameworks/base/core/java/android/view/SurfaceControl.java

  1. /**
  2. *如果窗口可聚焦,则将焦点设置在由输入 {@code token} 标识的窗口上,否则请求将被丢弃。
  3. *如果窗口不可见,则请求将排队,直到窗口变得可见或该请求被另一个请求覆盖
  4. *当前聚焦的窗口将立即失去焦点。
  5. *这是为了向新获得焦点的窗口发送在完成其第一次绘制时发生的任何焦点调度事件
  6. * @hide
  7. */
  8. public Transaction setFocusedWindow(@NonNull IBinder token, String windowName,
  9. int displayId) {
  10. nativeSetFocusedWindow(mNativeObject, token, windowName, displayId);
  11. return this;
  12. }

代码路径:frameworks/base/core/jni/android_view_SurfaceControl.cpp

  1. static void nativeSetFocusedWindow(JNIEnv* env, jclass clazz, jlong transactionObj,
  2. jobject toTokenObj, jstring windowNameJstr, jint displayId) {
  3. auto transaction = reinterpret_cast<SurfaceComposerClient::Transaction*>(transactionObj);
  4. if (toTokenObj == NULL) return;
  5. sp<IBinder> toToken(ibinderForJavaObject(env, toTokenObj));
  6. FocusRequest request;
  7. request.token = toToken;
  8. if (windowNameJstr != NULL) {
  9. ScopedUtfChars windowName(env, windowNameJstr);
  10. request.windowName = windowName.c_str();
  11. }
  12. request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
  13. request.displayId = displayId;
  14. //上面就是一些focusToken的异常检测,没问题,会调用下面的方法
  15. transaction->setFocusedWindow(request);
  16. }

代码路径:frameworks/native/libs/gui/SurfaceComposerClient.cpp

  1. SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setFocusedWindow(
  2. const FocusRequest& request) {
  3. mInputWindowCommands.focusRequests.push_back(request);
  4. return *this;
  5. }
  6. SurfaceComposerClient::Transaction&
  7. SurfaceComposerClient::Transaction::addWindowInfosReportedListener(
  8. sp<gui::IWindowInfosReportedListener> windowInfosReportedListener) {
  9. mInputWindowCommands.windowInfosReportedListeners.insert(windowInfosReportedListener);
  10. return *this;
  11. }

后续统一apply();BpBn调addInputWindowCommands()添加命令;

3.7 merge

再次回到InputMonitor#updateInputWindows()

代码路径:frameworks/base/services/core/java/com/android/server/wm/InputMonitor.java

  1. private void updateInputWindows(boolean inDrag) {
  2. Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "updateInputWindows");
  3. //.....
  4. // 遍历窗口更新inputInfo
  5. mDisplayContent.forAllWindows(this, true /* traverseTopToBottom */);
  6. //调用到Focus Request
  7. updateInputFocusRequest(mRecentsAnimationInputConsumer);
  8. // 将mInputTransaction合并到mPendingTransaction上进行提交
  9. if (!mUpdateInputWindowsImmediately) {
  10. mDisplayContent.getPendingTransaction().merge(mInputTransaction);
  11. mDisplayContent.scheduleAnimation();
  12. }
  13. Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
  14. }

调用SurfaceControl.Transaction#merge

代码路径:frameworks/base/core/java/android/view/SurfaceControl.java

  1. /**
  2. * Merge the other transaction into this transaction, clearing the
  3. * other transaction as if it had been applied.
  4. *
  5. * @param other The transaction to merge in to this one.
  6. * @return This transaction.
  7. */
  8. @NonNull
  9. public Transaction merge(@NonNull Transaction other) {
  10. if (this == other) {
  11. return this;
  12. }
  13. mResizedSurfaces.putAll(other.mResizedSurfaces);
  14. other.mResizedSurfaces.clear();
  15. mReparentedSurfaces.putAll(other.mReparentedSurfaces);
  16. other.mReparentedSurfaces.clear();
  17. nativeMergeTransaction(mNativeObject, other.mNativeObject);
  18. return this;
  19. }

之后,当WindowAnimator.java的animate()时发起apply();可以是线程"android.anim"或"binder"线程;

四、apply

接animate()的openSurfaceTransaction(),prepareSurfaces(),closeSurfaceTransaction()

代码路径:frameworks/base/services/core/java/com/android/server/wm/WindowAnimator.java

  1. private void animate(long frameTimeNs) {
  2. if (!mInitialized) {
  3. return;
  4. }
  5. // Schedule next frame already such that back-pressure happens continuously.
  6. scheduleAnimation();
  7. final RootWindowContainer root = mService.mRoot;
  8. mCurrentTime = frameTimeNs / TimeUtils.NANOS_PER_MS;
  9. mBulkUpdateParams = 0;
  10. root.mOrientationChangeComplete = true;
  11. if (DEBUG_WINDOW_TRACE) {
  12. Slog.i(TAG, "!!! animate: entry time=" + mCurrentTime);
  13. }
  14. ProtoLog.i(WM_SHOW_TRANSACTIONS, ">>> OPEN TRANSACTION animate");
  15. mService.openSurfaceTransaction();
  16. try {
  17. // Remove all deferred displays, tasks, and activities.
  18. root.handleCompleteDeferredRemoval();
  19. final AccessibilityController accessibilityController =
  20. mService.mAccessibilityController;
  21. final int numDisplays = root.getChildCount();
  22. for (int i = 0; i < numDisplays; i++) {
  23. final DisplayContent dc = root.getChildAt(i);
  24. // Update animations of all applications, including those associated with
  25. // exiting/removed apps.
  26. dc.updateWindowsForAnimator();
  27. dc.prepareSurfaces();
  28. }
  29. //......
  30. SurfaceControl.mergeToGlobalTransaction(mTransaction);
  31. mService.closeSurfaceTransaction("WindowAnimator");
  32. ProtoLog.i(WM_SHOW_TRANSACTIONS, "<<< CLOSE TRANSACTION animate");
  33. //......
  34. }
  1. mService.openSurfaceTransaction(),通过SurfaceControl来通知native开始一个Transaction;

  2. mService.closeSurfaceTransaction(),通过SurfaceControl来通知native(SurfaceFlinger)关闭一个Transaction最终来执行合成显示等工作;

4.1 WMS#openSurfaceTransaction

代码路径:frameworks/base/services/core/java/com/android/server/wm/WindowManagerService.java

  1. void openSurfaceTransaction() {
  2. try {
  3. Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "openSurfaceTransaction");
  4. SurfaceControl.openTransaction();
  5. } finally {
  6. Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
  7. }
  8. }

代码路径:frameworks/base/core/java/android/view/SurfaceControl.java

  1. /** 开启 transaction
  2. * @hide
  3. */
  4. @UnsupportedAppUsage
  5. public static void openTransaction() {
  6. synchronized (SurfaceControl.class) {
  7. //new出GlobalTransactionWrapper;
  8. if (sGlobalTransaction == null) {
  9. sGlobalTransaction = new GlobalTransactionWrapper();
  10. }
  11. synchronized(SurfaceControl.class) {
  12. sTransactionNestCount++;
  13. }
  14. }
  15. }

New出GlobalTransactionWrapper 接animate()的dc.prepareSurfaces();

4.2 DisplayContent#prepareSurfaces

代码路径:frameworks/base/services/core/java/com/android/server/wm/DisplayContent.java

  1. @Override
  2. void prepareSurfaces() {
  3. Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "prepareSurfaces");
  4. try {
  5. final Transaction transaction = getPendingTransaction();
  6. super.prepareSurfaces();
  7. // TODO: Once we totally eliminate global transaction we will pass transaction in here
  8. // rather than merging to global.
  9. SurfaceControl.mergeToGlobalTransaction(transaction);
  10. } finally {
  11. Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
  12. }
  13. }

将SurfaceControl提交在了mPendingTransaction上。然后完成遍历后,将mPendingTransaction合并到全局Transaction对象上提交给SurfaceFlinger。

代码路径:frameworks/base/core/java/android/view/SurfaceControl.java

  1. /**
  2. * Merge the supplied transaction in to the deprecated "global" transaction.
  3. * This clears the supplied transaction in an identical fashion to {@link Transaction#merge}.
  4. * <p>
  5. * This is a utility for interop with legacy-code and will go away with the Global Transaction.
  6. * @hide
  7. */
  8. @Deprecated
  9. public static void mergeToGlobalTransaction(Transaction t) {
  10. synchronized(SurfaceControl.class) {
  11. sGlobalTransaction.merge(t);
  12. }
  13. }

mergeToGlobalTransaction将提供的Transaction合并提交,然后接animate()调Wms的closeSurfaceTransaction()

4.3 WMS#closeSurfaceTransaction

代码路径:frameworks/base/services/core/java/com/android/server/wm/WindowManagerService.java

  1. /**
  2. * Closes a surface transaction.
  3. * @param where debug string indicating where the transaction originated
  4. */
  5. void closeSurfaceTransaction(String where) {
  6. try {
  7. Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "closeSurfaceTransaction");
  8. SurfaceControl.closeTransaction();
  9. mWindowTracing.logState(where);
  10. } finally {
  11. Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
  12. }
  13. }

代码路径:frameworks/base/core/java/android/view/SurfaceControl.java

  1. /** end a transaction
  2. * @hide
  3. */
  4. @UnsupportedAppUsage
  5. //open和close一一对应,保证 sTransactionNestCount 数量
  6. public static void closeTransaction() {
  7. synchronized(SurfaceControl.class) {
  8. if (sTransactionNestCount == 0) {
  9. Log.e(TAG,
  10. "Call to SurfaceControl.closeTransaction without matching openTransaction");
  11. } else if (--sTransactionNestCount > 0) {
  12. return;
  13. }
  14. sGlobalTransaction.applyGlobalTransaction(false);
  15. }
  16. }

再调用SurfaceControl的内部类GlobalTransactionWrapper#applyGlobalTransaction

代码路径:frameworks/base/core/java/android/view/SurfaceControl.java

  1. private static class GlobalTransactionWrapper extends SurfaceControl.Transaction {
  2. void applyGlobalTransaction(boolean sync) {
  3. applyResizedSurfaces();
  4. notifyReparentedSurfaces();
  5. nativeApplyTransaction(mNativeObject, sync);
  6. }
  7. @Override
  8. public void apply(boolean sync) {
  9. throw new RuntimeException("Global transaction must be applied from closeTransaction");
  10. }
  11. }

4.4 SurfaceComposerClient#apply

再调用android_view_SurfaceControl.cpp的nativeApplyTransaction方法

代码路径:frameworks/base/core/jni/android_view_SurfaceControl.cpp

  1. static void nativeApplyTransaction(JNIEnv* env, jclass clazz, jlong transactionObj, jboolean sync) {
  2. auto transaction = reinterpret_cast<SurfaceComposerClient::Transaction*>(transactionObj);
  3. transaction->apply(sync);
  4. }

代码路径:frameworks/native/libs/gui/SurfaceComposerClient.cpp

  1. status_t SurfaceComposerClient::Transaction::apply(bool synchronous, bool oneWay) {
  2. //......
  3. // 遍历mComposerStates,其中包含了所有的InputWindow
  4. for (auto const& kv : mComposerStates){ /
  5. composerStates.add(kv.second);
  6. }
  7. displayStates = std::move(mDisplayStates);
  8. //......
  9. //最后把上面收集的Transaction相关信息,调用sf的setTransactionState进行跨进程传递到sf进程
  10. sf->setTransactionState(mFrameTimelineInfo, composerStates, displayStates, flags, applyToken,
  11. mInputWindowCommands, mDesiredPresentTime, mIsAutoTimestamp,
  12. {} /*uncacheBuffer - only set in doUncacheBufferTransaction*/,
  13. hasListenerCallbacks, listenerCallbacks, mId);
  14. mId = generateId();
  15. // Clear the current states and flags
  16. clear();//apply后就需要把Transaction进行clear
  17. return NO_ERROR;
  18. }

apply方法主要就是收集之前通过transaction属性设置方法设置所有信息都需要收集起来,比如最重要的composerStates,然后调用sf的跨进程方法setTransactionState传递到sf中。

五、SF传递给Input(存疑)

 接下来就到了SurfaceFlinger端,内调ISurfaceComposer的setTransactionState()

5.1 SurfaceFlinger::setTransactionState

代码路径:frameworks/native/libs/gui/ISurfaceComposer.cpp

  1. virtual ~BpSurfaceComposer();
  2. status_t setTransactionState(
  3. const FrameTimelineInfo& frameTimelineInfo, Vector<ComposerState>& state,
  4. const Vector<DisplayState>& displays, uint32_t flags, const sp<IBinder>& applyToken,
  5. InputWindowCommands commands, int64_t desiredPresentTime, bool isAutoTimestamp,
  6. const std::vector<client_cache_t>& uncacheBuffers, bool hasListenerCallbacks,
  7. const std::vector<ListenerCallbacks>& listenerCallbacks, uint64_t transactionId,
  8. const std::vector<uint64_t>& mergedTransactionIds) override {
  9. Parcel data, reply;
  10. data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
  11. }
  12. status_t BnSurfaceComposer::onTransact(
  13. uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
  14. {
  15. return setTransactionState(frameTimelineInfo, state, displays, stateFlags, applyToken,
  16. std::move(inputWindowCommands), desiredPresentTime,
  17. isAutoTimestamp, uncacheBuffers, hasListenerCallbacks,
  18. listenerCallbacks, transactionId, mergedTransactions);
  19. }

这里是一个BpBn操作,进程surfaceflinger的binder线程,主要是调用到SurfaceFlinger.cpp的setTransactionState()。

代码路径:frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp

  1. status_t SurfaceFlinger::setTransactionState(
  2. const FrameTimelineInfo& frameTimelineInfo, const Vector<ComposerState>& states,
  3. const Vector<DisplayState>& displays, uint32_t flags, const sp<IBinder>& applyToken,
  4. const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime,
  5. bool isAutoTimestamp, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
  6. const std::vector<ListenerCallbacks>& listenerCallbacks, uint64_t transactionId) {
  7. ATRACE_CALL();
  8. ...
  9. TransactionState state{frameTimelineInfo, states,
  10. displays, flags,
  11. applyToken, inputWindowCommands,
  12. desiredPresentTime, isAutoTimestamp,
  13. uncacheBuffer, postTime,
  14. permissions, hasListenerCallbacks,
  15. listenerCallbacks, originPid,
  16. originUid, transactionId};
  17. ...
  18. if (mTransactionTracing) {
  19. mTransactionTracing->addQueuedTransaction(state);
  20. }
  21. // 将TransactionState入队,该方法会触发相应的Commit操作
  22. queueTransaction(state);
  23. // Check the pending state to make sure the transaction is synchronous.if (state.transactionCommittedSignal) {
  24. waitForSynchronousTransaction(*state.transactionCommittedSignal);
  25. }
  26. updateSmomoLayerInfo(state, desiredPresentTime, isAutoTimestamp);
  27. return NO_ERROR;
  28. }

5.2 SurfaceFlinger::updateInputFlinger

代码路径:frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp

在每次SurfaceFlinger主线程进行commit操作的时候,都会调用一次updateInputFlinger方法去更新一遍需要派发给InputDispatcher的窗口信息,代码如下:

  1. bool SurfaceFlinger::commit(TimePoint frameTime, VsyncId vsyncId, TimePoint expectedVsyncTime)
  2. FTL_FAKE_GUARD(kMainThreadContext) {
  3. // and may eventually call to ~Layer() if it holds the last reference
  4. //
  5. updateCursorAsync();
  6. updateInputFlinger(vsyncId, frameTime);
  7. }

转到updateInputFlinger();

代码路径:frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp

  1. void SurfaceFlinger::updateInputFlinger(VsyncId vsyncId, TimePoint frameTime) {
  2. // 如果是没有InputDispatcher或者是没有需要更新的Input窗口信息和窗口命令(如:焦点窗口切换)
  3. // 那么就没有执行updateInputFlinger的必要,直接返回
  4. if (!mInputFlinger || (!mUpdateInputInfo && mInputWindowCommands.empty())) {
  5. return;
  6. }
  7. ATRACE_CALL();
  8. std::vector<WindowInfo> windowInfos;
  9. std::vector<DisplayInfo> displayInfos;
  10. bool updateWindowInfo = false;
  11. if (mUpdateInputInfo) {// 需要更新InputInfo的时候会设置为true,默认是false
  12. mUpdateInputInfo = false;
  13. //将updateWindowInfo设置为true
  14. updateWindowInfo = true;
  15. //构建窗口列表信息
  16. buildWindowInfos(windowInfos, displayInfos);
  17. }
  18. std::unordered_set<int32_t> visibleWindowIds;
  19. // 保存最新的可见的WindowInfo
  20. for (WindowInfo& windowInfo : windowInfos) {
  21. if (!windowInfo.inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
  22. visibleWindowIds.insert(windowInfo.id);
  23. }
  24. }
  25. bool visibleWindowsChanged = false;
  26. if (visibleWindowIds != mVisibleWindowIds) {
  27. visibleWindowsChanged = true;
  28. mVisibleWindowIds = std::move(visibleWindowIds);
  29. }
  30. // 设置回调派发WindowInfo给InputDispatcher和调用焦点窗口切换方法
  31. BackgroundExecutor::getInstance().sendCallbacks({[updateWindowInfo,
  32. windowInfos = std::move(windowInfos),
  33. displayInfos = std::move(displayInfos),
  34. inputWindowCommands =
  35. std::move(mInputWindowCommands),
  36. inputFlinger = mInputFlinger, this,
  37. visibleWindowsChanged, vsyncId, frameTime]() {
  38. ATRACE_NAME("BackgroundExecutor::updateInputFlinger");
  39. //通知窗口信息改变
  40. if (updateWindowInfo) {
  41. //通知InputDispatcher更新窗口列表信息
  42. mWindowInfosListenerInvoker
  43. ->windowInfosChanged(gui::WindowInfosUpdate{std::move(windowInfos),
  44. std::move(displayInfos),
  45. vsyncId.value, frameTime.ns()},
  46. std::move(
  47. inputWindowCommands.windowInfosReportedListeners),
  48. /* forceImmediateCall= */ visibleWindowsChanged ||
  49. !inputWindowCommands.focusRequests.empty());
  50. } else {
  51. // 如果有监听器但输入窗口没有变化,则立即调用监听器。
  52. for (const auto& listener : inputWindowCommands.windowInfosReportedListeners) {
  53. if (IInterface::asBinder(listener)->isBinderAlive()) {
  54. listener->onWindowInfosReported();
  55. }
  56. }
  57. }
  58. // focusRequests也是从InputMonitor传过来的,
  59. // InputMonitor的updateInputFocusRequest方法最后会调用requestFocus方法,
  60. //requestFocus方法里面会往InputTransaction里设置focus window。
  61. for (const auto& focusRequest : inputWindowCommands.focusRequests) {
  62. inputFlinger->setFocusedWindow(focusRequest);
  63. }
  64. }});
  65. mInputWindowCommands.clear();
  66. }

接下来看一下构建WindowInfo方法:buildWindowInfos

5.3 SurfaceFlinger::buildWindowInfos

代码路径:frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp

  1. void SurfaceFlinger::buildWindowInfos(std::vector<WindowInfo>& outWindowInfos,
  2. std::vector<DisplayInfo>& outDisplayInfos) {
  3. static size_t sNumWindowInfos = 0;
  4. outWindowInfos.reserve(sNumWindowInfos);
  5. sNumWindowInfos = 0;
  6. if (mLayerLifecycleManagerEnabled) {
  7. mLayerSnapshotBuilder.forEachInputSnapshot(
  8. [&outWindowInfos](const frontend::LayerSnapshot& snapshot) {
  9. outWindowInfos.push_back(snapshot.inputInfo);
  10. });
  11. } else {
  12. //遍历Layer列表
  13. mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
  14. //如果对应Layer不满足needsInputInfo条件,则return
  15. //这里过滤了很大一部分layer
  16. if (!layer->needsInputInfo()) return;
  17. const auto opt =
  18. mFrontEndDisplayInfos.get(layer->getLayerStack())
  19. .transform([](const frontend::DisplayInfo& info) {
  20. return Layer::InputDisplayArgs{&info.transform, info.isSecure};
  21. });
  22. //先通过fillInputinfo填充窗口信息至对应Layer
  23. //再将返回的WindowInfo放入outWindowInfos列表中
  24. outWindowInfos.push_back(layer->fillInputInfo(opt.value_or(Layer::InputDisplayArgs{})));
  25. });
  26. }
  27. sNumWindowInfos = outWindowInfos.size();
  28. outDisplayInfos.reserve(mFrontEndDisplayInfos.size());
  29. for (const auto& [_, info] : mFrontEndDisplayInfos) {
  30. outDisplayInfos.push_back(info.info);
  31. }

需要出现在InputDispatcher的窗口列表中,在SurfaceFlinger这里需要满足两个条件:

  1. 对应Layer存在于SurfaceFlinger所维护的Layer列表中,

  2. 对应Layer需要满足needsInputInfo条件。

对于第一个条件,当Layer对应Surface没有被上层destroy时,才会存在于SurfaceFlinger的Layer列表中。(上层移除Surface的时机一般为对应窗口退出动画执行完毕时,由relayoutWindow流程发起)

对于第二个条件,需要对应窗口的inputChannelToken建立且没有被移除。

5.4 Layer::fillInputInfo 设置可见性

代码路径:frameworks/native/services/surfaceflinger/Layer.cpp

  1. WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
  2. WindowInfo info = mDrawingState.inputInfo;
  3. // 设置WindowInfo可见性
  4. info.visible = isVisibleForInput();
  5. info.alpha = getAlpha();
  6. fillTouchOcclusionMode(info);
  7. handleDropInputMode(info);
  8. // 不可见的WindowInfo就在这里设置上WindowInfo::InputConfig::NOT_VISIBLE
  9. // 后续派发到InputDispatcher中就能根据该flag判断是否可见
  10. info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !info.visible);
  11. return info;
  12. }

看一下可见性在Layer::isVisibleForInput中是如何判断的:

代码路径:frameworks/native/services/surfaceflinger/Layer.h

  1. virtual bool isVisibleForInput() const {
  2. // For compatibility reasons we let layers which can receive input
  3. // receive input before they have actually submitted a buffer. Because
  4. // of this we use canReceiveInput instead of isVisible to check the
  5. // policy-visibility, ignoring the buffer state. However for layers with
  6. // hasInputInfo()==false we can use the real visibility state.
  7. // We are just using these layers for occlusion detection in
  8. // InputDispatcher, and obviously if they aren't visible they can't occlude
  9. // anything.
  10. // 对于具不具备InputInfo的layer,有两种可见性的判断逻辑,对于输入窗口,走canReceiveInput
  11. return hasInputInfo() ? canReceiveInput() : isVisible();
  12. }

代码路径:frameworks/native/services/surfaceflinger/Layer.cpp

对于具有InputInfo的Layer,走的是canReceiveInput的逻辑判断当前是否可见:

  1. bool Layer::canReceiveInput() const {
  2. return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
  3. }

这里通过三个条件作可见性判断:

  1. isHiddenByPolicy:这里会检查目标Layer的flag是否带有不可见标识

  2. mBufferInfo.mBuffer:buffer为空即满足可见条件

  3. getAlpha:Alpha值大于0,非透明即可见

详细的有关layer可见性的本篇不再继续跟踪

5.5 WindowInfosListenerInvoker::windowInfosChanged

回到SurfaceFlinger::updateInputFlinger方法,我们继续跟一下windowInfosChanged

  1. void SurfaceFlinger::updateInputFlinger(VsyncId vsyncId, TimePoint frameTime) {
  2. // 如果是没有InputDispatcher或者是没有需要更新的Input窗口信息和窗口命令(如:焦点窗口切换)
  3. // 那么 就没有执行updateInputFlinger的必要,直接返回
  4. if (!mInputFlinger || (!mUpdateInputInfo && mInputWindowCommands.empty())) {
  5. return;
  6. }
  7. ATRACE_CALL();
  8. //......
  9. if (updateWindowInfo) {
  10. //通知InputDispatcher更新窗口列表信息
  11. mWindowInfosListenerInvoker
  12. ->windowInfosChanged(gui::WindowInfosUpdate{std::move(windowInfos),
  13. std::move(displayInfos),
  14. vsyncId.value, frameTime.ns()},
  15. std::move(
  16. inputWindowCommands.windowInfosReportedListeners),
  17. /* forceImmediateCall= */ visibleWindowsChanged ||
  18. !inputWindowCommands.focusRequests.empty());
  19. }
  20. //.....
  21. mInputWindowCommands.clear();
  22. }

windowInfosChanged方法能够将WindowInfo的变化通知到InputDispatcher。

代码路径:frameworks/native/services/surfaceflinger/WindowInfosListenerInvoker.cpp

  1. void WindowInfosListenerInvoker::windowInfosChanged(
  2. gui::WindowInfosUpdate update, WindowInfosReportedListenerSet reportedListeners,
  3. bool forceImmediateCall) {
  4. // ......
  5. for (auto& pair : mWindowInfosListeners) {
  6. auto& [listenerId, listener] = pair.second;
  7. // listener其实就是InputDispather
  8. auto status = listener->onWindowInfosChanged(update);
  9. if (!status.isOk()) {
  10. ackWindowInfosReceived(update.vsyncId, listenerId);
  11. }
  12. }
  13. // ......
  14. }

内调InputDispatcher.cpp内部类DispatcherWindowListener的onWindowInfosChanged();

代码路径:frameworks/native/services/inputflinger/dispatcher/InputDispatcher.cpp

  1. void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
  2. const gui::WindowInfosUpdate& update) {
  3. mDispatcher.onWindowInfosChanged(update);
  4. }
  5. void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
  6. // The listener sends the windows as a flattened array. Separate the windows by display for
  7. // more convenient parsing.
  8. std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
  9. for (const auto& info : update.windowInfos) {
  10. handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
  11. handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
  12. }
  13. { // acquire lock
  14. std::scoped_lock _l(mLock);
  15. //确保我们为所有现有显示器创建了一个条目,
  16. //以便如果 displayId 没有窗口,我们可以知道窗口已从显示器中删除。
  17. for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
  18. handlesPerDisplay[displayId];
  19. }
  20. mDisplayInfos.clear();
  21. for (const auto& displayInfo : update.displayInfos) {
  22. mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
  23. }
  24. //遍历,handlesPerDisplay,调setInputWindowsLocked()
  25. for (const auto& [displayId, handles] : handlesPerDisplay) {
  26. setInputWindowsLocked(handles, displayId);
  27. }
  28. if (update.vsyncId < mWindowInfosVsyncId) {
  29. ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
  30. ", current update vsync id: %" PRId64,
  31. mWindowInfosVsyncId, update.vsyncId);
  32. }
  33. mWindowInfosVsyncId = update.vsyncId;
  34. }
  35. // Wake up poll loop since it may need to make new input dispatching choices.
  36. mLooper->wake();
  37. }

//遍历,handlesPerDisplay,调setInputWindowsLocked() 由sf侧传递给input侧

六、Input之FocusWindow切换

 

6.1 InputDispatcher::setInputWindowsLocked

代码路径:frameworks/native/services/inputflinger/dispatcher/InputDispatcher.cpp

  1. // 对每一个windowInfo进行判断和处理
  2. void InputDispatcher::setInputWindowsLocked(
  3. const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
  4. ...
  5. // Copy old handles for release if they are no longer present.
  6. const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
  7. // Save the old windows' orientation by ID before it gets updated.
  8. std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
  9. for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
  10. oldWindowOrientations.emplace(handle->getId(),
  11. handle->getInfo()->transform.getOrientation());
  12. }
  13. //更新mWindowHandlesByDisplay这个map,然后通过getWindowHandlesLocked()
  14. //找newFocusedWindowHandle
  15. updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
  16. const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
  17. if (mLastHoverWindowHandle &&
  18. std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
  19. windowHandles.end()) {
  20. mLastHoverWindowHandle = nullptr;
  21. }
  22. // 对FocusChanges进行处理,同步给FocusResolver来更新窗口状态
  23. std::optional<FocusResolver::FocusChanges> changes =
  24. mFocusResolver.setInputWindows(displayId, windowHandles);
  25. if (changes) {
  26. onFocusChangedLocked(*changes);
  27. }
  28. ...
  29. }

6.2 FocusResolver::setInputWindows

代码路径:frameworks/native/services/inputflinger/dispatcher/FocusResolver.cpp

  1. /**
  2. * 当窗口属性更改时,将调用“setInputWindows”。这里我们将检查当前聚焦的窗口是否可以保持聚焦
  3. * 如果当前聚焦的窗口仍然有资格获得焦点(“isTokenFocusable”返回 OK),那么我们将继续授予它焦点
  4. * 否则我们将检查先前的焦点请求是否有资格获得焦点。
  5. */
  6. std::optional<FocusResolver::FocusChanges> FocusResolver::setInputWindows(
  7. int32_t displayId, const std::vector<sp<WindowInfoHandle>>& windows) {
  8. std::string removeFocusReason;
  9. //请求焦点,WMS把focusRequest发给surfaceFlinger,surfaceFlinger传递到这里。
  10. const std::optional<FocusRequest> request = getFocusRequest(displayId);
  11. // 获取当前的焦点窗口
  12. const sp<IBinder> currentFocus = getFocusedWindowToken(displayId);
  13. // 根据最新的 FocusRequest 查找下一个焦点令牌。如果请求的焦点窗口无法获得焦点,则焦点将被移除。
  14. if (request) {
  15. sp<IBinder> requestedFocus = request->token;
  16. sp<WindowInfoHandle> resolvedFocusWindow;
  17. Focusability result = getResolvedFocusWindow(requestedFocus, windows, resolvedFocusWindow);
  18. if (result == Focusability::OK && resolvedFocusWindow->getToken() == currentFocus) {
  19. return std::nullopt;
  20. }
  21. const Focusability previousResult = mLastFocusResultByDisplay[displayId];
  22. mLastFocusResultByDisplay[displayId] = result;
  23. //只有获取的状态为ok
  24. if (result == Focusability::OK) {
  25. LOG_ALWAYS_FATAL_IF(!resolvedFocusWindow,
  26. "Focused window should be non-null when result is OK!");
  27. // 如果可以获取焦点,则更新焦点窗口
  28. return updateFocusedWindow(displayId,
  29. "Window became focusable. Previous reason: " +
  30. ftl::enum_string(previousResult),
  31. resolvedFocusWindow->getToken(),
  32. resolvedFocusWindow->getName());
  33. }
  34. removeFocusReason = ftl::enum_string(result);
  35. }
  36. // 无法获取焦点,则焦点为空
  37. return updateFocusedWindow(displayId, removeFocusReason, nullptr);
  38. }

6.3 FocusResolver::isTokenFocusable判断焦点窗口状态

代码路径:frameworks/native/services/inputflinger/dispatcher/FocusResolver.cpp

  1. FocusResolver::Focusability FocusResolver::isTokenFocusable(
  2. const sp<IBinder>& token, const std::vector<sp<WindowInfoHandle>>& windows,
  3. sp<WindowInfoHandle>& outFocusableWindow) {
  4. bool allWindowsAreFocusable = true;
  5. bool windowFound = false;// 默认设置窗口未找到
  6. sp<WindowInfoHandle> visibleWindowHandle = nullptr;
  7. // 遍历InputDispatcher中保存的所有窗口信息
  8. for (const sp<WindowInfoHandle>& window : windows) {
  9. if (window->getToken() != token) {// 一直走这个分支的话,就是找不到目标窗口
  10. continue;
  11. }
  12. windowFound = true;
  13. // 目标窗口的inputConfig不包含NOT_VISIBLE,那么窗口就是可见的
  14. if (!window->getInfo()->inputConfig.test(gui::WindowInfo::InputConfig::NOT_VISIBLE)) {
  15. // Check if at least a single window is visible.
  16. visibleWindowHandle = window;
  17. }
  18. // 目标窗口的inputConfig包含NOT_FOCUSABLE,那么窗口就是不能获取焦点
  19. if (window->getInfo()->inputConfig.test(gui::WindowInfo::InputConfig::NOT_FOCUSABLE)) {
  20. // Check if all windows with the window token are focusable.
  21. allWindowsAreFocusable = false;
  22. break;
  23. }
  24. }
  25. // 根据前面的遍历查找结果设置焦点窗口状态
  26. if (!windowFound) {
  27. return Focusability::NO_WINDOW;
  28. }
  29. if (!allWindowsAreFocusable) {
  30. return Focusability::NOT_FOCUSABLE;
  31. }
  32. if (!visibleWindowHandle) {
  33. return Focusability::NOT_VISIBLE;
  34. }
  35. // 仅当窗口可以聚焦时才设置 outFoundWindow
  36. outFocusableWindow = visibleWindowHandle;
  37. return Focusability::OK;
  38. }

 

这里要遍历的windows是从SurfaceFlinger发来的最新的输入窗口列表,而token是之前设置的焦点窗口,这个函数的大意是根据最新的输入窗口信息判断之前设置的焦点窗口是否有效。

那么可能有几种情况,即对应Focusability的4个值:

  1. 返回NO_WINDOW,说明之前设置的焦点窗口已经不在最新的输入窗口列表里了,即该输入窗口的Layer已经被移除了,或者不满足Layer.needsInputInfo的条件

  2. 返回NOT_FOCUSABLE,说明之前设置的焦点窗口还在最新的输入窗口列表里,但是被设置了NOT_FOCUSABLE这个标志位,不满足作为焦点窗口的条件了

  3. 返回NOT_VISIBLE,说明之前设置的焦点窗口还在最新的输入窗口列表里,但是被设置了NOT_VISIBLE,即该Layer已经不可见了,所以不能再作为焦点窗口了

  4. 返回OK,找到了一个符合条件的窗口作为焦点窗口,并且将该窗口保存在传参outFocusableWindow中

  1. private:
  2. enum class Focusability {
  3. OK,
  4. NO_WINDOW,
  5. NOT_FOCUSABLE,
  6. NOT_VISIBLE,
  7. ftl_last = NOT_VISIBLE
  8. };

6.4 InputDispatcher::setFocusedWindow

异步BpBn;//进程system_server的binder线程调用InputManager.cpp的setFocusedWindow()

代码路径:frameworks/native/services/inputflinger/InputManager.cpp

  1. binder::Status InputManager::setFocusedWindow(const FocusRequest& request) {
  2. mDispatcher->setFocusedWindow(request);
  3. return binder::Status::ok();
  4. }

内调InputDispatcher.cpp的setFocusedWindow();

代码路径:frameworks/native/services/inputflinger/dispatcher/InputDispatcher.cpp

  1. /**
  2. * 将焦点设置到由标记标识的窗口。必须在更新任何输入窗口句柄后调用此函数。
  3. *
  4. * Params:
  5. * request.token - 输入通道令牌用于标识应该获得焦点的窗口
  6. * request.focusedToken - 调用者期望当前关注的令牌。如果指定的令牌与当前聚焦的窗口不匹配,则该请求将被丢弃。
  7. * 如果指定的焦点标记与当前焦点窗口匹配,则调用将成功。
  8. * 如果无论当前聚焦的令牌是什么,此调用都应该成功,则将其设置为“null”
  9. * request.timestamp - 请求焦点更改时客户端 (wm) 设置的 SYSTEM_TIME_MONOTONIC 时间戳(以纳秒为单位)。
  10. * 如果存在来自另一个源(例如指针向下)的焦点更改请求,这将确定哪个请求优先。
  11. */
  12. void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
  13. { // acquire lock
  14. std::scoped_lock _l(mLock);
  15. std::optional<FocusResolver::FocusChanges> changes =
  16. mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
  17. if (changes) {
  18. onFocusChangedLocked(*changes);
  19. }
  20. } // release lock
  21. // Wake up poll loop since it may need to make new input dispatching choices.
  22. mLooper->wake();
  23. }

先调用FocusResolver.cpp的setFocusedWindow()

6.5 FocusResolver::updateFocusedWindow

代码路径:frameworks/native/services/inputflinger/dispatcher/FocusResolver.cpp

  1. /**
  2. * 当窗口属性更改时,将调用“setInputWindows”。这里我们将检查当前聚焦的窗口是否可以保持聚焦
  3. * 如果当前聚焦的窗口仍然有资格获得焦点(“isTokenFocusable”返回 OK),那么我们将继续授予它焦点
  4. * 否则我们将检查先前的焦点请求是否有资格获得焦点。
  5. */
  6. std::optional<FocusResolver::FocusChanges> FocusResolver::setInputWindows(
  7. int32_t displayId, const std::vector<sp<WindowInfoHandle>>& windows) {
  8. std::string removeFocusReason;
  9. //请求焦点,WMS把focusRequest发给surfaceFlinger,surfaceFlinger传递到这里。
  10. const std::optional<FocusRequest> request = getFocusRequest(displayId);
  11. // 获取当前的焦点窗口
  12. const sp<IBinder> currentFocus = getFocusedWindowToken(displayId);
  13. // 根据最新的 FocusRequest 查找下一个焦点令牌。如果请求的焦点窗口无法获得焦点,则焦点将被移除。
  14. if (request) {
  15. sp<IBinder> requestedFocus = request->token;
  16. sp<WindowInfoHandle> resolvedFocusWindow;
  17. Focusability result = getResolvedFocusWindow(requestedFocus, windows, resolvedFocusWindow);
  18. if (result == Focusability::OK && resolvedFocusWindow->getToken() == currentFocus) {
  19. return std::nullopt;
  20. }
  21. const Focusability previousResult = mLastFocusResultByDisplay[displayId];
  22. mLastFocusResultByDisplay[displayId] = result;
  23. //只有获取的状态为ok
  24. if (result == Focusability::OK) {
  25. LOG_ALWAYS_FATAL_IF(!resolvedFocusWindow,
  26. "Focused window should be non-null when result is OK!");
  27. // 如果可以获取焦点,则更新焦点窗口
  28. return updateFocusedWindow(displayId,
  29. "Window became focusable. Previous reason: " +
  30. ftl::enum_string(previousResult),
  31. resolvedFocusWindow->getToken(),
  32. resolvedFocusWindow->getName());
  33. }
  34. removeFocusReason = ftl::enum_string(result);
  35. }
  36. // 无法获取焦点,则焦点为空
  37. return updateFocusedWindow(displayId, removeFocusReason, nullptr);
  38. }

调用updateFocusedWindow 新的焦点窗口newFocus赋值给mFocusedWindowTokenByDisplay

代码路径:frameworks/native/services/inputflinger/dispatcher/FocusResolver.cpp

  1. std::optional<FocusResolver::FocusChanges> FocusResolver::updateFocusedWindow(
  2. int32_t displayId, const std::string& reason, const sp<IBinder>& newFocus,
  3. const std::string& tokenName) {
  4. sp<IBinder> oldFocus = getFocusedWindowToken(displayId);
  5. if (newFocus == oldFocus) {
  6. return std::nullopt;
  7. }
  8. if (newFocus) {
  9. //赋值mFocusRequestByDisplay
  10. mFocusedWindowTokenByDisplay[displayId] = {tokenName, newFocus};
  11. } else {
  12. mFocusedWindowTokenByDisplay.erase(displayId);
  13. }
  14. return {{oldFocus, newFocus, displayId, reason}};
  15. }

   //赋值mFocusRequestByDisplay

6.6 InputDispatcher::dispatchFocusLocked

我们回到InputDispatcher::setFocusedWindow方法,继续调用InputDispatcher::onFocusChangedLocked方法

代码路径:frameworks/native/services/inputflinger/dispatcher/InputDispatcher.cpp

  1. void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
  2. if (changes.oldFocus) {
  3. std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
  4. if (focusedInputChannel) {
  5. CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
  6. "focus left window");
  7. synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
  8. enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
  9. }
  10. }
  11. if (changes.newFocus) {
  12. enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
  13. }
  14. disablePointerCaptureForcedLocked();
  15. if (mFocusedDisplayId == changes.displayId) {
  16. sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
  17. }
  18. }

调用enqueueFocusEventLocked方法,接下来是一系列调用堆栈

代码路径:frameworks/native/services/inputflinger/dispatcher/InputDispatcher.cpp

  1. void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
  2. const std::string& reason) {
  3. if (mPendingEvent != nullptr) {
  4. // Move the pending event to the front of the queue. This will give the chance
  5. // for the pending event to get dispatched to the newly focused window
  6. mInboundQueue.push_front(mPendingEvent);
  7. mPendingEvent = nullptr;
  8. }
  9. std::unique_ptr<FocusEntry> focusEntry =
  10. std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
  11. reason);
  12. //该事件应该位于队列的前面,但位于所有其他焦点事件之后
  13. // 找到最后一个焦点事件,并在其后面插入
  14. std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
  15. std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
  16. [](const std::shared_ptr<EventEntry>& event) {
  17. return event->type == EventEntry::Type::FOCUS;
  18. });
  19. // 维护焦点事件的顺序。在所有其他焦点事件之后插入条目。
  20. mInboundQueue.insert(it.base(), std::move(focusEntry));
  21. }

代码路径:frameworks/native/services/inputflinger/dispatcher/InputDispatcher.cpp

  1. void InputDispatcher::dispatchOnce() {
  2. nsecs_t nextWakeupTime = LLONG_MAX;
  3. { // acquire lock
  4. std::scoped_lock _l(mLock);
  5. mDispatcherIsAlive.notify_all();
  6. // Run a dispatch loop if there are no pending commands.
  7. // The dispatch loop might enqueue commands to run afterwards.
  8. if (!haveCommandsLocked()) {
  9. dispatchOnceInnerLocked(&nextWakeupTime);
  10. }
  11. //.......
  12. }

代码路径:frameworks/native/services/inputflinger/dispatcher/InputDispatcher.cpp

  1. void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
  2. nsecs_t currentTime = now();
  3. //......
  4. case EventEntry::Type::FOCUS: {
  5. std::shared_ptr<FocusEntry> typedEntry =
  6. std::static_pointer_cast<FocusEntry>(mPendingEvent);
  7. dispatchFocusLocked(currentTime, typedEntry);
  8. done = true;
  9. dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
  10. break;
  11. }
  12. //......
  13. }

dispatchFocusLocked关键log"Focus entering" "Focus leaving" 打印地方

代码路径:frameworks/native/services/inputflinger/dispatcher/InputDispatcher.cpp

  1. void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
  2. std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
  3. if (channel == nullptr) {
  4. return; // Window has gone away
  5. }
  6. InputTarget target;
  7. target.inputChannel = channel;
  8. target.flags = InputTarget::Flags::DISPATCH_AS_IS;
  9. entry->dispatchInProgress = true;
  10. std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
  11. channel->getName();
  12. std::string reason = std::string("reason=").append(entry->reason);
  13. android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
  14. dispatchEventLocked(currentTime, entry, {target});
  15. }

在这里打印日志"Focus entering" "Focus leaving"

代码路径:frameworks/native/services/inputflinger/dispatcher/InputDispatcher.cpp

  1. void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
  2. std::shared_ptr<EventEntry> eventEntry,
  3. const std::vector<InputTarget>& inputTargets) {
  4. ATRACE_CALL();
  5. if (DEBUG_DISPATCH_CYCLE) {
  6. ALOGD("dispatchEventToCurrentInputTargets");
  7. }
  8. updateInteractionTokensLocked(*eventEntry, inputTargets);
  9. ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
  10. pokeUserActivityLocked(*eventEntry);
  11. for (const InputTarget& inputTarget : inputTargets) {
  12. std::shared_ptr<Connection> connection =
  13. getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
  14. if (connection != nullptr) {
  15. prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
  16. } else {
  17. if (DEBUG_FOCUS) {
  18. ALOGD("Dropping event delivery to target with channel '%s' because it "
  19. "is no longer registered with the input dispatcher.",
  20. inputTarget.inputChannel->getName().c_str());
  21. }
  22. }
  23. }

总结:

焦点窗口切换涉及模块较多,需要经过WMS->SF->Input三个模块传递

其中对sf传给input这段相关的通信存疑,网上资料也比较少且安卓U上也有函数改动,希望能有大佬补充,上面相关流程有些地方可能不对,涉及到多个进程。希望相关大佬能够补充分析,感谢

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/爱喝兽奶帝天荒/article/detail/791031?site
推荐阅读
相关标签
  

闽ICP备14008679号