1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "third_party/blink/renderer/core/inspector/inspector_trace_events.h"
6 
7 #include <inttypes.h>
8 
9 #include <memory>
10 
11 #include "cc/layers/picture_layer.h"
12 #include "third_party/blink/public/mojom/loader/request_context_frame_type.mojom-blink.h"
13 #include "third_party/blink/renderer/bindings/core/v8/script_source_code.h"
14 #include "third_party/blink/renderer/bindings/core/v8/source_location.h"
15 #include "third_party/blink/renderer/core/animation/animation.h"
16 #include "third_party/blink/renderer/core/animation/keyframe_effect.h"
17 #include "third_party/blink/renderer/core/css/invalidation/invalidation_set.h"
18 #include "third_party/blink/renderer/core/css/style_change_reason.h"
19 #include "third_party/blink/renderer/core/dom/events/event.h"
20 #include "third_party/blink/renderer/core/events/keyboard_event.h"
21 #include "third_party/blink/renderer/core/events/wheel_event.h"
22 #include "third_party/blink/renderer/core/frame/local_dom_window.h"
23 #include "third_party/blink/renderer/core/frame/local_frame.h"
24 #include "third_party/blink/renderer/core/frame/local_frame_view.h"
25 #include "third_party/blink/renderer/core/html/html_frame_owner_element.h"
26 #include "third_party/blink/renderer/core/html/parser/html_document_parser.h"
27 #include "third_party/blink/renderer/core/inspector/identifiers_factory.h"
28 #include "third_party/blink/renderer/core/layout/hit_test_result.h"
29 #include "third_party/blink/renderer/core/layout/layout_image.h"
30 #include "third_party/blink/renderer/core/layout/layout_object.h"
31 #include "third_party/blink/renderer/core/loader/document_loader.h"
32 #include "third_party/blink/renderer/core/loader/resource/css_style_sheet_resource.h"
33 #include "third_party/blink/renderer/core/page/page.h"
34 #include "third_party/blink/renderer/core/paint/paint_layer.h"
35 #include "third_party/blink/renderer/core/probe/core_probes.h"
36 #include "third_party/blink/renderer/core/workers/worker_global_scope.h"
37 #include "third_party/blink/renderer/core/workers/worker_thread.h"
38 #include "third_party/blink/renderer/core/xmlhttprequest/xml_http_request.h"
39 #include "third_party/blink/renderer/platform/graphics/graphics_layer.h"
40 #include "third_party/blink/renderer/platform/instrumentation/instance_counters.h"
41 #include "third_party/blink/renderer/platform/instrumentation/tracing/traced_value.h"
42 #include "third_party/blink/renderer/platform/loader/fetch/resource_load_priority.h"
43 #include "third_party/blink/renderer/platform/loader/fetch/resource_load_timing.h"
44 #include "third_party/blink/renderer/platform/loader/fetch/resource_request.h"
45 #include "third_party/blink/renderer/platform/loader/fetch/resource_response.h"
46 #include "third_party/blink/renderer/platform/weborigin/kurl.h"
47 #include "third_party/blink/renderer/platform/wtf/dynamic_annotations.h"
48 #include "third_party/blink/renderer/platform/wtf/text/text_position.h"
49 #include "third_party/blink/renderer/platform/wtf/vector.h"
50 #include "v8/include/v8-profiler.h"
51 #include "v8/include/v8.h"
52 
53 namespace blink {
54 
55 namespace {
56 
InspectorParseHtmlBeginData(Document * document,unsigned start_line)57 std::unique_ptr<TracedValue> InspectorParseHtmlBeginData(Document* document,
58                                                          unsigned start_line) {
59   auto value = std::make_unique<TracedValue>();
60   value->SetInteger("startLine", start_line);
61   value->SetString("frame", IdentifiersFactory::FrameId(document->GetFrame()));
62   value->SetString("url", document->Url().GetString());
63   SetCallStack(value.get());
64   return value;
65 }
66 
InspectorParseHtmlEndData(unsigned end_line)67 std::unique_ptr<TracedValue> InspectorParseHtmlEndData(unsigned end_line) {
68   auto value = std::make_unique<TracedValue>();
69   value->SetInteger("endLine", end_line);
70   return value;
71 }
72 
GetNavigationTracingData(Document * document)73 std::unique_ptr<TracedValue> GetNavigationTracingData(Document* document) {
74   auto data = std::make_unique<TracedValue>();
75 
76   data->SetString("navigationId",
77                   IdentifiersFactory::LoaderId(document->Loader()));
78   return data;
79 }
80 
GetModifierFromEvent(const UIEventWithKeyState & event)81 int GetModifierFromEvent(const UIEventWithKeyState& event) {
82   int modifier = 0;
83   if (event.altKey())
84     modifier |= 1;
85   if (event.ctrlKey())
86     modifier |= 2;
87   if (event.metaKey())
88     modifier |= 4;
89   if (event.shiftKey())
90     modifier |= 8;
91   return modifier;
92 }
93 
94 }  //  namespace
95 
ToHexString(const void * p)96 String ToHexString(const void* p) {
97   return String::Format("0x%" PRIx64,
98                         static_cast<uint64_t>(reinterpret_cast<uintptr_t>(p)));
99 }
100 
SetCallStack(TracedValue * value)101 void SetCallStack(TracedValue* value) {
102   static const unsigned char* trace_category_enabled = nullptr;
103   WTF_ANNOTATE_BENIGN_RACE(&trace_category_enabled, "trace_event category");
104   if (!trace_category_enabled)
105     trace_category_enabled = TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
106         TRACE_DISABLED_BY_DEFAULT("devtools.timeline.stack"));
107   if (!*trace_category_enabled)
108     return;
109   // The CPU profiler stack trace does not include call site line numbers.
110   // So we collect the top frame with SourceLocation::capture() to get the
111   // binding call site info.
112   SourceLocation::Capture()->ToTracedValue(value, "stackTrace");
113   v8::CpuProfiler::CollectSample(v8::Isolate::GetCurrent());
114 }
115 
WillSendRequest(uint64_t identifier,DocumentLoader * loader,const KURL & fetch_context_url,const ResourceRequest & request,const ResourceResponse & redirect_response,const FetchInitiatorInfo &,ResourceType)116 void InspectorTraceEvents::WillSendRequest(
117     uint64_t identifier,
118     DocumentLoader* loader,
119     const KURL& fetch_context_url,
120     const ResourceRequest& request,
121     const ResourceResponse& redirect_response,
122     const FetchInitiatorInfo&,
123     ResourceType) {
124   LocalFrame* frame = loader ? loader->GetFrame() : nullptr;
125   TRACE_EVENT_INSTANT1(
126       "devtools.timeline", "ResourceSendRequest", TRACE_EVENT_SCOPE_THREAD,
127       "data",
128       inspector_send_request_event::Data(loader, identifier, frame, request));
129 }
130 
WillSendNavigationRequest(uint64_t identifier,DocumentLoader * loader,const KURL & url,const AtomicString & http_method,EncodedFormData *)131 void InspectorTraceEvents::WillSendNavigationRequest(
132     uint64_t identifier,
133     DocumentLoader* loader,
134     const KURL& url,
135     const AtomicString& http_method,
136     EncodedFormData*) {
137   LocalFrame* frame = loader ? loader->GetFrame() : nullptr;
138   TRACE_EVENT_INSTANT1("devtools.timeline", "ResourceSendRequest",
139                        TRACE_EVENT_SCOPE_THREAD, "data",
140                        inspector_send_navigation_request_event::Data(
141                            loader, identifier, frame, url, http_method));
142 }
143 
DidReceiveResourceResponse(uint64_t identifier,DocumentLoader * loader,const ResourceResponse & response,const Resource *)144 void InspectorTraceEvents::DidReceiveResourceResponse(
145     uint64_t identifier,
146     DocumentLoader* loader,
147     const ResourceResponse& response,
148     const Resource*) {
149   LocalFrame* frame = loader ? loader->GetFrame() : nullptr;
150   TRACE_EVENT_INSTANT1("devtools.timeline", "ResourceReceiveResponse",
151                        TRACE_EVENT_SCOPE_THREAD, "data",
152                        inspector_receive_response_event::Data(
153                            loader, identifier, frame, response));
154 }
155 
DidReceiveData(uint64_t identifier,DocumentLoader * loader,const char * data,uint64_t encoded_data_length)156 void InspectorTraceEvents::DidReceiveData(uint64_t identifier,
157                                           DocumentLoader* loader,
158                                           const char* data,
159                                           uint64_t encoded_data_length) {
160   LocalFrame* frame = loader ? loader->GetFrame() : nullptr;
161   TRACE_EVENT_INSTANT1("devtools.timeline", "ResourceReceivedData",
162                        TRACE_EVENT_SCOPE_THREAD, "data",
163                        inspector_receive_data_event::Data(
164                            loader, identifier, frame, encoded_data_length));
165 }
166 
DidFinishLoading(uint64_t identifier,DocumentLoader * loader,base::TimeTicks finish_time,int64_t encoded_data_length,int64_t decoded_body_length,bool should_report_corb_blocking)167 void InspectorTraceEvents::DidFinishLoading(uint64_t identifier,
168                                             DocumentLoader* loader,
169                                             base::TimeTicks finish_time,
170                                             int64_t encoded_data_length,
171                                             int64_t decoded_body_length,
172                                             bool should_report_corb_blocking) {
173   TRACE_EVENT_INSTANT1(
174       "devtools.timeline", "ResourceFinish", TRACE_EVENT_SCOPE_THREAD, "data",
175       inspector_resource_finish_event::Data(loader, identifier, finish_time,
176                                             false, encoded_data_length,
177                                             decoded_body_length));
178 }
179 
DidFailLoading(uint64_t identifier,DocumentLoader * loader,const ResourceError &)180 void InspectorTraceEvents::DidFailLoading(uint64_t identifier,
181                                           DocumentLoader* loader,
182                                           const ResourceError&) {
183   TRACE_EVENT_INSTANT1("devtools.timeline", "ResourceFinish",
184                        TRACE_EVENT_SCOPE_THREAD, "data",
185                        inspector_resource_finish_event::Data(
186                            loader, identifier, base::TimeTicks(), true, 0, 0));
187 }
188 
MarkResourceAsCached(DocumentLoader * loader,uint64_t identifier)189 void InspectorTraceEvents::MarkResourceAsCached(DocumentLoader* loader,
190                                                 uint64_t identifier) {
191   TRACE_EVENT_INSTANT1(
192       "devtools.timeline", "ResourceMarkAsCached", TRACE_EVENT_SCOPE_THREAD,
193       "data", inspector_mark_resource_cached_event::Data(loader, identifier));
194 }
195 
Will(const probe::ExecuteScript &)196 void InspectorTraceEvents::Will(const probe::ExecuteScript&) {}
197 
Did(const probe::ExecuteScript &)198 void InspectorTraceEvents::Did(const probe::ExecuteScript&) {
199   TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"),
200                        "UpdateCounters", TRACE_EVENT_SCOPE_THREAD, "data",
201                        inspector_update_counters_event::Data());
202 }
203 
Will(const probe::ParseHTML & probe)204 void InspectorTraceEvents::Will(const probe::ParseHTML& probe) {
205   // FIXME: Pass in current input length.
206   TRACE_EVENT_BEGIN1(
207       "devtools.timeline", "ParseHTML", "beginData",
208       InspectorParseHtmlBeginData(probe.parser->GetDocument(),
209                                   probe.parser->LineNumber().ZeroBasedInt()));
210 }
211 
Did(const probe::ParseHTML & probe)212 void InspectorTraceEvents::Did(const probe::ParseHTML& probe) {
213   TRACE_EVENT_END1(
214       "devtools.timeline", "ParseHTML", "endData",
215       InspectorParseHtmlEndData(probe.parser->LineNumber().ZeroBasedInt() - 1));
216   TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"),
217                        "UpdateCounters", TRACE_EVENT_SCOPE_THREAD, "data",
218                        inspector_update_counters_event::Data());
219 }
220 
Will(const probe::CallFunction & probe)221 void InspectorTraceEvents::Will(const probe::CallFunction& probe) {
222 }
223 
Did(const probe::CallFunction & probe)224 void InspectorTraceEvents::Did(const probe::CallFunction& probe) {
225   if (probe.depth)
226     return;
227   TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"),
228                        "UpdateCounters", TRACE_EVENT_SCOPE_THREAD, "data",
229                        inspector_update_counters_event::Data());
230 }
231 
PaintTiming(Document * document,const char * name,double timestamp)232 void InspectorTraceEvents::PaintTiming(Document* document,
233                                        const char* name,
234                                        double timestamp) {
235   TRACE_EVENT_MARK_WITH_TIMESTAMP2("loading,rail,devtools.timeline", name,
236                                    trace_event::ToTraceTimestamp(timestamp),
237                                    "frame", ToTraceValue(document->GetFrame()),
238                                    "data", GetNavigationTracingData(document));
239 }
240 
FrameStartedLoading(LocalFrame * frame)241 void InspectorTraceEvents::FrameStartedLoading(LocalFrame* frame) {
242   TRACE_EVENT_INSTANT1("devtools.timeline", "FrameStartedLoading",
243                        TRACE_EVENT_SCOPE_THREAD, "frame", ToTraceValue(frame));
244 }
245 
246 namespace {
247 
SetNodeInfo(TracedValue * value,Node * node,const char * id_field_name,const char * name_field_name=nullptr)248 void SetNodeInfo(TracedValue* value,
249                  Node* node,
250                  const char* id_field_name,
251                  const char* name_field_name = nullptr) {
252   value->SetIntegerWithCopiedName(id_field_name,
253                                   IdentifiersFactory::IntIdForNode(node));
254   if (name_field_name)
255     value->SetStringWithCopiedName(name_field_name, node->DebugName());
256 }
257 
PseudoTypeToString(CSSSelector::PseudoType pseudo_type)258 const char* PseudoTypeToString(CSSSelector::PseudoType pseudo_type) {
259   switch (pseudo_type) {
260 #define DEFINE_STRING_MAPPING(pseudoType) \
261   case CSSSelector::k##pseudoType:        \
262     return #pseudoType;
263     DEFINE_STRING_MAPPING(PseudoUnknown)
264     DEFINE_STRING_MAPPING(PseudoEmpty)
265     DEFINE_STRING_MAPPING(PseudoFirstChild)
266     DEFINE_STRING_MAPPING(PseudoFirstOfType)
267     DEFINE_STRING_MAPPING(PseudoLastChild)
268     DEFINE_STRING_MAPPING(PseudoLastOfType)
269     DEFINE_STRING_MAPPING(PseudoOnlyChild)
270     DEFINE_STRING_MAPPING(PseudoOnlyOfType)
271     DEFINE_STRING_MAPPING(PseudoFirstLine)
272     DEFINE_STRING_MAPPING(PseudoFirstLetter)
273     DEFINE_STRING_MAPPING(PseudoNthChild)
274     DEFINE_STRING_MAPPING(PseudoNthOfType)
275     DEFINE_STRING_MAPPING(PseudoNthLastChild)
276     DEFINE_STRING_MAPPING(PseudoNthLastOfType)
277     DEFINE_STRING_MAPPING(PseudoPart)
278     DEFINE_STRING_MAPPING(PseudoState)
279     DEFINE_STRING_MAPPING(PseudoLink)
280     DEFINE_STRING_MAPPING(PseudoVisited)
281     DEFINE_STRING_MAPPING(PseudoAny)
282     DEFINE_STRING_MAPPING(PseudoIs)
283     DEFINE_STRING_MAPPING(PseudoWhere)
284     DEFINE_STRING_MAPPING(PseudoWebkitAnyLink)
285     DEFINE_STRING_MAPPING(PseudoAnyLink)
286     DEFINE_STRING_MAPPING(PseudoAutofill)
287     DEFINE_STRING_MAPPING(PseudoAutofillPreviewed)
288     DEFINE_STRING_MAPPING(PseudoAutofillSelected)
289     DEFINE_STRING_MAPPING(PseudoHover)
290     DEFINE_STRING_MAPPING(PseudoDrag)
291     DEFINE_STRING_MAPPING(PseudoFocus)
292     DEFINE_STRING_MAPPING(PseudoFocusVisible)
293     DEFINE_STRING_MAPPING(PseudoFocusWithin)
294     DEFINE_STRING_MAPPING(PseudoActive)
295     DEFINE_STRING_MAPPING(PseudoChecked)
296     DEFINE_STRING_MAPPING(PseudoEnabled)
297     DEFINE_STRING_MAPPING(PseudoFullPageMedia)
298     DEFINE_STRING_MAPPING(PseudoDefault)
299     DEFINE_STRING_MAPPING(PseudoDisabled)
300     DEFINE_STRING_MAPPING(PseudoOptional)
301     DEFINE_STRING_MAPPING(PseudoPlaceholderShown)
302     DEFINE_STRING_MAPPING(PseudoRequired)
303     DEFINE_STRING_MAPPING(PseudoReadOnly)
304     DEFINE_STRING_MAPPING(PseudoReadWrite)
305     DEFINE_STRING_MAPPING(PseudoValid)
306     DEFINE_STRING_MAPPING(PseudoInvalid)
307     DEFINE_STRING_MAPPING(PseudoIndeterminate)
308     DEFINE_STRING_MAPPING(PseudoTarget)
309     DEFINE_STRING_MAPPING(PseudoBefore)
310     DEFINE_STRING_MAPPING(PseudoAfter)
311     DEFINE_STRING_MAPPING(PseudoMarker)
312     DEFINE_STRING_MAPPING(PseudoBackdrop)
313     DEFINE_STRING_MAPPING(PseudoLang)
314     DEFINE_STRING_MAPPING(PseudoNot)
315     DEFINE_STRING_MAPPING(PseudoPlaceholder)
316     DEFINE_STRING_MAPPING(PseudoResizer)
317     DEFINE_STRING_MAPPING(PseudoRoot)
318     DEFINE_STRING_MAPPING(PseudoScope)
319     DEFINE_STRING_MAPPING(PseudoScrollbar)
320     DEFINE_STRING_MAPPING(PseudoScrollbarButton)
321     DEFINE_STRING_MAPPING(PseudoScrollbarCorner)
322     DEFINE_STRING_MAPPING(PseudoScrollbarThumb)
323     DEFINE_STRING_MAPPING(PseudoScrollbarTrack)
324     DEFINE_STRING_MAPPING(PseudoScrollbarTrackPiece)
325     DEFINE_STRING_MAPPING(PseudoWindowInactive)
326     DEFINE_STRING_MAPPING(PseudoCornerPresent)
327     DEFINE_STRING_MAPPING(PseudoDecrement)
328     DEFINE_STRING_MAPPING(PseudoIncrement)
329     DEFINE_STRING_MAPPING(PseudoHorizontal)
330     DEFINE_STRING_MAPPING(PseudoVertical)
331     DEFINE_STRING_MAPPING(PseudoStart)
332     DEFINE_STRING_MAPPING(PseudoEnd)
333     DEFINE_STRING_MAPPING(PseudoDoubleButton)
334     DEFINE_STRING_MAPPING(PseudoSingleButton)
335     DEFINE_STRING_MAPPING(PseudoNoButton)
336     DEFINE_STRING_MAPPING(PseudoSelection)
337     DEFINE_STRING_MAPPING(PseudoLeftPage)
338     DEFINE_STRING_MAPPING(PseudoRightPage)
339     DEFINE_STRING_MAPPING(PseudoFirstPage)
340     DEFINE_STRING_MAPPING(PseudoFullScreen)
341     DEFINE_STRING_MAPPING(PseudoFullScreenAncestor)
342     DEFINE_STRING_MAPPING(PseudoFullscreen)
343     DEFINE_STRING_MAPPING(PseudoPictureInPicture)
344     DEFINE_STRING_MAPPING(PseudoInRange)
345     DEFINE_STRING_MAPPING(PseudoOutOfRange)
346     DEFINE_STRING_MAPPING(PseudoWebKitCustomElement)
347     DEFINE_STRING_MAPPING(PseudoBlinkInternalElement)
348     DEFINE_STRING_MAPPING(PseudoCue)
349     DEFINE_STRING_MAPPING(PseudoFutureCue)
350     DEFINE_STRING_MAPPING(PseudoPastCue)
351     DEFINE_STRING_MAPPING(PseudoUnresolved)
352     DEFINE_STRING_MAPPING(PseudoDefined)
353     DEFINE_STRING_MAPPING(PseudoContent)
354     DEFINE_STRING_MAPPING(PseudoHost)
355     DEFINE_STRING_MAPPING(PseudoHostContext)
356     DEFINE_STRING_MAPPING(PseudoShadow)
357     DEFINE_STRING_MAPPING(PseudoSlotted)
358     DEFINE_STRING_MAPPING(PseudoSpatialNavigationFocus)
359     DEFINE_STRING_MAPPING(PseudoSpatialNavigationInterest)
360     DEFINE_STRING_MAPPING(PseudoIsHtml)
361     DEFINE_STRING_MAPPING(PseudoListBox)
362     DEFINE_STRING_MAPPING(PseudoMultiSelectFocus)
363     DEFINE_STRING_MAPPING(PseudoHostHasAppearance)
364     DEFINE_STRING_MAPPING(PseudoVideoPersistent)
365     DEFINE_STRING_MAPPING(PseudoVideoPersistentAncestor)
366     DEFINE_STRING_MAPPING(PseudoXrOverlay)
367 #undef DEFINE_STRING_MAPPING
368   }
369 
370   NOTREACHED();
371   return "";
372 }
373 
UrlForFrame(LocalFrame * frame)374 String UrlForFrame(LocalFrame* frame) {
375   KURL url = frame->GetDocument()->Url();
376   url.RemoveFragmentIdentifier();
377   return url.GetString();
378 }
379 
CompileOptionsString(v8::ScriptCompiler::CompileOptions options)380 const char* CompileOptionsString(v8::ScriptCompiler::CompileOptions options) {
381   switch (options) {
382     case v8::ScriptCompiler::kNoCompileOptions:
383       return "code";
384     case v8::ScriptCompiler::kConsumeCodeCache:
385       return "code";
386     case v8::ScriptCompiler::kEagerCompile:
387       return "full code";
388   }
389   NOTREACHED();
390   return "";
391 }
392 
NotStreamedReasonString(ScriptStreamer::NotStreamingReason reason)393 const char* NotStreamedReasonString(ScriptStreamer::NotStreamingReason reason) {
394   switch (reason) {
395     case ScriptStreamer::kNotHTTP:
396       return "not http/https protocol";
397     case ScriptStreamer::kRevalidate:
398       return "revalidation event";
399     case ScriptStreamer::kContextNotValid:
400       return "script context not valid";
401     case ScriptStreamer::kEncodingNotSupported:
402       return "encoding not supported";
403     case ScriptStreamer::kThreadBusy:
404       return "script streamer thread busy";
405     case ScriptStreamer::kV8CannotStream:
406       return "V8 cannot stream script";
407     case ScriptStreamer::kScriptTooSmall:
408       return "script too small";
409     case ScriptStreamer::kNoResourceBuffer:
410       return "resource no longer alive";
411     case ScriptStreamer::kHasCodeCache:
412       return "script has code-cache available";
413     case ScriptStreamer::kStreamerNotReadyOnGetSource:
414       return "streamer not ready";
415     case ScriptStreamer::kInlineScript:
416       return "inline script";
417     case ScriptStreamer::kDidntTryToStartStreaming:
418       return "start streaming not called";
419     case ScriptStreamer::kErrorOccurred:
420       return "an error occurred";
421     case ScriptStreamer::kStreamingDisabled:
422       return "already disabled streaming";
423     case ScriptStreamer::kSecondScriptResourceUse:
424       return "already used streamed data";
425     case ScriptStreamer::kWorkerTopLevelScript:
426       return "worker top-level scripts are not streamable";
427     case ScriptStreamer::kModuleScript:
428       return "module script";
429     case ScriptStreamer::kAlreadyLoaded:
430     case ScriptStreamer::kCount:
431     case ScriptStreamer::kInvalid:
432       NOTREACHED();
433   }
434   NOTREACHED();
435   return "";
436 }
437 
438 }  // namespace
439 
440 namespace inspector_schedule_style_invalidation_tracking_event {
FillCommonPart(ContainerNode & node,const InvalidationSet & invalidation_set,const char * invalidated_selector)441 std::unique_ptr<TracedValue> FillCommonPart(
442     ContainerNode& node,
443     const InvalidationSet& invalidation_set,
444     const char* invalidated_selector) {
445   auto value = std::make_unique<TracedValue>();
446   value->SetString("frame",
447                    IdentifiersFactory::FrameId(node.GetDocument().GetFrame()));
448   SetNodeInfo(value.get(), &node, "nodeId", "nodeName");
449   value->SetString("invalidationSet",
450                    DescendantInvalidationSetToIdString(invalidation_set));
451   value->SetString("invalidatedSelectorId", invalidated_selector);
452   SourceLocation::Capture()->ToTracedValue(value.get(), "stackTrace");
453   return value;
454 }
455 }  // namespace inspector_schedule_style_invalidation_tracking_event
456 
457 const char inspector_schedule_style_invalidation_tracking_event::kAttribute[] =
458     "attribute";
459 const char inspector_schedule_style_invalidation_tracking_event::kClass[] =
460     "class";
461 const char inspector_schedule_style_invalidation_tracking_event::kId[] = "id";
462 const char inspector_schedule_style_invalidation_tracking_event::kPseudo[] =
463     "pseudo";
464 const char inspector_schedule_style_invalidation_tracking_event::kRuleSet[] =
465     "ruleset";
466 
ResourcePriorityString(ResourceLoadPriority priority)467 const char* ResourcePriorityString(ResourceLoadPriority priority) {
468   const char* priority_string = nullptr;
469   switch (priority) {
470     case ResourceLoadPriority::kVeryLow:
471       priority_string = "VeryLow";
472       break;
473     case ResourceLoadPriority::kLow:
474       priority_string = "Low";
475       break;
476     case ResourceLoadPriority::kMedium:
477       priority_string = "Medium";
478       break;
479     case ResourceLoadPriority::kHigh:
480       priority_string = "High";
481       break;
482     case ResourceLoadPriority::kVeryHigh:
483       priority_string = "VeryHigh";
484       break;
485     case ResourceLoadPriority::kUnresolved:
486       break;
487   }
488   return priority_string;
489 }
490 
491 std::unique_ptr<TracedValue>
IdChange(Element & element,const InvalidationSet & invalidation_set,const AtomicString & id)492 inspector_schedule_style_invalidation_tracking_event::IdChange(
493     Element& element,
494     const InvalidationSet& invalidation_set,
495     const AtomicString& id) {
496   std::unique_ptr<TracedValue> value =
497       FillCommonPart(element, invalidation_set, kId);
498   value->SetString("changedId", id);
499   return value;
500 }
501 
502 std::unique_ptr<TracedValue>
ClassChange(Element & element,const InvalidationSet & invalidation_set,const AtomicString & class_name)503 inspector_schedule_style_invalidation_tracking_event::ClassChange(
504     Element& element,
505     const InvalidationSet& invalidation_set,
506     const AtomicString& class_name) {
507   std::unique_ptr<TracedValue> value =
508       FillCommonPart(element, invalidation_set, kClass);
509   value->SetString("changedClass", class_name);
510   return value;
511 }
512 
513 std::unique_ptr<TracedValue>
AttributeChange(Element & element,const InvalidationSet & invalidation_set,const QualifiedName & attribute_name)514 inspector_schedule_style_invalidation_tracking_event::AttributeChange(
515     Element& element,
516     const InvalidationSet& invalidation_set,
517     const QualifiedName& attribute_name) {
518   std::unique_ptr<TracedValue> value =
519       FillCommonPart(element, invalidation_set, kAttribute);
520   value->SetString("changedAttribute", attribute_name.ToString());
521   return value;
522 }
523 
524 std::unique_ptr<TracedValue>
PseudoChange(Element & element,const InvalidationSet & invalidation_set,CSSSelector::PseudoType pseudo_type)525 inspector_schedule_style_invalidation_tracking_event::PseudoChange(
526     Element& element,
527     const InvalidationSet& invalidation_set,
528     CSSSelector::PseudoType pseudo_type) {
529   std::unique_ptr<TracedValue> value =
530       FillCommonPart(element, invalidation_set, kAttribute);
531   value->SetString("changedPseudo", PseudoTypeToString(pseudo_type));
532   return value;
533 }
534 
535 std::unique_ptr<TracedValue>
RuleSetInvalidation(ContainerNode & root_node,const InvalidationSet & invalidation_set)536 inspector_schedule_style_invalidation_tracking_event::RuleSetInvalidation(
537     ContainerNode& root_node,
538     const InvalidationSet& invalidation_set) {
539   std::unique_ptr<TracedValue> value =
540       FillCommonPart(root_node, invalidation_set, kRuleSet);
541   return value;
542 }
543 
DescendantInvalidationSetToIdString(const InvalidationSet & set)544 String DescendantInvalidationSetToIdString(const InvalidationSet& set) {
545   return ToHexString(&set);
546 }
547 
548 const char inspector_style_invalidator_invalidate_event::
549     kElementHasPendingInvalidationList[] =
550         "Element has pending invalidation list";
551 const char
552     inspector_style_invalidator_invalidate_event::kInvalidateCustomPseudo[] =
553         "Invalidate custom pseudo element";
554 const char inspector_style_invalidator_invalidate_event::
555     kInvalidationSetMatchedAttribute[] = "Invalidation set matched attribute";
556 const char inspector_style_invalidator_invalidate_event::
557     kInvalidationSetMatchedClass[] = "Invalidation set matched class";
558 const char
559     inspector_style_invalidator_invalidate_event::kInvalidationSetMatchedId[] =
560         "Invalidation set matched id";
561 const char inspector_style_invalidator_invalidate_event::
562     kInvalidationSetMatchedTagName[] = "Invalidation set matched tagName";
563 const char inspector_style_invalidator_invalidate_event::
564     kInvalidationSetMatchedPart[] = "Invalidation set matched part";
565 
566 namespace inspector_style_invalidator_invalidate_event {
FillCommonPart(ContainerNode & node,const char * reason)567 std::unique_ptr<TracedValue> FillCommonPart(ContainerNode& node,
568                                             const char* reason) {
569   auto value = std::make_unique<TracedValue>();
570   value->SetString("frame",
571                    IdentifiersFactory::FrameId(node.GetDocument().GetFrame()));
572   SetNodeInfo(value.get(), &node, "nodeId", "nodeName");
573   value->SetString("reason", reason);
574   return value;
575 }
576 }  // namespace inspector_style_invalidator_invalidate_event
577 
Data(Element & element,const char * reason)578 std::unique_ptr<TracedValue> inspector_style_invalidator_invalidate_event::Data(
579     Element& element,
580     const char* reason) {
581   return FillCommonPart(element, reason);
582 }
583 
584 std::unique_ptr<TracedValue>
SelectorPart(Element & element,const char * reason,const InvalidationSet & invalidation_set,const String & selector_part)585 inspector_style_invalidator_invalidate_event::SelectorPart(
586     Element& element,
587     const char* reason,
588     const InvalidationSet& invalidation_set,
589     const String& selector_part) {
590   std::unique_ptr<TracedValue> value = FillCommonPart(element, reason);
591   value->BeginArray("invalidationList");
592   invalidation_set.ToTracedValue(value.get());
593   value->EndArray();
594   value->SetString("selectorPart", selector_part);
595   return value;
596 }
597 
598 std::unique_ptr<TracedValue>
InvalidationList(ContainerNode & node,const Vector<scoped_refptr<InvalidationSet>> & invalidation_list)599 inspector_style_invalidator_invalidate_event::InvalidationList(
600     ContainerNode& node,
601     const Vector<scoped_refptr<InvalidationSet>>& invalidation_list) {
602   std::unique_ptr<TracedValue> value =
603       FillCommonPart(node, kElementHasPendingInvalidationList);
604   value->BeginArray("invalidationList");
605   for (const auto& invalidation_set : invalidation_list)
606     invalidation_set->ToTracedValue(value.get());
607   value->EndArray();
608   return value;
609 }
610 
611 std::unique_ptr<TracedValue>
Data(Node * node,StyleChangeType change_type,const StyleChangeReasonForTracing & reason)612 inspector_style_recalc_invalidation_tracking_event::Data(
613     Node* node,
614     StyleChangeType change_type,
615     const StyleChangeReasonForTracing& reason) {
616   DCHECK(node);
617 
618   auto value = std::make_unique<TracedValue>();
619   value->SetString("frame",
620                    IdentifiersFactory::FrameId(node->GetDocument().GetFrame()));
621   SetNodeInfo(value.get(), node, "nodeId", "nodeName");
622   value->SetBoolean("subtree", change_type == kSubtreeStyleChange);
623   value->SetString("reason", reason.ReasonString());
624   value->SetString("extraData", reason.GetExtraData());
625   SourceLocation::Capture()->ToTracedValue(value.get(), "stackTrace");
626   return value;
627 }
628 
BeginData(LocalFrameView * frame_view)629 std::unique_ptr<TracedValue> inspector_layout_event::BeginData(
630     LocalFrameView* frame_view) {
631   bool is_partial;
632   unsigned needs_layout_objects;
633   unsigned total_objects;
634   LocalFrame& frame = frame_view->GetFrame();
635   frame.View()->CountObjectsNeedingLayout(needs_layout_objects, total_objects,
636                                           is_partial);
637 
638   auto value = std::make_unique<TracedValue>();
639   value->SetInteger("dirtyObjects", needs_layout_objects);
640   value->SetInteger("totalObjects", total_objects);
641   value->SetBoolean("partialLayout", is_partial);
642   value->SetString("frame", IdentifiersFactory::FrameId(&frame));
643   SetCallStack(value.get());
644   return value;
645 }
646 
CreateQuad(TracedValue * value,const char * name,const FloatQuad & quad)647 static void CreateQuad(TracedValue* value,
648                        const char* name,
649                        const FloatQuad& quad) {
650   value->BeginArray(name);
651   value->PushDouble(quad.P1().X());
652   value->PushDouble(quad.P1().Y());
653   value->PushDouble(quad.P2().X());
654   value->PushDouble(quad.P2().Y());
655   value->PushDouble(quad.P3().X());
656   value->PushDouble(quad.P3().Y());
657   value->PushDouble(quad.P4().X());
658   value->PushDouble(quad.P4().Y());
659   value->EndArray();
660 }
661 
SetGeneratingNodeInfo(TracedValue * value,const LayoutObject * layout_object,const char * id_field_name,const char * name_field_name=nullptr)662 static void SetGeneratingNodeInfo(TracedValue* value,
663                                   const LayoutObject* layout_object,
664                                   const char* id_field_name,
665                                   const char* name_field_name = nullptr) {
666   Node* node = nullptr;
667   for (; layout_object && !node; layout_object = layout_object->Parent())
668     node = layout_object->GeneratingNode();
669   if (!node)
670     return;
671 
672   SetNodeInfo(value, node, id_field_name, name_field_name);
673 }
674 
EndData(LayoutObject * root_for_this_layout)675 std::unique_ptr<TracedValue> inspector_layout_event::EndData(
676     LayoutObject* root_for_this_layout) {
677   Vector<FloatQuad> quads;
678   root_for_this_layout->AbsoluteQuads(quads);
679 
680   auto value = std::make_unique<TracedValue>();
681   if (quads.size() >= 1) {
682     CreateQuad(value.get(), "root", quads[0]);
683     SetGeneratingNodeInfo(value.get(), root_for_this_layout, "rootNode");
684   } else {
685     NOTREACHED();
686   }
687   return value;
688 }
689 
690 namespace layout_invalidation_reason {
691 const char kUnknown[] = "Unknown";
692 const char kSizeChanged[] = "Size changed";
693 const char kAncestorMoved[] = "Ancestor moved";
694 const char kStyleChange[] = "Style changed";
695 const char kDomChanged[] = "DOM changed";
696 const char kTextChanged[] = "Text changed";
697 const char kPrintingChanged[] = "Printing changed";
698 const char kAttributeChanged[] = "Attribute changed";
699 const char kColumnsChanged[] = "Attribute changed";
700 const char kChildAnonymousBlockChanged[] = "Child anonymous block changed";
701 const char kAnonymousBlockChange[] = "Anonymous block change";
702 const char kFontsChanged[] = "Fonts changed";
703 const char kFullscreen[] = "Fullscreen change";
704 const char kChildChanged[] = "Child changed";
705 const char kListValueChange[] = "List value change";
706 const char kListStyleTypeChange[] = "List style type change";
707 const char kImageChanged[] = "Image changed";
708 const char kLineBoxesChanged[] = "Line boxes changed";
709 const char kSliderValueChanged[] = "Slider value changed";
710 const char kAncestorMarginCollapsing[] = "Ancestor margin collapsing";
711 const char kFieldsetChanged[] = "Fieldset changed";
712 const char kTextAutosizing[] = "Text autosizing (font boosting)";
713 const char kSvgResourceInvalidated[] = "SVG resource invalidated";
714 const char kFloatDescendantChanged[] = "Floating descendant changed";
715 const char kCountersChanged[] = "Counters changed";
716 const char kGridChanged[] = "Grid changed";
717 const char kMenuOptionsChanged[] = "Menu options changed";
718 const char kRemovedFromLayout[] = "Removed from layout";
719 const char kAddedToLayout[] = "Added to layout";
720 const char kTableChanged[] = "Table changed";
721 const char kPaddingChanged[] = "Padding changed";
722 const char kTextControlChanged[] = "Text control changed";
723 const char kSvgChanged[] = "SVG changed";
724 const char kScrollbarChanged[] = "Scrollbar changed";
725 const char kDisplayLock[] = "Display lock";
726 }  // namespace layout_invalidation_reason
727 
Data(const LayoutObject * layout_object,LayoutInvalidationReasonForTracing reason)728 std::unique_ptr<TracedValue> inspector_layout_invalidation_tracking_event::Data(
729     const LayoutObject* layout_object,
730     LayoutInvalidationReasonForTracing reason) {
731   DCHECK(layout_object);
732   auto value = std::make_unique<TracedValue>();
733   value->SetString("frame",
734                    IdentifiersFactory::FrameId(layout_object->GetFrame()));
735   SetGeneratingNodeInfo(value.get(), layout_object, "nodeId", "nodeName");
736   value->SetString("reason", reason);
737   SourceLocation::Capture()->ToTracedValue(value.get(), "stackTrace");
738   return value;
739 }
740 
Data(DocumentLoader * loader,uint64_t identifier,const ResourceLoadPriority & load_priority)741 std::unique_ptr<TracedValue> inspector_change_resource_priority_event::Data(
742     DocumentLoader* loader,
743     uint64_t identifier,
744     const ResourceLoadPriority& load_priority) {
745   String request_id = IdentifiersFactory::RequestId(loader, identifier);
746 
747   auto value = std::make_unique<TracedValue>();
748   value->SetString("requestId", request_id);
749   value->SetString("priority", ResourcePriorityString(load_priority));
750   return value;
751 }
752 
Data(DocumentLoader * loader,uint64_t identifier,LocalFrame * frame,const ResourceRequest & request)753 std::unique_ptr<TracedValue> inspector_send_request_event::Data(
754     DocumentLoader* loader,
755     uint64_t identifier,
756     LocalFrame* frame,
757     const ResourceRequest& request) {
758   auto value = std::make_unique<TracedValue>();
759   value->SetString("requestId",
760                    IdentifiersFactory::RequestId(loader, identifier));
761   value->SetString("frame", IdentifiersFactory::FrameId(frame));
762   value->SetString("url", request.Url().GetString());
763   value->SetString("requestMethod", request.HttpMethod());
764   const char* priority = ResourcePriorityString(request.Priority());
765   if (priority)
766     value->SetString("priority", priority);
767   SetCallStack(value.get());
768   return value;
769 }
770 
Data(DocumentLoader * loader,uint64_t identifier,LocalFrame * frame,const KURL & url,const AtomicString & http_method)771 std::unique_ptr<TracedValue> inspector_send_navigation_request_event::Data(
772     DocumentLoader* loader,
773     uint64_t identifier,
774     LocalFrame* frame,
775     const KURL& url,
776     const AtomicString& http_method) {
777   auto value = std::make_unique<TracedValue>();
778   value->SetString("requestId", IdentifiersFactory::LoaderId(loader));
779   value->SetString("frame", IdentifiersFactory::FrameId(frame));
780   value->SetString("url", url.GetString());
781   value->SetString("requestMethod", http_method);
782   const char* priority =
783       ResourcePriorityString(ResourceLoadPriority::kVeryHigh);
784   if (priority)
785     value->SetString("priority", priority);
786   SetCallStack(value.get());
787   return value;
788 }
789 
790 namespace {
RecordTiming(const ResourceLoadTiming & timing,TracedValue * value)791 void RecordTiming(const ResourceLoadTiming& timing, TracedValue* value) {
792   value->SetDouble("requestTime",
793                    timing.RequestTime().since_origin().InSecondsF());
794   value->SetDouble("proxyStart",
795                    timing.CalculateMillisecondDelta(timing.ProxyStart()));
796   value->SetDouble("proxyEnd",
797                    timing.CalculateMillisecondDelta(timing.ProxyEnd()));
798   value->SetDouble("dnsStart",
799                    timing.CalculateMillisecondDelta(timing.DnsStart()));
800   value->SetDouble("dnsEnd", timing.CalculateMillisecondDelta(timing.DnsEnd()));
801   value->SetDouble("connectStart",
802                    timing.CalculateMillisecondDelta(timing.ConnectStart()));
803   value->SetDouble("connectEnd",
804                    timing.CalculateMillisecondDelta(timing.ConnectEnd()));
805   value->SetDouble("sslStart",
806                    timing.CalculateMillisecondDelta(timing.SslStart()));
807   value->SetDouble("sslEnd", timing.CalculateMillisecondDelta(timing.SslEnd()));
808   value->SetDouble("workerStart",
809                    timing.CalculateMillisecondDelta(timing.WorkerStart()));
810   value->SetDouble("workerReady",
811                    timing.CalculateMillisecondDelta(timing.WorkerReady()));
812   value->SetDouble("sendStart",
813                    timing.CalculateMillisecondDelta(timing.SendStart()));
814   value->SetDouble("sendEnd",
815                    timing.CalculateMillisecondDelta(timing.SendEnd()));
816   value->SetDouble("receiveHeadersEnd", timing.CalculateMillisecondDelta(
817                                             timing.ReceiveHeadersEnd()));
818   value->SetDouble("pushStart", timing.PushStart().since_origin().InSecondsF());
819   value->SetDouble("pushEnd", timing.PushEnd().since_origin().InSecondsF());
820 }
821 }  // namespace
822 
Data(DocumentLoader * loader,uint64_t identifier,LocalFrame * frame,const ResourceResponse & response)823 std::unique_ptr<TracedValue> inspector_receive_response_event::Data(
824     DocumentLoader* loader,
825     uint64_t identifier,
826     LocalFrame* frame,
827     const ResourceResponse& response) {
828   String request_id = IdentifiersFactory::RequestId(loader, identifier);
829 
830   auto value = std::make_unique<TracedValue>();
831   value->SetString("requestId", request_id);
832   value->SetString("frame", IdentifiersFactory::FrameId(frame));
833   value->SetInteger("statusCode", response.HttpStatusCode());
834   value->SetString("mimeType", response.MimeType().GetString().IsolatedCopy());
835   value->SetDouble("encodedDataLength", response.EncodedDataLength());
836   value->SetBoolean("fromCache", response.WasCached());
837   value->SetBoolean("fromServiceWorker", response.WasFetchedViaServiceWorker());
838   if (response.GetResourceLoadTiming()) {
839     value->BeginDictionary("timing");
840     RecordTiming(*response.GetResourceLoadTiming(), value.get());
841     value->EndDictionary();
842   }
843   if (response.WasFetchedViaServiceWorker())
844     value->SetBoolean("fromServiceWorker", true);
845   return value;
846 }
847 
Data(DocumentLoader * loader,uint64_t identifier,LocalFrame * frame,uint64_t encoded_data_length)848 std::unique_ptr<TracedValue> inspector_receive_data_event::Data(
849     DocumentLoader* loader,
850     uint64_t identifier,
851     LocalFrame* frame,
852     uint64_t encoded_data_length) {
853   String request_id = IdentifiersFactory::RequestId(loader, identifier);
854 
855   auto value = std::make_unique<TracedValue>();
856   value->SetString("requestId", request_id);
857   value->SetString("frame", IdentifiersFactory::FrameId(frame));
858   value->SetDouble("encodedDataLength", encoded_data_length);
859   return value;
860 }
861 
Data(DocumentLoader * loader,uint64_t identifier,base::TimeTicks finish_time,bool did_fail,int64_t encoded_data_length,int64_t decoded_body_length)862 std::unique_ptr<TracedValue> inspector_resource_finish_event::Data(
863     DocumentLoader* loader,
864     uint64_t identifier,
865     base::TimeTicks finish_time,
866     bool did_fail,
867     int64_t encoded_data_length,
868     int64_t decoded_body_length) {
869   String request_id = IdentifiersFactory::RequestId(loader, identifier);
870 
871   auto value = std::make_unique<TracedValue>();
872   value->SetString("requestId", request_id);
873   value->SetBoolean("didFail", did_fail);
874   value->SetDouble("encodedDataLength", encoded_data_length);
875   value->SetDouble("decodedBodyLength", decoded_body_length);
876   if (!finish_time.is_null())
877     value->SetDouble("finishTime", finish_time.since_origin().InSecondsF());
878   return value;
879 }
880 
Data(DocumentLoader * loader,uint64_t identifier)881 std::unique_ptr<TracedValue> inspector_mark_resource_cached_event::Data(
882     DocumentLoader* loader,
883     uint64_t identifier) {
884   auto value = std::make_unique<TracedValue>();
885   String request_id = IdentifiersFactory::RequestId(loader, identifier);
886   value->SetString("requestId", request_id);
887   return value;
888 }
889 
FrameForExecutionContext(ExecutionContext * context)890 static LocalFrame* FrameForExecutionContext(ExecutionContext* context) {
891   if (auto* window = DynamicTo<LocalDOMWindow>(context))
892     return window->GetFrame();
893   return nullptr;
894 }
895 
GenericTimerData(ExecutionContext * context,int timer_id)896 static std::unique_ptr<TracedValue> GenericTimerData(ExecutionContext* context,
897                                                      int timer_id) {
898   auto value = std::make_unique<TracedValue>();
899   value->SetInteger("timerId", timer_id);
900   if (LocalFrame* frame = FrameForExecutionContext(context))
901     value->SetString("frame", IdentifiersFactory::FrameId(frame));
902   return value;
903 }
904 
Data(ExecutionContext * context,int timer_id,base::TimeDelta timeout,bool single_shot)905 std::unique_ptr<TracedValue> inspector_timer_install_event::Data(
906     ExecutionContext* context,
907     int timer_id,
908     base::TimeDelta timeout,
909     bool single_shot) {
910   std::unique_ptr<TracedValue> value = GenericTimerData(context, timer_id);
911   value->SetDouble("timeout", timeout.InMillisecondsF());
912   value->SetBoolean("singleShot", single_shot);
913   SetCallStack(value.get());
914   return value;
915 }
916 
Data(ExecutionContext * context,int timer_id)917 std::unique_ptr<TracedValue> inspector_timer_remove_event::Data(
918     ExecutionContext* context,
919     int timer_id) {
920   std::unique_ptr<TracedValue> value = GenericTimerData(context, timer_id);
921   SetCallStack(value.get());
922   return value;
923 }
924 
Data(ExecutionContext * context,int timer_id)925 std::unique_ptr<TracedValue> inspector_timer_fire_event::Data(
926     ExecutionContext* context,
927     int timer_id) {
928   return GenericTimerData(context, timer_id);
929 }
930 
Data(ExecutionContext * context,int callback_id)931 std::unique_ptr<TracedValue> inspector_animation_frame_event::Data(
932     ExecutionContext* context,
933     int callback_id) {
934   auto value = std::make_unique<TracedValue>();
935   value->SetInteger("id", callback_id);
936   if (auto* window = DynamicTo<LocalDOMWindow>(context)) {
937     value->SetString("frame", IdentifiersFactory::FrameId(window->GetFrame()));
938   } else if (auto* scope = DynamicTo<WorkerGlobalScope>(context)) {
939     value->SetString("worker", ToHexString(scope));
940   }
941   SetCallStack(value.get());
942   return value;
943 }
944 
GenericIdleCallbackEvent(ExecutionContext * context,int id)945 std::unique_ptr<TracedValue> GenericIdleCallbackEvent(ExecutionContext* context,
946                                                       int id) {
947   auto value = std::make_unique<TracedValue>();
948   value->SetInteger("id", id);
949   if (LocalFrame* frame = FrameForExecutionContext(context))
950     value->SetString("frame", IdentifiersFactory::FrameId(frame));
951   SetCallStack(value.get());
952   return value;
953 }
954 
Data(ExecutionContext * context,int id,double timeout)955 std::unique_ptr<TracedValue> inspector_idle_callback_request_event::Data(
956     ExecutionContext* context,
957     int id,
958     double timeout) {
959   std::unique_ptr<TracedValue> value = GenericIdleCallbackEvent(context, id);
960   value->SetInteger("timeout", timeout);
961   return value;
962 }
963 
Data(ExecutionContext * context,int id)964 std::unique_ptr<TracedValue> inspector_idle_callback_cancel_event::Data(
965     ExecutionContext* context,
966     int id) {
967   return GenericIdleCallbackEvent(context, id);
968 }
969 
Data(ExecutionContext * context,int id,double allotted_milliseconds,bool timed_out)970 std::unique_ptr<TracedValue> inspector_idle_callback_fire_event::Data(
971     ExecutionContext* context,
972     int id,
973     double allotted_milliseconds,
974     bool timed_out) {
975   std::unique_ptr<TracedValue> value = GenericIdleCallbackEvent(context, id);
976   value->SetDouble("allottedMilliseconds", allotted_milliseconds);
977   value->SetBoolean("timedOut", timed_out);
978   return value;
979 }
980 
Data(const CSSStyleSheetResource * cached_style_sheet)981 std::unique_ptr<TracedValue> inspector_parse_author_style_sheet_event::Data(
982     const CSSStyleSheetResource* cached_style_sheet) {
983   auto value = std::make_unique<TracedValue>();
984   value->SetString("styleSheetUrl", cached_style_sheet->Url().GetString());
985   return value;
986 }
987 
Data(ExecutionContext * context,XMLHttpRequest * request)988 std::unique_ptr<TracedValue> inspector_xhr_ready_state_change_event::Data(
989     ExecutionContext* context,
990     XMLHttpRequest* request) {
991   auto value = std::make_unique<TracedValue>();
992   value->SetString("url", request->Url().GetString());
993   value->SetInteger("readyState", request->readyState());
994   if (LocalFrame* frame = FrameForExecutionContext(context))
995     value->SetString("frame", IdentifiersFactory::FrameId(frame));
996   SetCallStack(value.get());
997   return value;
998 }
999 
Data(ExecutionContext * context,XMLHttpRequest * request)1000 std::unique_ptr<TracedValue> inspector_xhr_load_event::Data(
1001     ExecutionContext* context,
1002     XMLHttpRequest* request) {
1003   auto value = std::make_unique<TracedValue>();
1004   value->SetString("url", request->Url().GetString());
1005   if (LocalFrame* frame = FrameForExecutionContext(context))
1006     value->SetString("frame", IdentifiersFactory::FrameId(frame));
1007   SetCallStack(value.get());
1008   return value;
1009 }
1010 
LocalCoordToFloatPoint(LocalFrameView * view,const FloatPoint & local)1011 static FloatPoint LocalCoordToFloatPoint(LocalFrameView* view,
1012                                          const FloatPoint& local) {
1013   return FloatPoint(view->ConvertToRootFrame(RoundedIntPoint(local)));
1014 }
1015 
LocalToPageQuad(const LayoutObject & layout_object,const PhysicalRect & rect,FloatQuad * quad)1016 static void LocalToPageQuad(const LayoutObject& layout_object,
1017                             const PhysicalRect& rect,
1018                             FloatQuad* quad) {
1019   LocalFrame* frame = layout_object.GetFrame();
1020   LocalFrameView* view = frame->View();
1021   FloatQuad absolute = layout_object.LocalRectToAbsoluteQuad(rect);
1022   quad->SetP1(LocalCoordToFloatPoint(view, absolute.P1()));
1023   quad->SetP2(LocalCoordToFloatPoint(view, absolute.P2()));
1024   quad->SetP3(LocalCoordToFloatPoint(view, absolute.P3()));
1025   quad->SetP4(LocalCoordToFloatPoint(view, absolute.P4()));
1026 }
1027 
Data(LayoutObject * layout_object,const PhysicalRect & clip_rect,const GraphicsLayer * graphics_layer)1028 std::unique_ptr<TracedValue> inspector_paint_event::Data(
1029     LayoutObject* layout_object,
1030     const PhysicalRect& clip_rect,
1031     const GraphicsLayer* graphics_layer) {
1032   auto value = std::make_unique<TracedValue>();
1033   value->SetString("frame",
1034                    IdentifiersFactory::FrameId(layout_object->GetFrame()));
1035   FloatQuad quad;
1036   LocalToPageQuad(*layout_object, clip_rect, &quad);
1037   CreateQuad(value.get(), "clip", quad);
1038   SetGeneratingNodeInfo(value.get(), layout_object, "nodeId");
1039   int graphics_layer_id = graphics_layer ? graphics_layer->CcLayer()->id() : 0;
1040   value->SetInteger("layerId", graphics_layer_id);
1041   SetCallStack(value.get());
1042   return value;
1043 }
1044 
FrameEventData(LocalFrame * frame)1045 std::unique_ptr<TracedValue> FrameEventData(LocalFrame* frame) {
1046   auto value = std::make_unique<TracedValue>();
1047   bool is_main_frame = frame && frame->IsMainFrame();
1048   value->SetBoolean("isMainFrame", is_main_frame);
1049   // TODO(dgozman): this does not work with OOPIF, so everyone who
1050   // uses it should migrate to frame instead.
1051   value->SetString("page",
1052                    IdentifiersFactory::FrameId(&frame->LocalFrameRoot()));
1053   return value;
1054 }
1055 
FillCommonFrameData(TracedValue * frame_data,LocalFrame * frame)1056 void FillCommonFrameData(TracedValue* frame_data, LocalFrame* frame) {
1057   frame_data->SetString("frame", IdentifiersFactory::FrameId(frame));
1058   frame_data->SetString("url", UrlForFrame(frame));
1059   frame_data->SetString("name", frame->Tree().GetName());
1060 
1061   FrameOwner* owner = frame->Owner();
1062   if (auto* frame_owner_element = DynamicTo<HTMLFrameOwnerElement>(owner)) {
1063     frame_data->SetInteger(
1064         "nodeId", IdentifiersFactory::IntIdForNode(frame_owner_element));
1065   }
1066   Frame* parent = frame->Tree().Parent();
1067   if (IsA<LocalFrame>(parent))
1068     frame_data->SetString("parent", IdentifiersFactory::FrameId(parent));
1069 }
1070 
Data(LocalFrame * frame)1071 std::unique_ptr<TracedValue> inspector_commit_load_event::Data(
1072     LocalFrame* frame) {
1073   std::unique_ptr<TracedValue> frame_data = FrameEventData(frame);
1074   FillCommonFrameData(frame_data.get(), frame);
1075   return frame_data;
1076 }
1077 
Data(LocalFrame * frame)1078 std::unique_ptr<TracedValue> inspector_mark_load_event::Data(
1079     LocalFrame* frame) {
1080   std::unique_ptr<TracedValue> frame_data = FrameEventData(frame);
1081   frame_data->SetString("frame", IdentifiersFactory::FrameId(frame));
1082   return frame_data;
1083 }
1084 
Data(LayoutObject * layout_object)1085 std::unique_ptr<TracedValue> inspector_scroll_layer_event::Data(
1086     LayoutObject* layout_object) {
1087   auto value = std::make_unique<TracedValue>();
1088   value->SetString("frame",
1089                    IdentifiersFactory::FrameId(layout_object->GetFrame()));
1090   SetGeneratingNodeInfo(value.get(), layout_object, "nodeId");
1091   return value;
1092 }
1093 
Data(LocalFrame * frame)1094 std::unique_ptr<TracedValue> inspector_update_layer_tree_event::Data(
1095     LocalFrame* frame) {
1096   auto value = std::make_unique<TracedValue>();
1097   value->SetString("frame", IdentifiersFactory::FrameId(frame));
1098   return value;
1099 }
1100 
1101 namespace {
FillLocation(const String & url,const TextPosition & text_position)1102 std::unique_ptr<TracedValue> FillLocation(const String& url,
1103                                           const TextPosition& text_position) {
1104   auto value = std::make_unique<TracedValue>();
1105   value->SetString("url", url);
1106   value->SetInteger("lineNumber", text_position.line_.OneBasedInt());
1107   value->SetInteger("columnNumber", text_position.column_.OneBasedInt());
1108   return value;
1109 }
1110 }  // namespace
1111 
Data(LocalFrame * frame,const String & url,const TextPosition & text_position)1112 std::unique_ptr<TracedValue> inspector_evaluate_script_event::Data(
1113     LocalFrame* frame,
1114     const String& url,
1115     const TextPosition& text_position) {
1116   std::unique_ptr<TracedValue> value = FillLocation(url, text_position);
1117   value->SetString("frame", IdentifiersFactory::FrameId(frame));
1118   SetCallStack(value.get());
1119   return value;
1120 }
1121 
Data(uint64_t identifier,const String & url)1122 std::unique_ptr<TracedValue> inspector_parse_script_event::Data(
1123     uint64_t identifier,
1124     const String& url) {
1125   String request_id = IdentifiersFactory::RequestId(nullptr, identifier);
1126   auto value = std::make_unique<TracedValue>();
1127   value->SetString("requestId", request_id);
1128   value->SetString("url", url);
1129   return value;
1130 }
1131 
ProduceResult(int cache_size)1132 inspector_compile_script_event::V8CacheResult::ProduceResult::ProduceResult(
1133     int cache_size)
1134     : cache_size(cache_size) {}
1135 
ConsumeResult(v8::ScriptCompiler::CompileOptions consume_options,int cache_size,bool rejected)1136 inspector_compile_script_event::V8CacheResult::ConsumeResult::ConsumeResult(
1137     v8::ScriptCompiler::CompileOptions consume_options,
1138     int cache_size,
1139     bool rejected)
1140     : consume_options(consume_options),
1141       cache_size(cache_size),
1142       rejected(rejected) {
1143   DCHECK_EQ(consume_options, v8::ScriptCompiler::kConsumeCodeCache);
1144 }
1145 
V8CacheResult(base::Optional<ProduceResult> produce_result,base::Optional<ConsumeResult> consume_result)1146 inspector_compile_script_event::V8CacheResult::V8CacheResult(
1147     base::Optional<ProduceResult> produce_result,
1148     base::Optional<ConsumeResult> consume_result)
1149     : produce_result(std::move(produce_result)),
1150       consume_result(std::move(consume_result)) {}
1151 
Data(const String & url,const TextPosition & text_position,const V8CacheResult & cache_result,bool streamed,ScriptStreamer::NotStreamingReason not_streaming_reason)1152 std::unique_ptr<TracedValue> inspector_compile_script_event::Data(
1153     const String& url,
1154     const TextPosition& text_position,
1155     const V8CacheResult& cache_result,
1156     bool streamed,
1157     ScriptStreamer::NotStreamingReason not_streaming_reason) {
1158   std::unique_ptr<TracedValue> value = FillLocation(url, text_position);
1159 
1160   if (cache_result.produce_result) {
1161     value->SetInteger("producedCacheSize",
1162                       cache_result.produce_result->cache_size);
1163   }
1164 
1165   if (cache_result.consume_result) {
1166     value->SetString(
1167         "cacheConsumeOptions",
1168         CompileOptionsString(cache_result.consume_result->consume_options));
1169     value->SetInteger("consumedCacheSize",
1170                       cache_result.consume_result->cache_size);
1171     value->SetBoolean("cacheRejected", cache_result.consume_result->rejected);
1172   }
1173   value->SetBoolean("streamed", streamed);
1174   if (!streamed) {
1175     value->SetString("notStreamedReason",
1176                      NotStreamedReasonString(not_streaming_reason));
1177   }
1178   return value;
1179 }
1180 
Data(ExecutionContext * context,const v8::Local<v8::Function> & function)1181 std::unique_ptr<TracedValue> inspector_function_call_event::Data(
1182     ExecutionContext* context,
1183     const v8::Local<v8::Function>& function) {
1184   auto value = std::make_unique<TracedValue>();
1185   if (LocalFrame* frame = FrameForExecutionContext(context))
1186     value->SetString("frame", IdentifiersFactory::FrameId(frame));
1187 
1188   if (function.IsEmpty())
1189     return value;
1190 
1191   v8::Local<v8::Function> original_function = GetBoundFunction(function);
1192   v8::Local<v8::Value> function_name = original_function->GetDebugName();
1193   if (!function_name.IsEmpty() && function_name->IsString()) {
1194     value->SetString("functionName",
1195                      ToCoreString(function_name.As<v8::String>()));
1196   }
1197   std::unique_ptr<SourceLocation> location =
1198       SourceLocation::FromFunction(original_function);
1199   value->SetString("scriptId", String::Number(location->ScriptId()));
1200   value->SetString("url", location->Url());
1201   value->SetInteger("lineNumber", location->LineNumber());
1202   value->SetInteger("columnNumber", location->ColumnNumber());
1203   return value;
1204 }
1205 
Data(const LayoutImage & layout_image,const FloatRect & src_rect,const FloatRect & dest_rect)1206 std::unique_ptr<TracedValue> inspector_paint_image_event::Data(
1207     const LayoutImage& layout_image,
1208     const FloatRect& src_rect,
1209     const FloatRect& dest_rect) {
1210   auto value = std::make_unique<TracedValue>();
1211   SetGeneratingNodeInfo(value.get(), &layout_image, "nodeId");
1212   if (const ImageResourceContent* resource = layout_image.CachedImage())
1213     value->SetString("url", resource->Url().GetString());
1214 
1215   value->SetInteger("x", dest_rect.X());
1216   value->SetInteger("y", dest_rect.Y());
1217   value->SetInteger("width", dest_rect.Width());
1218   value->SetInteger("height", dest_rect.Height());
1219   value->SetInteger("srcWidth", src_rect.Width());
1220   value->SetInteger("srcHeight", src_rect.Height());
1221 
1222   return value;
1223 }
1224 
Data(const LayoutObject & owning_layout_object,const StyleImage & style_image)1225 std::unique_ptr<TracedValue> inspector_paint_image_event::Data(
1226     const LayoutObject& owning_layout_object,
1227     const StyleImage& style_image) {
1228   auto value = std::make_unique<TracedValue>();
1229   SetGeneratingNodeInfo(value.get(), &owning_layout_object, "nodeId");
1230   if (const ImageResourceContent* resource = style_image.CachedImage())
1231     value->SetString("url", resource->Url().GetString());
1232   return value;
1233 }
1234 
Data(Node * node,const StyleImage & style_image,const FloatRect & src_rect,const FloatRect & dest_rect)1235 std::unique_ptr<TracedValue> inspector_paint_image_event::Data(
1236     Node* node,
1237     const StyleImage& style_image,
1238     const FloatRect& src_rect,
1239     const FloatRect& dest_rect) {
1240   auto value = std::make_unique<TracedValue>();
1241   if (node)
1242     SetNodeInfo(value.get(), node, "nodeId", nullptr);
1243   if (const ImageResourceContent* resource = style_image.CachedImage())
1244     value->SetString("url", resource->Url().GetString());
1245 
1246   value->SetInteger("x", dest_rect.X());
1247   value->SetInteger("y", dest_rect.Y());
1248   value->SetInteger("width", dest_rect.Width());
1249   value->SetInteger("height", dest_rect.Height());
1250   value->SetInteger("srcWidth", src_rect.Width());
1251   value->SetInteger("srcHeight", src_rect.Height());
1252 
1253   return value;
1254 }
1255 
Data(const LayoutObject * owning_layout_object,const ImageResourceContent & image_resource)1256 std::unique_ptr<TracedValue> inspector_paint_image_event::Data(
1257     const LayoutObject* owning_layout_object,
1258     const ImageResourceContent& image_resource) {
1259   auto value = std::make_unique<TracedValue>();
1260   SetGeneratingNodeInfo(value.get(), owning_layout_object, "nodeId");
1261   value->SetString("url", image_resource.Url().GetString());
1262   return value;
1263 }
1264 
UsedHeapSize()1265 static size_t UsedHeapSize() {
1266   v8::HeapStatistics heap_statistics;
1267   v8::Isolate::GetCurrent()->GetHeapStatistics(&heap_statistics);
1268   return heap_statistics.used_heap_size();
1269 }
1270 
Data()1271 std::unique_ptr<TracedValue> inspector_update_counters_event::Data() {
1272   auto value = std::make_unique<TracedValue>();
1273   if (IsMainThread()) {
1274     value->SetInteger("documents", InstanceCounters::CounterValue(
1275                                        InstanceCounters::kDocumentCounter));
1276     value->SetInteger("nodes", InstanceCounters::CounterValue(
1277                                    InstanceCounters::kNodeCounter));
1278     value->SetInteger("jsEventListeners",
1279                       InstanceCounters::CounterValue(
1280                           InstanceCounters::kJSEventListenerCounter));
1281   }
1282   value->SetDouble("jsHeapSizeUsed", static_cast<double>(UsedHeapSize()));
1283   return value;
1284 }
1285 
Data(LocalFrame * frame)1286 std::unique_ptr<TracedValue> inspector_invalidate_layout_event::Data(
1287     LocalFrame* frame) {
1288   auto value = std::make_unique<TracedValue>();
1289   value->SetString("frame", IdentifiersFactory::FrameId(frame));
1290   SetCallStack(value.get());
1291   return value;
1292 }
1293 
Data(LocalFrame * frame)1294 std::unique_ptr<TracedValue> inspector_recalculate_styles_event::Data(
1295     LocalFrame* frame) {
1296   auto value = std::make_unique<TracedValue>();
1297   value->SetString("frame", IdentifiersFactory::FrameId(frame));
1298   SetCallStack(value.get());
1299   return value;
1300 }
1301 
Data(const Event & event)1302 std::unique_ptr<TracedValue> inspector_event_dispatch_event::Data(
1303     const Event& event) {
1304   auto value = std::make_unique<TracedValue>();
1305   value->SetString("type", event.type());
1306   bool record_input_enabled;
1307   TRACE_EVENT_CATEGORY_GROUP_ENABLED(
1308       TRACE_DISABLED_BY_DEFAULT("devtools.timeline.inputs"),
1309       &record_input_enabled);
1310   if (record_input_enabled) {
1311     const auto* keyboard_event = DynamicTo<KeyboardEvent>(event);
1312     if (keyboard_event) {
1313       value->SetInteger("modifier", GetModifierFromEvent(*keyboard_event));
1314       value->SetDouble(
1315           "timestamp",
1316           keyboard_event->PlatformTimeStamp().since_origin().InMicroseconds());
1317       value->SetString("code", keyboard_event->code());
1318       value->SetString("key", keyboard_event->key());
1319     }
1320 
1321     const auto* mouse_event = DynamicTo<MouseEvent>(event);
1322     const auto* wheel_event = DynamicTo<WheelEvent>(event);
1323     if (mouse_event || wheel_event) {
1324       value->SetDouble("x", mouse_event->x());
1325       value->SetDouble("y", mouse_event->y());
1326       value->SetInteger("modifier", GetModifierFromEvent(*mouse_event));
1327       value->SetDouble(
1328           "timestamp",
1329           mouse_event->PlatformTimeStamp().since_origin().InMicroseconds());
1330       value->SetInteger("button", mouse_event->button());
1331       value->SetInteger("buttons", mouse_event->buttons());
1332       value->SetInteger("clickCount", mouse_event->detail());
1333       if (wheel_event) {
1334         value->SetDouble("deltaX", wheel_event->deltaX());
1335         value->SetDouble("deltaY", wheel_event->deltaY());
1336       }
1337     }
1338   }
1339   SetCallStack(value.get());
1340   return value;
1341 }
1342 
Data(ExecutionContext * context,const String & message)1343 std::unique_ptr<TracedValue> inspector_time_stamp_event::Data(
1344     ExecutionContext* context,
1345     const String& message) {
1346   auto value = std::make_unique<TracedValue>();
1347   value->SetString("message", message);
1348   if (LocalFrame* frame = FrameForExecutionContext(context))
1349     value->SetString("frame", IdentifiersFactory::FrameId(frame));
1350   return value;
1351 }
1352 
1353 std::unique_ptr<TracedValue>
Data(const base::UnguessableToken & worker_devtools_token,const base::UnguessableToken & parent_devtools_token,const KURL & url,PlatformThreadId worker_thread_id)1354 inspector_tracing_session_id_for_worker_event::Data(
1355     const base::UnguessableToken& worker_devtools_token,
1356     const base::UnguessableToken& parent_devtools_token,
1357     const KURL& url,
1358     PlatformThreadId worker_thread_id) {
1359   auto value = std::make_unique<TracedValue>();
1360   value->SetString("frame",
1361                    IdentifiersFactory::IdFromToken(parent_devtools_token));
1362   value->SetString("url", url.GetString());
1363   value->SetString("workerId",
1364                    IdentifiersFactory::IdFromToken(worker_devtools_token));
1365   value->SetDouble("workerThreadId", worker_thread_id);
1366   return value;
1367 }
1368 
Data(const String & session_id,LocalFrame * frame)1369 std::unique_ptr<TracedValue> inspector_tracing_started_in_frame::Data(
1370     const String& session_id,
1371     LocalFrame* frame) {
1372   auto value = std::make_unique<TracedValue>();
1373   value->SetString("sessionId", session_id);
1374   value->SetString("page",
1375                    IdentifiersFactory::FrameId(&frame->LocalFrameRoot()));
1376   value->SetBoolean("persistentIds", true);
1377   value->BeginArray("frames");
1378   for (Frame* f = frame; f; f = f->Tree().TraverseNext(frame)) {
1379     auto* local_frame = DynamicTo<LocalFrame>(f);
1380     if (!local_frame)
1381       continue;
1382     value->BeginDictionary();
1383     FillCommonFrameData(value.get(), local_frame);
1384     value->EndDictionary();
1385   }
1386   value->EndArray();
1387   return value;
1388 }
1389 
Data(LocalFrame * frame)1390 std::unique_ptr<TracedValue> inspector_set_layer_tree_id::Data(
1391     LocalFrame* frame) {
1392   auto value = std::make_unique<TracedValue>();
1393   value->SetString("frame", IdentifiersFactory::FrameId(frame));
1394   value->SetInteger("layerTreeId",
1395                     frame->GetPage()->GetChromeClient().GetLayerTreeId(*frame));
1396   return value;
1397 }
1398 
Data(const Animation & animation)1399 std::unique_ptr<TracedValue> inspector_animation_event::Data(
1400     const Animation& animation) {
1401   auto value = std::make_unique<TracedValue>();
1402   value->SetString("id", String::Number(animation.SequenceNumber()));
1403   value->SetString("state", animation.PlayStateString());
1404   if (const AnimationEffect* effect = animation.effect()) {
1405     value->SetString("name", animation.id());
1406     if (auto* frame_effect = DynamicTo<KeyframeEffect>(effect)) {
1407       if (Element* target = frame_effect->EffectTarget())
1408         SetNodeInfo(value.get(), target, "nodeId", "nodeName");
1409     }
1410   }
1411   return value;
1412 }
1413 
Data(const Animation & animation)1414 std::unique_ptr<TracedValue> inspector_animation_state_event::Data(
1415     const Animation& animation) {
1416   auto value = std::make_unique<TracedValue>();
1417   value->SetString("state", animation.PlayStateString());
1418   return value;
1419 }
1420 
EndData(const HitTestRequest & request,const HitTestLocation & location,const HitTestResult & result)1421 std::unique_ptr<TracedValue> inspector_hit_test_event::EndData(
1422     const HitTestRequest& request,
1423     const HitTestLocation& location,
1424     const HitTestResult& result) {
1425   auto value(std::make_unique<TracedValue>());
1426   value->SetInteger("x", location.RoundedPoint().X());
1427   value->SetInteger("y", location.RoundedPoint().Y());
1428   if (location.IsRectBasedTest())
1429     value->SetBoolean("rect", true);
1430   if (location.IsRectilinear())
1431     value->SetBoolean("rectilinear", true);
1432   if (request.TouchEvent())
1433     value->SetBoolean("touch", true);
1434   if (request.Move())
1435     value->SetBoolean("move", true);
1436   if (request.ListBased())
1437     value->SetBoolean("listBased", true);
1438   else if (Node* node = result.InnerNode())
1439     SetNodeInfo(value.get(), node, "nodeId", "nodeName");
1440   return value;
1441 }
1442 
Data(const StringView & name)1443 std::unique_ptr<TracedValue> inspector_async_task::Data(
1444     const StringView& name) {
1445   auto value = std::make_unique<TracedValue>();
1446   value->SetString("name", name.ToString());
1447   return value;
1448 }
1449 
1450 }  // namespace blink
1451