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) {
eventTiming = EventTiming::Create(window, *event_);
eventTiming = EventTiming::Create(window, *event_, event_->target());
}
if (event_->type() == event_type_names::kChange && event_->isTrusted() &&

@ -254,7 +254,7 @@ WebInputEventResult MouseEventManager::DispatchMouseEvent(
: MouseEvent::kRealOrIndistinguishable,
mouse_event.menu_source_type);
if (frame_ && frame_->DomWindow())
event_timing = EventTiming::Create(frame_->DomWindow(), *event);
event_timing = EventTiming::Create(frame_->DomWindow(), *event, target);
if (should_dispatch) {
input_event_result = event_handling_util::ToWebInputEventResult(
target->DispatchEvent(*event));
@ -270,7 +270,7 @@ WebInputEventResult MouseEventManager::DispatchMouseEvent(
: MouseEvent::kRealOrIndistinguishable,
mouse_event.menu_source_type);
if (frame_ && frame_->DomWindow())
event_timing = EventTiming::Create(frame_->DomWindow(), *event);
event_timing = EventTiming::Create(frame_->DomWindow(), *event, target);
if (should_dispatch) {
input_event_result = event_handling_util::ToWebInputEventResult(
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.
pointer_event->SetTrusted(true);
std::unique_ptr<EventTiming> event_timing;
if (frame_ && frame_->DomWindow())
event_timing = EventTiming::Create(frame_->DomWindow(), *pointer_event);
if (frame_ && frame_->DomWindow()) {
event_timing =
EventTiming::Create(frame_->DomWindow(), *pointer_event, target);
}
if (event_type == event_type_names::kPointerdown ||
event_type == event_type_names::kPointerover ||

@ -46,10 +46,12 @@ bool ShouldReportForEventTiming(WindowPerformance* performance) {
EventTiming::EventTiming(base::TimeTicks processing_start,
WindowPerformance* performance,
const Event& event)
const Event& event,
EventTarget* original_event_target)
: processing_start_(processing_start),
performance_(performance),
event_(&event) {
event_(&event),
original_event_target_(original_event_target) {
performance_->SetCurrentEventTimingEvent(&event);
}
@ -93,8 +95,10 @@ bool EventTiming::IsEventTypeForEventTiming(const Event& event) {
}
// static
std::unique_ptr<EventTiming> EventTiming::Create(LocalDOMWindow* window,
const Event& event) {
std::unique_ptr<EventTiming> EventTiming::Create(
LocalDOMWindow* window,
const Event& event,
EventTarget* original_event_target) {
auto* performance = DOMWindowPerformance::performance(*window);
if (!performance || !event.isTrusted() ||
(!IsEventTypeForEventTiming(event) &&
@ -118,7 +122,7 @@ std::unique_ptr<EventTiming> EventTiming::Create(LocalDOMWindow* window,
HandleInputDelay(window, event, processing_start);
return should_report_for_event_timing
? std::make_unique<EventTiming>(processing_start, performance,
event)
event, original_event_target)
: nullptr;
}
@ -133,8 +137,15 @@ EventTiming::~EventTiming() {
base::TimeTicks event_timestamp =
pointer_event ? pointer_event->OldestPlatformTimeStamp()
: 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

@ -30,11 +30,15 @@ class CORE_EXPORT EventTiming final {
// This object should be constructed before the event is dispatched and
// destructed after dispatch so that we can calculate the input delay and
// 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,
WindowPerformance* performance,
const Event& event);
const Event& event,
EventTarget* original_event_target);
~EventTiming();
EventTiming(const EventTiming&) = delete;
EventTiming& operator=(const EventTiming&) = delete;
@ -57,6 +61,8 @@ class CORE_EXPORT EventTiming final {
Persistent<WindowPerformance> performance_;
Persistent<const Event> event_;
Persistent<EventTarget> original_event_target_;
};
} // namespace blink

@ -391,6 +391,7 @@ void WindowPerformance::ReportLongTask(base::TimeTicks start_time,
}
void WindowPerformance::RegisterEventTiming(const Event& event,
EventTarget* event_target,
base::TimeTicks start_time,
base::TimeTicks processing_start,
base::TimeTicks processing_end) {
@ -426,7 +427,7 @@ void WindowPerformance::RegisterEventTiming(const Event& event,
event_type, MonotonicTimeToDOMHighResTimeStamp(start_time),
MonotonicTimeToDOMHighResTimeStamp(processing_start),
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.
// See crbug.com/1320878.
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
// promise is resolved.
void RegisterEventTiming(const Event& event,
EventTarget* event_target,
base::TimeTicks start_time,
base::TimeTicks processing_start,
base::TimeTicks processing_end);

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

@ -19,7 +19,7 @@ promise_test(async t => {
new PerformanceObserver(() => {
resolve2();
}).observe({type: "event", durationThreshold: 16});
await clickOnElementAndDelay('myDiv', 30);
await clickAndBlockMain('myDiv', { duration: 30 });
});
const afterFirstClick = performance.now();
new PerformanceObserver(t.step_func(list => {
@ -37,7 +37,7 @@ promise_test(async t => {
});
})).observe({type: 'event', durationThreshold: 16, buffered: true});
// 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");
</script>

@ -19,44 +19,53 @@
let timeBeforeFirstClick;
let timeAfterFirstClick;
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);
assert_not_equals(timeAfterFirstClick, undefined);
assert_not_equals(timeAfterSecondClick, undefined);
// First click.
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.");
function testExpectations(observedEntries) {
assert_not_equals(timeBeforeFirstClick, undefined);
assert_not_equals(timeAfterFirstClick, undefined);
assert_not_equals(timeAfterSecondClick, undefined);
// 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,
// First click.
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.
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.");
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();
clickAndBlockMain('button').then( () => {
timeAfterFirstClick = performance.now();
clickAndBlockMain('button').then(() => {
timeAfterSecondClick = performance.now();
})
});
await clickAndBlockMain('button');
timeAfterFirstClick = performance.now();
await clickAndBlockMain('button');
timeAfterSecondClick = performance.now();
const observedEntries = await observerPromise;
testExpectations(observedEntries);
}, "Event Timing: compare click timings.");
</script>
</html>

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

@ -45,6 +45,8 @@
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.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.");
</script>

@ -1,24 +1,44 @@
// Clicks on the element with the given ID. It adds an event handler to the element which
// ensures that the events have a duration of at least |delay|. Calls |callback| during
// event handler if |callback| is provided.
async function clickOnElementAndDelay(id, delay, callback) {
const element = document.getElementById(id);
const pointerdownHandler = () => {
mainThreadBusy(delay);
if (callback) {
callback();
}
element.removeEventListener("pointerdown", pointerdownHandler);
function mainThreadBusy(ms) {
const target = performance.now() + ms;
while (performance.now() < target);
}
async function wait() {
return new Promise(resolve => step_timeout(resolve, 0));
}
async function raf() {
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 click(element);
await Promise.all([
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
// 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);
}
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
// attempt to check that the duration is appropriately checked by:
// * 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 => {
for (let index = 0; index < numEntries; index++) {
// Add some click events that has at least slowDur for duration.
await clickOnElementAndDelay(id, slowDur);
await clickAndBlockMain(id, { duration: slowDur });
}
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.
// In that case, the test will verify the event duration to ensure the event duration is
// 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
// observer promise can be resolved
await clickOnElementAndDelay(id, durThreshold);
await clickAndBlockMain(id, { duration: durThreshold });
return observerPromise;
}
@ -269,7 +269,7 @@ async function testEventType(t, eventType, looseCount=false) {
// Trigger two 'fast' events of the type.
await applyAction(eventType, target);
await applyAction(eventType, target);
await waitForTick();
await afterNextPaint();
await new Promise(t.step_func(resolve => {
testCounts(t, resolve, looseCount, eventType, initialCount + 2);
}));
@ -313,7 +313,7 @@ async function testEventType(t, eventType, looseCount=false) {
// Cause a slow event.
await applyAction(eventType, target);
await waitForTick();
await afterNextPaint();
await observerPromise;
}

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