File: read_anything_screenshotter.cc

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (223 lines) | stat: -rw-r--r-- 8,529 bytes parent folder | download | duplicates (6)
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
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/webui/side_panel/read_anything/read_anything_screenshotter.h"

#include <string>

#include "base/base_paths.h"
#include "base/files/file_path.h"
#include "base/functional/callback_helpers.h"
#include "base/path_service.h"
#include "base/strings/stringprintf.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "components/paint_preview/browser/compositor_utils.h"
#include "components/paint_preview/browser/paint_preview_base_service.h"
#include "components/paint_preview/common/recording_map.h"
#include "mojo/public/cpp/base/proto_wrapper.h"
#include "skia/rusty_png_feature.h"
#include "third_party/skia/include/core/SkImage.h"
#include "third_party/skia/include/core/SkStream.h"
#include "third_party/skia/include/encode/SkPngEncoder.h"
#include "ui/gfx/geometry/rect.h"

constexpr size_t kMaxScreenshotFileSize = 50 * 1000L * 1000L;  // 50 MB.

namespace {

int debug_file_sequencer = 0;

// Crops the pixmap to the first non-transparent pixel in each row and column.
// This is necessary because the screenshotter sometimes returns a bitmap with
// transparent pixels outside the bounds of the page.
bool CropPixmap(const SkPixmap& pixmap, SkPixmap* cropped_pixmap) {
  SkIRect bounds = pixmap.bounds();
  int top = 0;
  int left = 0;
  int bottom = bounds.height();
  int right = bounds.width();
  while (top < bounds.height() && pixmap.getColor(0, top) == 0) {
    top++;
  }
  while (left < bounds.width() && pixmap.getColor(left, 0) == 0) {
    left++;
  }
  while (bottom >= 0 && pixmap.getColor(0, bottom - 1) == 0) {
    bottom--;
  }
  while (right >= 0 && pixmap.getColor(right - 1, 0) == 0) {
    right--;
  }
  SkIRect area = SkIRect::MakeLTRB(left, top, right, bottom);
  return pixmap.extractSubset(cropped_pixmap, area);
}

void WriteBitmapToPng(const SkBitmap& bitmap) {
  base::FilePath temp_dir;
  CHECK(base::PathService::Get(base::DIR_TEMP, &temp_dir));
  std::string screenshot_filename = base::StringPrintf(
      "csai_main_content_web_screenshot_%i.png", debug_file_sequencer++);
  std::string screenshot_filepath =
      temp_dir.AppendASCII(screenshot_filename).MaybeAsASCII();
  SkFILEWStream out_file(screenshot_filepath.c_str());
  if (!out_file.isValid()) {
    VLOG(2) << "Unable to create: " << screenshot_filepath;
    return;
  }

  SkPixmap cropped_pixmap;
  bool success_crop = CropPixmap(bitmap.pixmap(), &cropped_pixmap);
  if (!success_crop) {
    VLOG(2) << "Failed to crop pixmap: " << screenshot_filepath;
    return;
  }
  bool success_encode =
      skia::EncodePng(&out_file, cropped_pixmap, /*options=*/{});
  if (success_encode) {
    VLOG(2) << "Wrote debug file: " << screenshot_filepath;
  } else {
    VLOG(2) << "Failed to write debug file: " << screenshot_filepath;
  }
}

}  // namespace

ReadAnythingScreenshotter::ReadAnythingScreenshotter()
    : paint_preview::PaintPreviewBaseService(
          /*file_mixin=*/nullptr,  // in-memory captures
          /*policy=*/nullptr,      // all content is deemed amenable
          /*is_off_the_record=*/false),
      paint_preview_compositor_service_(nullptr,
                                        base::OnTaskRunnerDeleter(nullptr)),
      paint_preview_compositor_client_(nullptr,
                                       base::OnTaskRunnerDeleter(nullptr)) {
  paint_preview_compositor_service_ =
      paint_preview::StartCompositorService(base::BindOnce(
          &ReadAnythingScreenshotter::OnCompositorServiceDisconnected,
          weak_ptr_factory_.GetWeakPtr()));
  CHECK(paint_preview_compositor_service_);
}

ReadAnythingScreenshotter::~ReadAnythingScreenshotter() = default;

void ReadAnythingScreenshotter::RequestScreenshot(
    const raw_ptr<content::WebContents> web_contents) {
  if (!web_contents) {
    VLOG(2) << "The given web contents no longer valid";
    return;
  }

  // Start capturing via Paint Preview.
  CaptureParams capture_params;
  capture_params.web_contents = web_contents;
  capture_params.persistence =
      paint_preview::RecordingPersistence::kMemoryBuffer;
  capture_params.max_per_capture_size = kMaxScreenshotFileSize;
  CapturePaintPreview(
      capture_params,
      base::BindOnce(&ReadAnythingScreenshotter::OnScreenshotCaptured,
                     weak_ptr_factory_.GetWeakPtr()));
}

