summaryrefslogtreecommitdiff
path: root/chromium/third_party/blink/renderer/core/inspector/legacy_dom_snapshot_agent.cc
blob: 8970aaf50700c58a503e550f294a760e87a2d0e2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "third_party/blink/renderer/core/inspector/legacy_dom_snapshot_agent.h"

#include "third_party/blink/renderer/bindings/core/v8/script_event_listener.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
#include "third_party/blink/renderer/core/css/css_computed_style_declaration.h"
#include "third_party/blink/renderer/core/dom/attribute.h"
#include "third_party/blink/renderer/core/dom/attribute_collection.h"
#include "third_party/blink/renderer/core/dom/character_data.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/document_type.h"
#include "third_party/blink/renderer/core/dom/dom_node_ids.h"
#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/core/dom/node.h"
#include "third_party/blink/renderer/core/dom/pseudo_element.h"
#include "third_party/blink/renderer/core/dom/qualified_name.h"
#include "third_party/blink/renderer/core/dom/shadow_root.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/html/forms/html_input_element.h"
#include "third_party/blink/renderer/core/html/forms/html_option_element.h"
#include "third_party/blink/renderer/core/html/forms/html_text_area_element.h"
#include "third_party/blink/renderer/core/html/html_frame_owner_element.h"
#include "third_party/blink/renderer/core/html/html_image_element.h"
#include "third_party/blink/renderer/core/html/html_link_element.h"
#include "third_party/blink/renderer/core/html/html_template_element.h"
#include "third_party/blink/renderer/core/input_type_names.h"
#include "third_party/blink/renderer/core/inspector/identifiers_factory.h"
#include "third_party/blink/renderer/core/inspector/inspector_dom_agent.h"
#include "third_party/blink/renderer/core/inspector/inspector_dom_debugger_agent.h"
#include "third_party/blink/renderer/core/inspector/inspector_dom_snapshot_agent.h"
#include "third_party/blink/renderer/core/inspector/thread_debugger.h"
#include "third_party/blink/renderer/core/layout/layout_embedded_content.h"
#include "third_party/blink/renderer/core/layout/layout_object.h"
#include "third_party/blink/renderer/core/layout/layout_text.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "v8/include/v8-inspector.h"

