0

Event Timing reports EventTarget for more pointer events

Only in cases where there is not a single pointer event registered on a page, blink may entirely optimize out EventDispatch steps, since there are no observers anyway.  This optimization should not normally be detectable.

However, the Event Timing API still measures these events and reports them to the performance timeline.  Because the EventDispatch steps are where we assign EventTarget to Event objects, the Event Timing API was effectively missing the target value whenever we skipped this step.

This patch plumbs the original HitTest target which we fall back to under such situations.

Bug: 1367329
Change-Id: Icf21e6103c98261e9f6e88cef1ac09f3a683751b
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/5246848
Commit-Queue: Michal Mocny <mmocny@chromium.org>
Reviewed-by: Aoyuan Zuo <zuoaoyuan@chromium.org>
Reviewed-by: Christian Biesinger <cbiesinger@chromium.org>
Cr-Commit-Position: refs/heads/main@{#1255634}
This commit is contained in:
Michal Mocny
2024-02-02 17:38:01 +00:00
committed by Chromium LUCI CQ
parent 0e80319e35
commit c7dac09bd9
14 changed files with 146 additions and 105 deletions

@@ -198,7 +198,7 @@ DispatchEventResult EventDispatcher::Dispatch() {
} }
if (frame && window) { if (frame && window) {
eventTiming = EventTiming::Create(window, *event_); eventTiming = EventTiming::Create(window, *event_, event_->target());
} }
if (event_->type() == event_type_names::kChange && event_->isTrusted() && if (event_->type() == event_type_names::kChange && event_->isTrusted() &&

@@ -254,7 +254,7 @@ WebInputEventResult MouseEventManager::DispatchMouseEvent(
: MouseEvent::kRealOrIndistinguishable, : MouseEvent::kRealOrIndistinguishable,
mouse_event.menu_source_type); mouse_event.menu_source_type);
if (frame_ && frame_->DomWindow()) if (frame_ && frame_->DomWindow())
event_timing = EventTiming::Create(frame_->DomWindow(), *event); event_timing = EventTiming::Create(frame_->DomWindow(), *event, target);
if (should_dispatch) { if (should_dispatch) {
input_event_result = event_handling_util::ToWebInputEventResult( input_event_result = event_handling_util::ToWebInputEventResult(
target->DispatchEvent(*event)); target->DispatchEvent(*event));
@@ -270,7 +270,7 @@ WebInputEventResult MouseEventManager::DispatchMouseEvent(
: MouseEvent::kRealOrIndistinguishable, : MouseEvent::kRealOrIndistinguishable,
mouse_event.menu_source_type); mouse_event.menu_source_type);
if (frame_ && frame_->DomWindow()) if (frame_ && frame_->DomWindow())
event_timing = EventTiming::Create(frame_->DomWindow(), *event); event_timing = EventTiming::Create(frame_->DomWindow(), *event, target);
if (should_dispatch) { if (should_dispatch) {
input_event_result = event_handling_util::ToWebInputEventResult( input_event_result = event_handling_util::ToWebInputEventResult(
target->DispatchEvent(*event)); target->DispatchEvent(*event));

@@ -168,8 +168,10 @@ WebInputEventResult PointerEventManager::DispatchPointerEvent(
// We are about to dispatch this event. It has to be trusted at this point. // We are about to dispatch this event. It has to be trusted at this point.
pointer_event->SetTrusted(true); pointer_event->SetTrusted(true);
std::unique_ptr<EventTiming> event_timing; std::unique_ptr<EventTiming> event_timing;
if (frame_ && frame_->DomWindow()) if (frame_ && frame_->DomWindow()) {
event_timing = EventTiming::Create(frame_->DomWindow(), *pointer_event); event_timing =
EventTiming::Create(frame_->DomWindow(), *pointer_event, target);
}
if (event_type == event_type_names::kPointerdown || if (event_type == event_type_names::kPointerdown ||
event_type == event_type_names::kPointerover || event_type == event_type_names::kPointerover ||

@@ -46,10 +46,12 @@ bool ShouldReportForEventTiming(WindowPerformance* performance) {
EventTiming::EventTiming(base::TimeTicks processing_start, EventTiming::EventTiming(base::TimeTicks processing_start,
WindowPerformance* performance, WindowPerformance* performance,
const Event& event) const Event& event,
EventTarget* original_event_target)
: processing_start_(processing_start), : processing_start_(processing_start),
performance_(performance), performance_(performance),
event_(&event) { event_(&event),
original_event_target_(original_event_target) {
performance_->SetCurrentEventTimingEvent(&event); performance_->SetCurrentEventTimingEvent(&event);
} }
@@ -93,8 +95,10 @@ bool EventTiming::IsEventTypeForEventTiming(const Event& event) {
} }
// static // static
std::unique_ptr<EventTiming> EventTiming::Create(LocalDOMWindow* window, std::unique_ptr<EventTiming> EventTiming::Create(
const Event& event) { LocalDOMWindow* window,
const Event& event,
EventTarget* original_event_target) {
auto* performance = DOMWindowPerformance::performance(*window); auto* performance = DOMWindowPerformance::performance(*window);
if (!performance || !event.isTrusted() || if (!performance || !event.isTrusted() ||
(!IsEventTypeForEventTiming(event) && (!IsEventTypeForEventTiming(event) &&
@@ -118,7 +122,7 @@ std::unique_ptr<EventTiming> EventTiming::Create(LocalDOMWindow* window,
HandleInputDelay(window, event, processing_start); HandleInputDelay(window, event, processing_start);
return should_report_for_event_timing return should_report_for_event_timing
? std::make_unique<EventTiming>(processing_start, performance, ? std::make_unique<EventTiming>(processing_start, performance,
event) event, original_event_target)
: nullptr; : nullptr;
} }
@@ -133,8 +137,15 @@ EventTiming::~EventTiming() {
base::TimeTicks event_timestamp = base::TimeTicks event_timestamp =
pointer_event ? pointer_event->OldestPlatformTimeStamp() pointer_event ? pointer_event->OldestPlatformTimeStamp()
: event_->PlatformTimeStamp(); : event_->PlatformTimeStamp();
performance_->RegisterEventTiming(*event_, event_timestamp, processing_start_,
Now()); // `event->target()` is assigned as part of EventDispatch, and will be unset
// whenever we skip dispatch. (See: crbug.com/1367329).
// In those cases, we may still have an `original_event_target` which was the
// result of the original HitTest. Use that as fallback only.
EventTarget* event_target =
event_->target() ? event_->target() : original_event_target_.Get();
performance_->RegisterEventTiming(*event_, event_target, event_timestamp,
processing_start_, Now());
} }
} // namespace blink } // namespace blink

@@ -30,11 +30,15 @@ class CORE_EXPORT EventTiming final {
// This object should be constructed before the event is dispatched and // This object should be constructed before the event is dispatched and
// destructed after dispatch so that we can calculate the input delay and // destructed after dispatch so that we can calculate the input delay and
// other latency values correctly. // other latency values correctly.
static std::unique_ptr<EventTiming> Create(LocalDOMWindow*, const Event&); static std::unique_ptr<EventTiming> Create(
LocalDOMWindow* window,
const Event& event,
EventTarget* original_event_target);
explicit EventTiming(base::TimeTicks processing_start, explicit EventTiming(base::TimeTicks processing_start,
WindowPerformance* performance, WindowPerformance* performance,
const Event& event); const Event& event,
EventTarget* original_event_target);
~EventTiming(); ~EventTiming();
EventTiming(const EventTiming&) = delete; EventTiming(const EventTiming&) = delete;
EventTiming& operator=(const EventTiming&) = delete; EventTiming& operator=(const EventTiming&) = delete;
@@ -57,6 +61,8 @@ class CORE_EXPORT EventTiming final {
Persistent<WindowPerformance> performance_; Persistent<WindowPerformance> performance_;
Persistent<const Event> event_; Persistent<const Event> event_;
Persistent<EventTarget> original_event_target_;
}; };
} // namespace blink } // namespace blink

@@ -391,6 +391,7 @@ void WindowPerformance::ReportLongTask(base::TimeTicks start_time,
} }
void WindowPerformance::RegisterEventTiming(const Event& event, void WindowPerformance::RegisterEventTiming(const Event& event,
EventTarget* event_target,
base::TimeTicks start_time, base::TimeTicks start_time,
base::TimeTicks processing_start, base::TimeTicks processing_start,
base::TimeTicks processing_end) { base::TimeTicks processing_end) {
@@ -426,7 +427,7 @@ void WindowPerformance::RegisterEventTiming(const Event& event,
event_type, MonotonicTimeToDOMHighResTimeStamp(start_time), event_type, MonotonicTimeToDOMHighResTimeStamp(start_time),
MonotonicTimeToDOMHighResTimeStamp(processing_start), MonotonicTimeToDOMHighResTimeStamp(processing_start),
MonotonicTimeToDOMHighResTimeStamp(processing_end), event.cancelable(), MonotonicTimeToDOMHighResTimeStamp(processing_end), event.cancelable(),
event.target() ? event.target()->ToNode() : nullptr, event_target ? event_target->ToNode() : nullptr,
DomWindow()); // TODO(haoliuk): Add WPT for Event Timing. DomWindow()); // TODO(haoliuk): Add WPT for Event Timing.
// See crbug.com/1320878. // See crbug.com/1320878.
absl::optional<PointerId> pointer_id; absl::optional<PointerId> pointer_id;

@@ -133,6 +133,7 @@ class CORE_EXPORT WindowPerformance final : public Performance,
// presentation promise to calculate the |duration| attribute when such // presentation promise to calculate the |duration| attribute when such
// promise is resolved. // promise is resolved.
void RegisterEventTiming(const Event& event, void RegisterEventTiming(const Event& event,
EventTarget* event_target,
base::TimeTicks start_time, base::TimeTicks start_time,
base::TimeTicks processing_start, base::TimeTicks processing_start,
base::TimeTicks processing_end); base::TimeTicks processing_end);

@@ -112,8 +112,9 @@ class WindowPerformanceTest : public testing::Test {
init->setKeyCode(key_code); init->setKeyCode(key_code);
KeyboardEvent* keyboard_event = KeyboardEvent* keyboard_event =
MakeGarbageCollected<KeyboardEvent>(type, init); MakeGarbageCollected<KeyboardEvent>(type, init);
performance_->RegisterEventTiming(*keyboard_event, start_time, performance_->RegisterEventTiming(*keyboard_event, keyboard_event->target(),
processing_start, processing_end); start_time, processing_start,
processing_end);
return performance_->event_presentation_promise_count_; return performance_->event_presentation_promise_count_;
} }
@@ -129,8 +130,9 @@ class WindowPerformanceTest : public testing::Test {
if (target) { if (target) {
pointer_event->SetTarget(target); pointer_event->SetTarget(target);
} }
performance_->RegisterEventTiming(*pointer_event, start_time, performance_->RegisterEventTiming(*pointer_event, pointer_event->target(),
processing_start, processing_end); start_time, processing_start,
processing_end);
} }
PerformanceEventTiming* CreatePerformanceEventTiming( PerformanceEventTiming* CreatePerformanceEventTiming(

@@ -19,7 +19,7 @@ promise_test(async t => {
new PerformanceObserver(() => { new PerformanceObserver(() => {
resolve2(); resolve2();
}).observe({type: "event", durationThreshold: 16}); }).observe({type: "event", durationThreshold: 16});
await clickOnElementAndDelay('myDiv', 30); await clickAndBlockMain('myDiv', { duration: 30 });
}); });
const afterFirstClick = performance.now(); const afterFirstClick = performance.now();
new PerformanceObserver(t.step_func(list => { new PerformanceObserver(t.step_func(list => {
@@ -37,7 +37,7 @@ promise_test(async t => {
}); });
})).observe({type: 'event', durationThreshold: 16, buffered: true}); })).observe({type: 'event', durationThreshold: 16, buffered: true});
// This should be the only click observed since the other one would not be buffered. // This should be the only click observed since the other one would not be buffered.
await clickOnElementAndDelay('myDiv', 30); await clickAndBlockMain('myDiv', { duration: 30 } );
}); });
}, "PerformanceObserver buffering independent of durationThreshold"); }, "PerformanceObserver buffering independent of durationThreshold");
</script> </script>

