InputTracer: Wait to trace dispatch events to the backend

... until event processing is complete. This is because we need to wait
until processing complete to get information about the targets and
sensitivity of an event, which is required to write the dispatch event
to the backend.

Bug: 210460522
Test: atest inputflinger_tests
Change-Id: I227c207d6a5667f9297e74b4c8be9f8e980d6d13
diff --git a/services/inputflinger/dispatcher/trace/InputTracer.cpp b/services/inputflinger/dispatcher/trace/InputTracer.cpp
index 83ed452..49e6e21 100644
--- a/services/inputflinger/dispatcher/trace/InputTracer.cpp
+++ b/services/inputflinger/dispatcher/trace/InputTracer.cpp
@@ -183,10 +183,21 @@
     const int32_t windowId = dispatchEntry.windowId.value_or(0);
     const int32_t vsyncId = dispatchEntry.windowId.has_value() ? dispatchEntry.vsyncId : 0;
 
-    mBackend->traceWindowDispatch({std::move(traced), dispatchEntry.deliveryTime,
-                                   dispatchEntry.resolvedFlags, dispatchEntry.targetUid, vsyncId,
-                                   windowId, dispatchEntry.transform, dispatchEntry.rawTransform,
-                                   /*hmac=*/{}, resolvedKeyRepeatCount});
+    const WindowDispatchArgs windowDispatchArgs{std::move(traced),
+                                                dispatchEntry.deliveryTime,
+                                                dispatchEntry.resolvedFlags,
+                                                dispatchEntry.targetUid,
+                                                vsyncId,
+                                                windowId,
+                                                dispatchEntry.transform,
+                                                dispatchEntry.rawTransform,
+                                                /*hmac=*/{},
+                                                resolvedKeyRepeatCount};
+    if (eventState->isEventProcessingComplete) {
+        mBackend->traceWindowDispatch(std::move(windowDispatchArgs));
+    } else {
+        eventState->pendingDispatchArgs.emplace_back(std::move(windowDispatchArgs));
+    }
 }
 
 std::shared_ptr<InputTracer::EventState>& InputTracer::getState(
@@ -205,6 +216,12 @@
     for (const auto& event : events) {
         writeEventToBackend(event, *tracer.mBackend);
     }
+    // Write all pending dispatch args to the trace.
+    for (const auto& windowDispatchArgs : pendingDispatchArgs) {
+        tracer.mBackend->traceWindowDispatch(windowDispatchArgs);
+    }
+    pendingDispatchArgs.clear();
+
     isEventProcessingComplete = true;
 }