namespace blink {
using protocol::Maybe;
using protocol::Response;

namespace {

std::unique_ptr<protocol::DOM::Rect> LegacyBuildRectForPhysicalRect(
    const PhysicalRect& rect) {
  return protocol::DOM::Rect::create()
      .setX(rect.X())
      .setY(rect.Y())
      .setWidth(rect.Width())
      .setHeight(rect.Height())
      .build();
}

}  // namespace

struct LegacyDOMSnapshotAgent::VectorStringHashTraits
    : public WTF::GenericHashTraits<Vector<String>> {
  static unsigned GetHash(const Vector<String>& vec) {
    unsigned h = DefaultHash<size_t>::Hash::GetHash(vec.size());
    for (wtf_size_t i = 0; i < vec.size(); i++) {
      h = WTF::HashInts(h, DefaultHash<String>::Hash::GetHash(vec[i]));
    }
    return h;
  }

  static bool Equal(const Vector<String>& a, const Vector<String>& b) {
    if (a.size() != b.size())
      return false;
    for (wtf_size_t i = 0; i < a.size(); i++) {
      if (a[i] != b[i])
        return false;
    }
    return true;
  }

  static void ConstructDeletedValue(Vector<String>& vec, bool) {
    new (NotNull, &vec) Vector<String>(WTF::kHashTableDeletedValue);
  }

  static bool IsDeletedValue(const Vector<String>& vec) {
    return vec.IsHashTableDeletedValue();
  }

  static bool IsEmptyValue(const Vector<String>& vec) { return vec.IsEmpty(); }

  static const bool kEmptyValueIsZero = false;
  static const bool safe_to_compare_to_empty_or_deleted = false;
  static const bool kHasIsEmptyValueFunction = true;
};

LegacyDOMSnapshotAgent::LegacyDOMSnapshotAgent(
    InspectorDOMDebuggerAgent* dom_debugger_agent,
    OriginUrlMap* origin_url_map)
    : origin_url_map_(origin_url_map),
      dom_debugger_agent_(dom_debugger_agent) {}

LegacyDOMSnapshotAgent::~LegacyDOMSnapshotAgent() = default;

Response LegacyDOMSnapshotAgent::GetSnapshot(
    Document* document,
    std::unique_ptr<protocol::Array<String>> style_filter,
    protocol::Maybe<bool> include_event_listeners,
    protocol::Maybe<bool> include_paint_order,
    protocol::Maybe<bool> include_user_agent_shadow_tree,
    std::unique_ptr<protocol::Array<protocol::DOMSnapshot::DOMNode>>* dom_nodes,
    std::unique_ptr<protocol::Array<protocol::DOMSnapshot::LayoutTreeNode>>*
        layout_tree_nodes,
    std::unique_ptr<protocol::Array<protocol::DOMSnapshot::ComputedStyle>>*
        computed_styles) {
  // Setup snapshot.
  dom_nodes_ =
      std::make_unique<protocol::Array<protocol::DOMSnapshot::DOMNode>>();
  layout_tree_nodes_ = std::make_unique<
      protocol::Array<protocol::DOMSnapshot::LayoutTreeNode>>();
  computed_styles_ =
      std::make_unique<protocol::Array<protocol::DOMSnapshot::ComputedStyle>>();
  computed_styles_map_ = std::make_unique<ComputedStylesMap>();
  css_property_filter_ = std::make_unique<CSSPropertyFilter>();

  // Look up the CSSPropertyIDs for each entry in |style_filter|.
  for (const String& entry : *style_filter) {
    CSSPropertyID property_id =
        cssPropertyID(document->GetExecutionContext(), entry);
    if (property_id == CSSPropertyID::kInvalid)
      continue;
    css_property_filter_->emplace_back(entry, property_id);
  }

  if (include_paint_order.fromMaybe(false))
    paint_order_map_ = InspectorDOMSnapshotAgent::BuildPaintLayerTree(document);

  // Actual traversal.
  VisitNode(document, include_event_listeners.fromMaybe(false),
            include_user_agent_shadow_tree.fromMaybe(false));

  // Extract results from state and reset.
  *dom_nodes = std::move(dom_nodes_);
  *layout_tree_nodes = std::move(layout_tree_nodes_);
  *computed_styles = std::move(computed_styles_);
  computed_styles_map_.reset();
  css_property_filter_.reset();
  paint_order_map_.reset();
  return Response::Success();
}

int LegacyDOMSnapshotAgent::VisitNode(Node* node,
                                      bool include_event_listeners,
                                      bool include_user_agent_shadow_tree) {
  // Update layout tree before traversal of document so that we inspect a
  // current and consistent state of all trees. No need to do this if paint
  // order was calculated, since layout trees were already updated during
  // TraversePaintLayerTree().
  if (node->IsDocumentNode() && !paint_order_map_)
    node->GetDocument().UpdateStyleAndLayoutTree();

  String node_value;
  switch (node->getNodeType()) {
    case Node::kTextNode:
    case Node::kAttributeNode:
    case Node::kCommentNode:
    case Node::kCdataSectionNode:
    case Node::kDocumentFragmentNode:
      node_value = node->nodeValue();
      break;
    default:
      break;
  }

  // Create DOMNode object and add it to the result array before traversing
  // children, so that parents appear before their children in the array.
  std::unique_ptr<protocol::DOMSnapshot::DOMNode> owned_value =
      protocol::DOMSnapshot::DOMNode::create()
          .setNodeType(static_cast<int>(node->getNodeType()))
          .setNodeName(node->nodeName())
          .setNodeValue(node_value)
          .setBackendNodeId(IdentifiersFactory::IntIdForNode(node))
          .build();
  if (origin_url_map_ &&
      origin_url_map_->Contains(owned_value->getBackendNodeId())) {
    String origin_url = origin_url_map_->at(owned_value->getBackendNodeId());
    // In common cases, it is implicit that a child node would have the same
    // origin url as its parent, so no need to mark twice.
    if (!node->parentNode() || origin_url_map_->at(DOMNodeIds::IdForNode(
                                   node->parentNode())) != origin_url) {
      owned_value->setOriginURL(
          origin_url_map_->at(owned_value->getBackendNodeId()));
    }
  }
  protocol::DOMSnapshot::DOMNode* value = owned_value.get();
  int index = static_cast<int>(dom_nodes_->size());
  dom_nodes_->emplace_back(std::move(owned_value));

  int layoutNodeIndex =
      VisitLayoutTreeNode(node->GetLayoutObject(), node, index);
  if (layoutNodeIndex != -1)
    value->setLayoutNodeIndex(layoutNodeIndex);

  if (node->WillRespondToMouseClickEvents())
    value->setIsClickable(true);

  if (include_event_listeners && node->GetDocument().GetFrame()) {
    ScriptState* script_state =
        ToScriptStateForMainWorld(node->GetDocument().GetFrame());
    if (script_state->ContextIsValid()) {
      ScriptState::Scope scope(script_state);
      v8::Local<v8::Context> context = script_state->GetContext();
      V8EventListenerInfoList event_information;
      InspectorDOMDebuggerAgent::CollectEventListeners(
          script_state->GetIsolate(), node, v8::Local<v8::Value>(), node, true,
          &event_information);
      if (!event_information.IsEmpty()) {
        value->setEventListeners(
            dom_debugger_agent_->BuildObjectsForEventListeners(
                event_information, context, v8_inspector::StringView()));
      }
    }
  }

  auto* element = DynamicTo<Element>(node);
  if (element) {
    value->setAttributes(BuildArrayForElementAttributes(element));

    if (auto* frame_owner = DynamicTo<HTMLFrameOwnerElement>(node)) {
      if (LocalFrame* frame =
              DynamicTo<LocalFrame>(frame_owner->ContentFrame()))
        value->setFrameId(IdentifiersFactory::FrameId(frame));

      if (Document* doc = frame_owner->contentDocument()) {
        value->setContentDocumentIndex(VisitNode(
            doc, include_event_listeners, include_user_agent_shadow_tree));
      }
    }

    if (node->parentNode() && node->parentNode()->IsDocumentNode()) {
      LocalFrame* frame = node->GetDocument().GetFrame();
      if (frame)
        value->setFrameId(IdentifiersFactory::FrameId(frame));
    }

    if (auto* textarea_element = DynamicTo<HTMLTextAreaElement>(*element))
      value->setTextValue(textarea_element->value());

    if (auto* input_element = DynamicTo<HTMLInputElement>(*element)) {
      value->setInputValue(input_element->value());
      if ((input_element->type() == input_type_names::kRadio) ||
          (input_element->type() == input_type_names::kCheckbox)) {
        value->setInputChecked(input_element->checked());
      }
    }

    if (auto* option_element = DynamicTo<HTMLOptionElement>(*element))
      value->setOptionSelected(option_element->Selected());

    if (element->GetPseudoId()) {
      value->setPseudoType(
          InspectorDOMAgent::ProtocolPseudoElementType(element->GetPseudoId()));
    }
    value->setPseudoElementIndexes(
        VisitPseudoElements(element, index, include_event_listeners,
                            include_user_agent_shadow_tree));

    auto* image_element = DynamicTo<HTMLImageElement>(node);
    if (image_element)
      value->setCurrentSourceURL(image_element->currentSrc());
  } else if (auto* document = DynamicTo<Document>(node)) {
    value->setDocumentURL(InspectorDOMAgent::DocumentURLString(document));
    value->setBaseURL(InspectorDOMAgent::DocumentBaseURLString(document));
    if (document->ContentLanguage())
      value->setContentLanguage(document->ContentLanguage().Utf8().c_str());
    if (document->EncodingName())
      value->setDocumentEncoding(document->EncodingName().Utf8().c_str());
    value->setFrameId(IdentifiersFactory::FrameId(document->GetFrame()));
    if (document->View() && document->View()->LayoutViewport()) {
      auto offset = document->View()->LayoutViewport()->GetScrollOffset();
      value->setScrollOffsetX(offset.Width());
      value->setScrollOffsetY(offset.Height());
    }
  } else if (auto* doc_type = DynamicTo<DocumentType>(node)) {
    value->setPublicId(doc_type->publicId());
    value->setSystemId(doc_type->systemId());
  }
  if (node->IsInShadowTree()) {
    value->setShadowRootType(
        InspectorDOMAgent::GetShadowRootType(node->ContainingShadowRoot()));
  }

  if (node->IsContainerNode()) {
    value->setChildNodeIndexes(VisitContainerChildren(
        node, include_event_listeners, include_user_agent_shadow_tree));
  }
  return index;
}

std::unique_ptr<protocol::Array<int>>
LegacyDOMSnapshotAgent::VisitContainerChildren(
    Node* container,
    bool include_event_listeners,
    bool include_user_agent_shadow_tree) {
  auto children = std::make_unique<protocol::Array<int>>();

  if (!InspectorDOMSnapshotAgent::HasChildren(*container,
                                              include_user_agent_shadow_tree))
    return nullptr;

  Node* child = InspectorDOMSnapshotAgent::FirstChild(
      *container, include_user_agent_shadow_tree);
  while (child) {
    children->emplace_back(VisitNode(child, include_event_listeners,
                                     include_user_agent_shadow_tree));
    child = InspectorDOMSnapshotAgent::NextSibling(
        *child, include_user_agent_shadow_tree);
  }

  return children;
}

std::unique_ptr<protocol::Array<int>>
LegacyDOMSnapshotAgent::VisitPseudoElements(
    Element* parent,
    int index,
    bool include_event_listeners,
    bool include_user_agent_shadow_tree) {
  if (!parent->GetPseudoElement(kPseudoIdFirstLetter) &&
      !parent->GetPseudoElement(kPseudoIdBefore) &&
      !parent->GetPseudoElement(kPseudoIdAfter)) {
    return nullptr;
  }

  auto pseudo_elements = std::make_unique<protocol::Array<int>>();
  for (PseudoId pseudo_id :
       {kPseudoIdFirstLetter, kPseudoIdBefore, kPseudoIdAfter}) {
    if (Node* pseudo_node = parent->GetPseudoElement(pseudo_id)) {
      pseudo_elements->emplace_back(VisitNode(pseudo_node,
                                              include_event_listeners,
                                              include_user_agent_shadow_tree));
    }
  }
  return pseudo_elements;
}

std::unique_ptr<protocol::Array<protocol::DOMSnapshot::NameValue>>
LegacyDOMSnapshotAgent::BuildArrayForElementAttributes(Element* element) {
  AttributeCollection attributes = element->Attributes();
  if (attributes.IsEmpty())
    return nullptr;
  auto attributes_value =
      std::make_unique<protocol::Array<protocol::DOMSnapshot::NameValue>>();
  for (const auto& attribute : attributes) {
    attributes_value->emplace_back(protocol::DOMSnapshot::NameValue::create()
                                       .setName(attribute.GetName().ToString())
                                       .setValue(attribute.Value())
                                       .build());
  }
  return attributes_value;
}

int LegacyDOMSnapshotAgent::VisitLayoutTreeNode(LayoutObject* layout_object,
                                                Node* node,
                                                int node_index) {
  if (!layout_object)
    return -1;

  if (node->GetPseudoId()) {
    // For pseudo elements, visit the children of the layout object.
    for (LayoutObject* child = layout_object->SlowFirstChild(); child;
         child = child->NextSibling()) {
      if (child->IsAnonymous())
        VisitLayoutTreeNode(child, node, node_index);
    }
  }

  auto layout_tree_node =
      protocol::DOMSnapshot::LayoutTreeNode::create()
          .setDomNodeIndex(node_index)
          .setBoundingBox(LegacyBuildRectForPhysicalRect(
              InspectorDOMSnapshotAgent::RectInDocument(layout_object)))
          .build();

  int style_index = GetStyleIndexForNode(node);
  if (style_index != -1)
    layout_tree_node->setStyleIndex(style_index);

  if (layout_object->Style() && layout_object->Style()->IsStackingContext())
    layout_tree_node->setIsStackingContext(true);

  if (paint_order_map_) {
    PaintLayer* paint_layer = layout_object->EnclosingLayer();

    // We visited all PaintLayers when building |paint_order_map_|.
    DCHECK(paint_order_map_->Contains(paint_layer));

    if (int paint_order = paint_order_map_->at(paint_layer))
      layout_tree_node->setPaintOrder(paint_order);
  }

  if (layout_object->IsText()) {
    LayoutText* layout_text = ToLayoutText(layout_object);
    layout_tree_node->setLayoutText(layout_text->GetText());
    Vector<LayoutText::TextBoxInfo> text_boxes = layout_text->GetTextBoxInfo();
    if (!text_boxes.IsEmpty()) {
      auto inline_text_nodes = std::make_unique<
          protocol::Array<protocol::DOMSnapshot::InlineTextBox>>();
      for (const auto& text_box : text_boxes) {
        inline_text_nodes->emplace_back(
            protocol::DOMSnapshot::InlineTextBox::create()
                .setStartCharacterIndex(text_box.dom_start_offset)
                .setNumCharacters(text_box.dom_length)
                .setBoundingBox(LegacyBuildRectForPhysicalRect(
                    InspectorDOMSnapshotAgent::TextFragmentRectInDocument(
                        layout_object, text_box)))
                .build());
      }
      layout_tree_node->setInlineTextNodes(std::move(inline_text_nodes));
    }
  }

  int index = static_cast<int>(layout_tree_nodes_->size());
  layout_tree_nodes_->emplace_back(std::move(layout_tree_node));
  return index;
}

int LegacyDOMSnapshotAgent::GetStyleIndexForNode(Node* node) {
  auto* computed_style_info =
      MakeGarbageCollected<CSSComputedStyleDeclaration>(node, true);

  Vector<String> style;
  bool all_properties_empty = true;
  for (const auto& pair : *css_property_filter_) {
    String value = computed_style_info->GetPropertyValue(pair.second);
    if (!value.IsEmpty())
      all_properties_empty = false;
    style.push_back(value);
  }

  // -1 means an empty style.
  if (all_properties_empty)
    return -1;

  ComputedStylesMap::iterator it = computed_styles_map_->find(style);
  if (it != computed_styles_map_->end())
    return it->value;

  // It's a distinct style, so append to |computedStyles|.
  auto style_properties =
      std::make_unique<protocol::Array<protocol::DOMSnapshot::NameValue>>();

  for (wtf_size_t i = 0; i < style.size(); i++) {
    if (style[i].IsEmpty())
      continue;
    style_properties->emplace_back(
        protocol::DOMSnapshot::NameValue::create()
            .setName((*css_property_filter_)[i].first)
            .setValue(style[i])
            .build());
  }

  wtf_size_t index = static_cast<wtf_size_t>(computed_styles_->size());
  computed_styles_->emplace_back(protocol::DOMSnapshot::ComputedStyle::create()
                                     .setProperties(std::move(style_properties))
                                     .build());
  computed_styles_map_->insert(std::move(style), index);
  return index;
}

}  // namespace blink