void ReadAnythingScreenshotter::OnScreenshotCaptured(
    paint_preview::PaintPreviewBaseService::CaptureStatus status,
    std::unique_ptr<paint_preview::CaptureResult> result) {
  if (status != PaintPreviewBaseService::CaptureStatus::kOk ||
      !result->capture_success) {
    VLOG(2) << base::StringPrintf(
        "Failed to capture a screenshot (CaptureStatus=%d)",
        static_cast<int>(status));
    return;
  }
  if (!paint_preview_compositor_client_) {
    paint_preview_compositor_client_ =
        paint_preview_compositor_service_->CreateCompositor(
            base::BindOnce(&ReadAnythingScreenshotter::SendCompositeRequest,
                           weak_ptr_factory_.GetWeakPtr(),
                           PrepareCompositeRequest(std::move(result))));
  } else {
    SendCompositeRequest(PrepareCompositeRequest(std::move(result)));
  }
}

paint_preview::mojom::PaintPreviewBeginCompositeRequestPtr
ReadAnythingScreenshotter::PrepareCompositeRequest(
    std::unique_ptr<paint_preview::CaptureResult> capture_result) {
  paint_preview::mojom::PaintPreviewBeginCompositeRequestPtr
      begin_composite_request =
          paint_preview::mojom::PaintPreviewBeginCompositeRequest::New();
  std::pair<paint_preview::RecordingMap, paint_preview::PaintPreviewProto>
      map_and_proto = paint_preview::RecordingMapFromCaptureResult(
          std::move(*capture_result));
  begin_composite_request->recording_map = std::move(map_and_proto.first);
  if (begin_composite_request->recording_map.empty()) {
    VLOG(2) << "Captured an empty screenshot";
    return nullptr;
  }
  begin_composite_request->preview =
      mojo_base::ProtoWrapper(std::move(map_and_proto.second));
  return begin_composite_request;
}

void ReadAnythingScreenshotter::SendCompositeRequest(
    paint_preview::mojom::PaintPreviewBeginCompositeRequestPtr
        begin_composite_request) {
  if (!begin_composite_request) {
    VLOG(2) << "Invalid begin_composite_request";
    return;
  }

  CHECK(paint_preview_compositor_client_);
  paint_preview_compositor_client_->BeginMainFrameComposite(
      std::move(begin_composite_request),
      base::BindOnce(&ReadAnythingScreenshotter::OnCompositeFinished,
                     weak_ptr_factory_.GetWeakPtr()));
}

void ReadAnythingScreenshotter::OnCompositorServiceDisconnected() {
  VLOG(2) << "Compositor service is disconnected";
  paint_preview_compositor_client_.reset();
  paint_preview_compositor_service_.reset();
}

void ReadAnythingScreenshotter::OnCompositeFinished(
    paint_preview::mojom::PaintPreviewCompositor::BeginCompositeStatus status,
    paint_preview::mojom::PaintPreviewBeginCompositeResponsePtr response) {
  if (status != paint_preview::mojom::PaintPreviewCompositor::
                    BeginCompositeStatus::kSuccess &&
      status != paint_preview::mojom::PaintPreviewCompositor::
                    BeginCompositeStatus::kPartialSuccess) {
    VLOG(2) << base::StringPrintf(
        "Failed to composite (BeginCompositeStatus=%d)",
        static_cast<int>(status));
    return;
  }
  // Start converting to a bitmap.
  RequestBitmapForMainFrame();
}

void ReadAnythingScreenshotter::RequestBitmapForMainFrame() {
  // Passing an empty `gfx::Rect` allows us to get a bitmap for the full page.
  paint_preview_compositor_client_->BitmapForMainFrame(
      gfx::Rect(), /*scale_factor=*/1.0,
      base::BindOnce(&ReadAnythingScreenshotter::OnBitmapReceived,
                     weak_ptr_factory_.GetWeakPtr()));
}

void ReadAnythingScreenshotter::OnBitmapReceived(
    paint_preview::mojom::PaintPreviewCompositor::BitmapStatus status,
    const SkBitmap& bitmap) {
  if (status != paint_preview::mojom::PaintPreviewCompositor::BitmapStatus::
                    kSuccess ||
      bitmap.empty()) {
    VLOG(2) << base::StringPrintf("Failed to get bitmap (BitmapStatus=%d)",
                                  static_cast<int>(status));
    return;
  }

  base::ThreadPool::PostTask(
      FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()},
      base::BindOnce(&WriteBitmapToPng, bitmap));
}