@@ -19,44 +19,53 @@
let timeBeforeFirstClick; let timeBeforeFirstClick;
let timeAfterFirstClick; let timeAfterFirstClick;
let timeAfterSecondClick; let timeAfterSecondClick;
let observedEntries = [];
async_test(function(t) {
assert_implements(window.PerformanceEventTiming, 'Event Timing is not supported.');
new PerformanceObserver(t.step_func(entryList => {
observedEntries = observedEntries.concat(entryList.getEntries().filter(
entry => entry.name === 'pointerdown'));
if (observedEntries.length < 2)
return;
assert_not_equals(timeBeforeFirstClick, undefined); function testExpectations(observedEntries) {
assert_not_equals(timeAfterFirstClick, undefined); assert_not_equals(timeBeforeFirstClick, undefined);
assert_not_equals(timeAfterSecondClick, undefined); assert_not_equals(timeAfterFirstClick, undefined);
// First click. assert_not_equals(timeAfterSecondClick, undefined);
verifyClickEvent(observedEntries[0], 'button');
assert_between_exclusive(observedEntries[0].processingStart,
timeBeforeFirstClick,
timeAfterFirstClick,
"First click's processingStart");
assert_greater_than(timeAfterFirstClick, observedEntries[0].startTime,
"timeAfterFirstClick should be later than first click's start time.");
// Second click. // First click.
verifyClickEvent(observedEntries[1], 'button'); verifyClickEvent(observedEntries[0], 'button');
assert_between_exclusive(observedEntries[1].processingStart, assert_between_exclusive(observedEntries[0].processingStart,
timeAfterFirstClick, timeBeforeFirstClick,
timeAfterSecondClick, timeAfterFirstClick,
"Second click's processingStart"); "First click's processingStart");
assert_greater_than(timeAfterSecondClick, observedEntries[1].startTime, assert_greater_than(timeAfterFirstClick, observedEntries[0].startTime,
"timeAfterFirstClick should be later than first click's start time.");
// Second click.
verifyClickEvent(observedEntries[1], 'button');
assert_between_exclusive(observedEntries[1].processingStart,
timeAfterFirstClick,
timeAfterSecondClick,
"Second click's processingStart");
assert_greater_than(timeAfterSecondClick, observedEntries[1].startTime,
"timeAfterSecondClick should be later than second click's start time."); "timeAfterSecondClick should be later than second click's start time.");
t.done(); }
})).observe({type: 'event'});
promise_test(async function(t) {
assert_implements(window.PerformanceEventTiming, 'Event Timing is not supported.');
const observerPromise = new Promise(resolve => {
const observedEntries = [];
new PerformanceObserver(entryList => {
observedEntries.push(...entryList.getEntriesByName("pointerdown"));
if (observedEntries.length < 2)
return;
resolve(observedEntries);
}).observe({type: 'event'});
})
timeBeforeFirstClick = performance.now(); timeBeforeFirstClick = performance.now();
clickAndBlockMain('button').then( () => { await clickAndBlockMain('button');
timeAfterFirstClick = performance.now(); timeAfterFirstClick = performance.now();
clickAndBlockMain('button').then(() => { await clickAndBlockMain('button');
timeAfterSecondClick = performance.now(); timeAfterSecondClick = performance.now();
})
}); const observedEntries = await observerPromise;
testExpectations(observedEntries);
}, "Event Timing: compare click timings."); }, "Event Timing: compare click timings.");
</script> </script>
</html> </html>

