File: page_text_agent.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (166 lines) | stat: -rw-r--r-- 5,742 bytes parent folder | download | duplicates (8)
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
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/optimization_guide/content/renderer/page_text_agent.h"

#include "base/functional/callback_helpers.h"
#include "content/public/renderer/render_frame.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h"
#include "third_party/blink/public/platform/web_string.h"
#include "third_party/blink/public/web/web_frame_content_dumper.h"

namespace optimization_guide {

namespace {

constexpr size_t kChunkSize = 4096;

std::optional<mojom::TextDumpEvent> LayoutEventAsMojoEvent(
    blink::WebMeaningfulLayout layout_event) {
  switch (layout_event) {
    case blink::WebMeaningfulLayout::kFinishedParsing:
      return mojom::TextDumpEvent::kFirstLayout;
    case blink::WebMeaningfulLayout::kFinishedLoading:
      return mojom::TextDumpEvent::kFinishedLoad;
    default:
      break;
  }
  return std::nullopt;
}

}  // namespace

PageTextAgent::PageTextAgent(content::RenderFrame* frame)
    : content::RenderFrameObserver(frame),
      content::RenderFrameObserverTracker<PageTextAgent>(frame) {
  if (!frame) {
    // For unittesting.
    return;
  }
  frame->GetAssociatedInterfaceRegistry()->AddInterface<mojom::PageTextService>(
      base::BindRepeating(&PageTextAgent::Bind, weak_factory_.GetWeakPtr()));
}
PageTextAgent::~PageTextAgent() = default;

void PageTextAgent::Bind(
    mojo::PendingAssociatedReceiver<mojom::PageTextService> receiver) {
  receivers_.Add(this, std::move(receiver));
}

base::OnceCallback<void(scoped_refptr<const base::RefCountedString16>)>
PageTextAgent::MaybeRequestTextDumpOnLayoutEvent(
    blink::WebMeaningfulLayout event,
    uint32_t* max_size) {
  // This code path is only supported for mainframes, when there is a frame.
  if (render_frame() && !render_frame()->IsMainFrame()) {
    return base::NullCallback();
  }

  std::optional<mojom::TextDumpEvent> mojo_event =
      LayoutEventAsMojoEvent(event);
  if (!mojo_event) {
    return base::NullCallback();
  }

  auto requests_iter = requests_by_event_.find(*mojo_event);
  if (requests_iter == requests_by_event_.end()) {
    return base::NullCallback();
  }

  // Move the pending consumer remote out of the map. The map entry will be
  // destroyed since it's not needed anymore, but the pending remote will be
  // given to the callback for when the text is ready.
  mojo::PendingRemote<mojom::PageTextConsumer> pending_consumer =
      std::move(requests_iter->second.second);
  *max_size = std::max(*max_size, requests_iter->second.first->max_size);

  requests_by_event_.erase(*mojo_event);

  return base::BindOnce(&PageTextAgent::OnPageTextDump,
                        weak_factory_.GetWeakPtr(),
                        std::move(pending_consumer));
}

void PageTextAgent::OnPageTextDump(
    mojo::PendingRemote<mojom::PageTextConsumer> pending_consumer,
    scoped_refptr<const base::RefCountedString16> content) {
  mojo::Remote<mojom::PageTextConsumer> consumer;
  consumer.Bind(std::move(pending_consumer));

  if (content) {
    for (size_t i = 0; i < content->as_string().size(); i += kChunkSize) {
      // Take a substring of length |kChunkSize|, or whatever is left in
      // |content|, whichever is less.
      size_t chunk_size = std::min(kChunkSize, content->as_string().size() - i);

      // Either mojo will end up making a copy of the string (if passed a const
      // ref), or we will. Might as well just do it now to make this less
      // complex, but std::move it.
      std::u16string chunk = content->as_string().substr(i, chunk_size);
      consumer->OnTextDumpChunk(std::move(chunk));
    }
  }
  consumer->OnChunksEnd();
}

void PageTextAgent::DidFinishLoad() {
  if (!render_frame()) {
    return;
  }

  // Only subframes should use this code path.
  if (render_frame()->IsMainFrame()) {
    return;
  }

  // Only AMP subframes are supported.
  if (!is_amp_page_) {
    return;
  }

  auto requests_iter =
      requests_by_event_.find(mojom::TextDumpEvent::kFinishedLoad);
  if (requests_iter == requests_by_event_.end()) {
    return;
  }

  mojo::PendingRemote<mojom::PageTextConsumer> pending_consumer =
      std::move(requests_iter->second.second);
  uint32_t max_size = requests_iter->second.first->max_size;
  requests_by_event_.erase(mojom::TextDumpEvent::kFinishedLoad);

  auto content = base::MakeRefCounted<const base::RefCountedString16>(
      blink::WebFrameContentDumper::DumpFrameTreeAsText(
          render_frame()->GetWebFrame(), max_size)
          .Utf16());
  OnPageTextDump(std::move(pending_consumer), std::move(content));
}

void PageTextAgent::DidStartNavigation(
    const GURL& url,
    std::optional<blink::WebNavigationType> navigation_type) {
  is_amp_page_ = false;
  // Note that |requests_by_event_| should NOT be reset here. Requests and
  // navigations from the browser race with each other, and the text dump
  // request normally wins. We don't want to drop a request when its navigation
  // is just about to start.
}

void PageTextAgent::DidObserveLoadingBehavior(
    blink::LoadingBehaviorFlag behavior) {
  is_amp_page_ |=
      behavior & blink::LoadingBehaviorFlag::kLoadingBehaviorAmpDocumentLoaded;
}

void PageTextAgent::RequestPageTextDump(
    mojom::PageTextDumpRequestPtr request,
    mojo::PendingRemote<mojom::PageTextConsumer> consumer) {
  // Save the request and consumer until the event comes along.
  mojom::TextDumpEvent event = request->event;
  requests_by_event_.emplace(
      event, std::make_pair(std::move(request), std::move(consumer)));
}

}  // namespace optimization_guide