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
|
// Copyright 2020 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/ash/clipboard/clipboard_image_model_request.h"
#include <memory>
#include "ash/public/cpp/clipboard_history_controller.h"
#include "ash/public/cpp/scoped_clipboard_history_pause.h"
#include "base/base64.h"
#include "base/metrics/histogram.h"
#include "base/metrics/histogram_macros.h"
#include "base/task/sequenced_task_runner.h"
#include "chromeos/ash/components/browser_context_helper/browser_context_helper.h"
#include "components/account_id/account_id.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/web_contents.h"
#include "ui/aura/window.h"
#include "ui/base/clipboard/clipboard_data.h"
#include "ui/base/clipboard/clipboard_non_backed.h"
#include "ui/base/data_transfer_policy/data_transfer_endpoint.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/gfx/image/image_skia_operations.h"
#include "ui/gfx/image/image_skia_rep.h"
#include "ui/views/controls/webview/webview.h"
#include "ui/views/widget/widget.h"
#include "url/gurl.h"
namespace {
// The maximum size that the web contents can be. It caps the memory consumption
// incurred by web contents rendering.
constexpr gfx::Size kMaxWebContentsSize(2000, 2000);
// The initial size of the NativeView to force painting in an inactive shown
// widget for auto-resize mode.
constexpr gfx::Size kAutoResizeModeInitialSize(1, 1);
ClipboardImageModelRequest::TestParams* g_test_params = nullptr;
content::BrowserContext* GetBrowserContextByAccountId(
const AccountId& account_id) {
auto* browser_context =
ash::BrowserContextHelper::Get()->GetBrowserContextByAccountId(
account_id);
CHECK(browser_context);
return browser_context;
}
} // namespace
// ClipboardImageModelFactory::Params: -----------------------------------------
ClipboardImageModelRequest::Params::Params(const base::UnguessableToken& id,
const std::string& html_markup,
const gfx::Size& bounding_box_size,
ImageModelCallback callback)
: id(id),
html_markup(html_markup),
bounding_box_size(bounding_box_size),
callback(std::move(callback)) {}
ClipboardImageModelRequest::Params::Params(Params&&) = default;
ClipboardImageModelRequest::Params&
ClipboardImageModelRequest::Params::operator=(Params&&) = default;
ClipboardImageModelRequest::Params::~Params() = default;
// ClipboardImageModelFactory::TestParams: -------------------------------------
ClipboardImageModelRequest::TestParams::TestParams(
RequestStopCallback callback,
const std::optional<bool>& enforce_auto_resize)
: callback(callback), enforce_auto_resize(enforce_auto_resize) {}
ClipboardImageModelRequest::TestParams::~TestParams() = default;
// ClipboardImageModelRequest------------- -------------------------------------
ClipboardImageModelRequest::ScopedClipboardModifier::ScopedClipboardModifier(
const std::string& html_markup) {
auto* clipboard = ui::ClipboardNonBacked::GetForCurrentThread();
ui::DataTransferEndpoint data_dst(ui::EndpointType::kClipboardHistory);
const auto* current_data = clipboard->GetClipboardData(&data_dst);
// No need to replace the clipboard contents if the markup is the same.
if (current_data && (html_markup == current_data->markup_data())) {
return;
}
// Put |html_markup| on the clipboard temporarily so it can be pasted into
// the WebContents. This is preferable to directly loading |html_markup_| in a
// data URL because pasting the data into WebContents sanitizes the markup.
// TODO(crbug.com/40729185): Sanitize copied HTML prior to storing it
// in the clipboard buffer. Then |html_markup_| can be loaded from a data URL
// and will not need to be pasted in this manner.
auto new_data = std::make_unique<ui::ClipboardData>();
new_data->set_markup_data(html_markup);
scoped_clipboard_history_pause_ =
ash::ClipboardHistoryController::Get()->CreateScopedPause();
replaced_clipboard_data_ = clipboard->WriteClipboardData(std::move(new_data));
}
ClipboardImageModelRequest::ScopedClipboardModifier::
~ScopedClipboardModifier() {
if (!replaced_clipboard_data_) {
return;
}
ui::ClipboardNonBacked::GetForCurrentThread()->WriteClipboardData(
std::move(replaced_clipboard_data_));
}
ClipboardImageModelRequest::ClipboardImageModelRequest(
const AccountId& account_id,
base::RepeatingClosure on_request_finished_callback)
: widget_(std::make_unique<views::Widget>()),
web_view_(new views::WebView(GetBrowserContextByAccountId(account_id))),
on_request_finished_callback_(std::move(on_request_finished_callback)),
request_creation_time_(base::TimeTicks::Now()) {
views::Widget::InitParams widget_params(
views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET,
views::Widget::InitParams::TYPE_WINDOW_FRAMELESS);
widget_params.name = "ClipboardImageModelRequest";
widget_->Init(std::move(widget_params));
widget_->SetContentsView(web_view_);
Observe(web_view_->GetWebContents());
web_contents()->SetDelegate(this);
}
ClipboardImageModelRequest::~ClipboardImageModelRequest() {
UMA_HISTOGRAM_TIMES("Ash.ClipboardHistory.ImageModelRequest.Lifetime",
base::TimeTicks::Now() - request_creation_time_);
}
void ClipboardImageModelRequest::Start(Params&& params) {
DCHECK(!deliver_image_model_callback_);
DCHECK(params.callback);
DCHECK_EQ(base::UnguessableToken(), request_id_);
request_id_ = std::move(params.id);
html_markup_ = params.html_markup;
deliver_image_model_callback_ = std::move(params.callback);
timeout_timer_.Start(FROM_HERE, base::Seconds(10), this,
&ClipboardImageModelRequest::OnTimeout);
request_start_time_ = base::TimeTicks::Now();
// Begin the document with the proper charset, this should prevent strange
// looking characters from showing up in the render in some cases.
std::string html_document(
"<!DOCTYPE html>"
"<html>"
" <head><meta charset=\"UTF-8\"></meta></head>"
" <body contenteditable='true' style=\"overflow: hidden\"> "
" <script>"
// Focus the Contenteditable body to ensure WebContents::Paste() reaches
// the body.
" document.body.focus();"
" </script>"
" </body>"
"</html");
std::string encoded_html = base::Base64Encode(html_document);
constexpr char kDataURIPrefix[] = "data:text/html;base64,";
web_contents()->GetController().LoadURLWithParams(
content::NavigationController::LoadURLParams(
GURL(kDataURIPrefix + encoded_html)));
widget_->ShowInactive();
// Adapt to the render widget host view whose device scale factor is not one.
bounding_box_size_ = gfx::ScaleToCeiledSize(
params.bounding_box_size,
web_contents()->GetRenderWidgetHostView()->GetDeviceScaleFactor());
}
void ClipboardImageModelRequest::Stop(RequestStopReason stop_reason) {
UMA_HISTOGRAM_ENUMERATION("Ash.ClipboardHistory.ImageModelRequest.StopReason",
stop_reason);
DCHECK(!request_start_time_.is_null());
UMA_HISTOGRAM_TIMES("Ash.ClipboardHistory.ImageModelRequest.Runtime",
base::TimeTicks::Now() - request_start_time_);
request_start_time_ = base::TimeTicks();
scoped_clipboard_modifier_.reset();
weak_ptr_factory_.InvalidateWeakPtrs();
copy_surface_weak_ptr_factory_.InvalidateWeakPtrs();
timeout_timer_.Stop();
widget_->Hide();
deliver_image_model_callback_.Reset();
request_id_ = base::UnguessableToken();
did_stop_loading_ = false;
on_request_finished_callback_.Run();
if (g_test_params && g_test_params->callback) {
g_test_params->callback.Run(ShouldEnableAutoResizeMode());
}
}
ClipboardImageModelRequest::Params
ClipboardImageModelRequest::StopAndGetParams() {
DCHECK(IsRunningRequest());
Params params(request_id_, html_markup_, bounding_box_size_,
std::move(deliver_image_model_callback_));
Stop(RequestStopReason::kRequestCanceled);
return params;
}
bool ClipboardImageModelRequest::IsModifyingClipboard() const {
return scoped_clipboard_modifier_.has_value();
}
bool ClipboardImageModelRequest::IsRunningRequest(
std::optional<base::UnguessableToken> request_id) const {
return request_id.has_value() ? *request_id == request_id_
: !request_id_.is_empty();
}
void ClipboardImageModelRequest::ResizeDueToAutoResize(
content::WebContents* web_contents,
const gfx::Size& new_size) {
web_contents->GetNativeView()->SetBounds(gfx::Rect(gfx::Point(), new_size));
// `ResizeDueToAutoResize()` can be called before and/or after
// DidStopLoading(). If `DidStopLoading()` has not been called, wait for the
// next resize before copying the surface.
if (!web_contents->IsLoading()) {
PostCopySurfaceTask();
}
}
void ClipboardImageModelRequest::DidStopLoading() {
// `DidStopLoading()` can be called multiple times after a paste. We are only
// interested in the initial load of the data URL.
if (did_stop_loading_) {
return;
}
did_stop_loading_ = true;
// Modify the clipboard so `html_markup_` can be pasted into the WebContents.
scoped_clipboard_modifier_.emplace(html_markup_);
web_contents()->GetRenderViewHost()->GetWidget()->InsertVisualStateCallback(
base::BindOnce(&ClipboardImageModelRequest::OnVisualStateChangeFinished,
weak_ptr_factory_.GetWeakPtr()));
// After navigating to a new page, the surface id is invalidated. As a result,
// copy from surface is disabled as well. Setting the window's bounds should
// generate a new local surface id. Hence, window bounds setting should be
// after the web navigation.
// Changing auto resize mode does not generate a new local surface id while
// setting the window bounds will. As a result, enabling/disabling the auto
// resize mode has to precede the window bounds setting. Otherwise the change
// in the window bounds may trigger the unnecessary update in the view layout
// for the obsolete auto resize state. This layout update will consume the
// newly generated local surface id. Then it will cause a crash when the
// layout update brought by the change in the auto resize state arrives.
if (ShouldEnableAutoResizeMode()) {
web_contents()->GetRenderWidgetHostView()->EnableAutoResize(
kAutoResizeModeInitialSize, kMaxWebContentsSize);
web_contents()->GetNativeView()->SetBounds(
gfx::Rect(kAutoResizeModeInitialSize));
} else {
web_contents()->GetRenderWidgetHostView()->DisableAutoResize(
bounding_box_size_);
web_contents()->GetNativeView()->SetBounds(gfx::Rect(bounding_box_size_));
}
// TODO(https://crbug.com/1149556): Clipboard Contents could be overwritten
// prior to the `WebContents::Paste()` completing.
web_contents()->Paste();
}
// static
void ClipboardImageModelRequest::SetTestParams(TestParams* test_params) {
// Supports only setting `g_test_params` or resetting it.
DCHECK(!g_test_params || !test_params);
g_test_params = test_params;
}
void ClipboardImageModelRequest::OnVisualStateChangeFinished(bool done) {
if (!done) {
return;
}
scoped_clipboard_modifier_.reset();
PostCopySurfaceTask();
}
void ClipboardImageModelRequest::PostCopySurfaceTask() {
if (!deliver_image_model_callback_) {
return;
}
// Debounce calls to `CopySurface()`. `DidStopLoading()` and
// `ResizeDueToAutoResize()` can be called multiple times in the same task
// sequence. Wait for the final update before copying the surface.
copy_surface_weak_ptr_factory_.InvalidateWeakPtrs();
DCHECK(
web_contents()->GetRenderWidgetHostView()->IsSurfaceAvailableForCopy());
base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&ClipboardImageModelRequest::CopySurface,
copy_surface_weak_ptr_factory_.GetWeakPtr()),
base::Milliseconds(250));
}
void ClipboardImageModelRequest::CopySurface() {
content::RenderWidgetHostView* source_view =
web_contents()->GetRenderViewHost()->GetWidget()->GetView();
if (source_view->GetViewBounds().size().IsEmpty()) {
Stop(RequestStopReason::kEmptyResult);
return;
}
// There is no guarantee CopyFromSurface will call OnCopyComplete. If this
// takes too long, this will be cleaned up by |timeout_timer_|.
source_view->CopyFromSurface(
/*src_rect=*/gfx::Rect(), /*output_size=*/gfx::Size(),
base::BindOnce(&ClipboardImageModelRequest::OnCopyComplete,
weak_ptr_factory_.GetWeakPtr(),
source_view->GetDeviceScaleFactor()));
}
void ClipboardImageModelRequest::OnCopyComplete(float device_scale_factor,
const SkBitmap& bitmap) {
if (!deliver_image_model_callback_) {
Stop(RequestStopReason::kMultipleCopyCompletion);
return;
}
std::move(deliver_image_model_callback_)
.Run(ui::ImageModel::FromImageSkia(
gfx::ImageSkia(gfx::ImageSkiaRep(bitmap, device_scale_factor))));
Stop(RequestStopReason::kFulfilled);
}
void ClipboardImageModelRequest::OnTimeout() {
DCHECK(deliver_image_model_callback_);
Stop(RequestStopReason::kTimeout);
}
bool ClipboardImageModelRequest::ShouldEnableAutoResizeMode() const {
// Prefer to use the auto resize mode specified by `g_test_params` if any.
if (g_test_params && g_test_params->enforce_auto_resize) {
return *g_test_params->enforce_auto_resize;
}
// Use auto resize mode if `bounding_box_size_` is not meaningful.
if (bounding_box_size_.IsEmpty()) {
return true;
}
// Use auto resize mode if the copied web content is too big to render.
return !gfx::Rect(kMaxWebContentsSize)
.Contains(gfx::Rect(bounding_box_size_));
}
|