@@ -46,11 +46,14 @@
promise_test(async t => { promise_test(async t => {
assert_implements(window.PerformanceEventTiming, "Event Timing is not supported"); assert_implements(window.PerformanceEventTiming, "Event Timing is not supported");
// Wait for load event so we can interact with the iframe. // Wait for load event so we can interact with the iframe.
await new Promise(resolve => { await new Promise(resolve => {
window.addEventListener('load', resolve); window.addEventListener('load', resolve);
}); });
clickTimeMin = performance.now(); clickTimeMin = performance.now();
let observedPointerDown = false; let observedPointerDown = false;
const observerPromise = new Promise(resolve => { const observerPromise = new Promise(resolve => {
new PerformanceObserver(t.step_func(entries => { new PerformanceObserver(t.step_func(entries => {
@@ -61,14 +64,16 @@
assert_false(observedPointerDown, assert_false(observedPointerDown,
"Observer of main frames should only capture main-frame event-timing entries"); "Observer of main frames should only capture main-frame event-timing entries");
validateEntries(pointerDowns);
observedPointerDown = true; observedPointerDown = true;
resolve(); resolve(pointerDowns);
})).observe({type: 'event'}); })).observe({type: 'event'});
}); });
clickAndBlockMain('button').then(() => {
clickDone = performance.now(); await clickAndBlockMain('button');
}); clickDone = performance.now();
const pointerDowns = await observerPromise;
validateEntries(pointerDowns);
const childFrameEntriesPromise = new Promise(resolve => { const childFrameEntriesPromise = new Promise(resolve => {
window.addEventListener("message", (event) => { window.addEventListener("message", (event) => {
// testdriver-complete is a webdriver internal event // testdriver-complete is a webdriver internal event
@@ -80,13 +85,15 @@
} }
}, false); }, false);
}); });
// Tap on the iframe, with an offset of 10 to target the div inside it. // Tap on the iframe, with an offset of 10 to target the div inside it.
const actions = new test_driver.Actions() const actions = new test_driver.Actions()
.pointerMove(10, 10, { origin: document.getElementById("iframe") }) .pointerMove(10, 10, { origin: document.getElementById("iframe") })
.pointerDown() .pointerDown()
.pointerUp(); .pointerUp();
actions.send(); actions.send();
return Promise.all([observerPromise, childFrameEntriesPromise]);
await childFrameEntriesPromise;
}, "Event Timing: entries should only be observable by its own frame."); }, "Event Timing: entries should only be observable by its own frame.");
</script> </script>

@@ -45,6 +45,8 @@
assert_greater_than(firstInputInteractionId, 0, 'The first input entry should have a non-trivial interactionId'); assert_greater_than(firstInputInteractionId, 0, 'The first input entry should have a non-trivial interactionId');
assert_equals(firstInputInteractionId, eventTimingPointerDownInteractionId, 'The first input entry should have the same interactionId as the event timing pointerdown entry'); assert_equals(firstInputInteractionId, eventTimingPointerDownInteractionId, 'The first input entry should have the same interactionId as the event timing pointerdown entry');
assert_equals(firstInputInteractionId.target, eventTimingPointerDownInteractionId.target, 'The first input entry should have the same target as the event timing pointerdown entry');
assert_not_equals(firstInputInteractionId.target, null, 'The first input entry should have a non-null target');
}, "The interactionId of the first input entry should match the same pointerdown entry of event timing when tap."); }, "The interactionId of the first input entry should match the same pointerdown entry of event timing when tap.");
</script> </script>

@@ -1,24 +1,44 @@
// Clicks on the element with the given ID. It adds an event handler to the element which function mainThreadBusy(ms) {
// ensures that the events have a duration of at least |delay|. Calls |callback| during const target = performance.now() + ms;
// event handler if |callback| is provided. while (performance.now() < target);
async function clickOnElementAndDelay(id, delay, callback) { }
const element = document.getElementById(id);
const pointerdownHandler = () => { async function wait() {
mainThreadBusy(delay); return new Promise(resolve => step_timeout(resolve, 0));
if (callback) { }
callback();
} async function raf() {
element.removeEventListener("pointerdown", pointerdownHandler); return new Promise(resolve => requestAnimationFrame(resolve));
}
async function afterNextPaint() {
await raf();
await wait();
}
async function blockNextEventListener(target, eventType, duration = 120) {
return new Promise(resolve => {
target.addEventListener(eventType, () => {
mainThreadBusy(duration);
resolve();
}, { once: true });
});
}
async function clickAndBlockMain(id, options = {}) {
options = {
eventType: "pointerdown",
duration: 120,
...options
}; };
const element = document.getElementById(id);
element.addEventListener("pointerdown", pointerdownHandler); await Promise.all([
await click(element); blockNextEventListener(element, options.eventType, options.duration),
click(element),
]);
} }
function mainThreadBusy(duration) {
const now = performance.now();
while (performance.now() < now + duration);
}
// This method should receive an entry of type 'event'. |isFirst| is true only when we want // This method should receive an entry of type 'event'. |isFirst| is true only when we want
// to check that the event also happens to correspond to the first event. In this case, the // to check that the event also happens to correspond to the first event. In this case, the
@@ -58,27 +78,7 @@ function verifyClickEvent(entry, targetId, isFirst=false, minDuration=104, event
verifyEvent(entry, event, targetId, isFirst, minDuration); verifyEvent(entry, event, targetId, isFirst, minDuration);
} }
function wait() {
return new Promise((resolve, reject) => {
step_timeout(() => {
resolve();
}, 0);
});
}
function clickAndBlockMain(id) {
return new Promise((resolve, reject) => {
clickOnElementAndDelay(id, 120, resolve);
});
}
function waitForTick() {
return new Promise(resolve => {
window.requestAnimationFrame(() => {
window.requestAnimationFrame(resolve);
});
});
}
// Add a PerformanceObserver and observe with a durationThreshold of |dur|. This test will // Add a PerformanceObserver and observe with a durationThreshold of |dur|. This test will
// attempt to check that the duration is appropriately checked by: // attempt to check that the duration is appropriately checked by:
// * Asserting that entries received have a duration which is the smallest multiple of 8 // * Asserting that entries received have a duration which is the smallest multiple of 8
@@ -115,7 +115,7 @@ async function testDuration(t, id, numEntries, dur, slowDur) {
const clicksPromise = new Promise(async resolve => { const clicksPromise = new Promise(async resolve => {
for (let index = 0; index < numEntries; index++) { for (let index = 0; index < numEntries; index++) {
// Add some click events that has at least slowDur for duration. // Add some click events that has at least slowDur for duration.
await clickOnElementAndDelay(id, slowDur); await clickAndBlockMain(id, { duration: slowDur });
} }
resolve(); resolve();
}); });
@@ -154,11 +154,11 @@ async function testDuration(t, id, numEntries, dur, slowDur) {
// These clicks are expected to be ignored, unless the test has some extra delays. // These clicks are expected to be ignored, unless the test has some extra delays.
// In that case, the test will verify the event duration to ensure the event duration is // In that case, the test will verify the event duration to ensure the event duration is
// greater than the duration threshold // greater than the duration threshold
await clickOnElementAndDelay(id, processingDelay); await clickAndBlockMain(id, { duration: processingDelay });
} }
// Send click with event duration equals to or greater than |durThreshold|, so the // Send click with event duration equals to or greater than |durThreshold|, so the
// observer promise can be resolved // observer promise can be resolved
await clickOnElementAndDelay(id, durThreshold); await clickAndBlockMain(id, { duration: durThreshold });
return observerPromise; return observerPromise;
} }
@@ -269,7 +269,7 @@ async function testEventType(t, eventType, looseCount=false) {
// Trigger two 'fast' events of the type. // Trigger two 'fast' events of the type.
await applyAction(eventType, target); await applyAction(eventType, target);
await applyAction(eventType, target); await applyAction(eventType, target);
await waitForTick(); await afterNextPaint();
await new Promise(t.step_func(resolve => { await new Promise(t.step_func(resolve => {
testCounts(t, resolve, looseCount, eventType, initialCount + 2); testCounts(t, resolve, looseCount, eventType, initialCount + 2);
})); }));
@@ -313,7 +313,7 @@ async function testEventType(t, eventType, looseCount=false) {
// Cause a slow event. // Cause a slow event.
await applyAction(eventType, target); await applyAction(eventType, target);
await waitForTick(); await afterNextPaint();
await observerPromise; await observerPromise;
} }

@@ -42,7 +42,7 @@ promise_test(async t => {
Math.ceil(span1Rect.y + span1Rect.height / 2) Math.ceil(span1Rect.y + span1Rect.height / 2)
).send(); ).send();
await waitForTick(); await afterNextPaint();
const observerPromise = new Promise(resolve => { const observerPromise = new Promise(resolve => {
new PerformanceObserver(t.step_func(entryList => { new PerformanceObserver(t.step_func(entryList => {
@@ -60,7 +60,7 @@ promise_test(async t => {
Math.ceil(span2Rect.y + span2Rect.height / 2) Math.ceil(span2Rect.y + span2Rect.height / 2)
).send(); ).send();
await waitForTick(); await afterNextPaint();
await observerPromise; await observerPromise;
}, "Event Timing: Move pointer within shadow DOM should create event-timing entry with null target."); }, "Event Timing: Move pointer within shadow DOM should create event-timing entry with null target.");