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 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
|
// 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 "base/test/scoped_feature_list.h"
#include "base/test/test_future.h"
#include "build/buildflag.h"
#include "cc/base/features.h"
#include "cc/test/pixel_comparator.h"
#include "cc/test/pixel_test_utils.h"
#include "components/viz/host/host_frame_sink_manager.h"
#include "content/browser/compositor/surface_utils.h"
#include "content/browser/renderer_host/frame_tree_node.h"
#include "content/browser/renderer_host/view_transition_opt_in_state.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/test/back_forward_cache_util.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/content_browser_test.h"
#include "content/shell/browser/shell.h"
#include "content/shell/browser/shell_download_manager_delegate.h"
#include "content/test/content_browser_test_utils_internal.h"
#include "mojo/public/cpp/bindings/sync_call_restrictions.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/default_handlers.h"
#include "services/viz/privileged/mojom/compositing/features.mojom-features.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/common/features_generated.h"
#include "ui/gfx/geometry/size.h"
namespace content {
class ViewTransitionBrowserTest : public ContentBrowserTest {
public:
class TestCondition : public CommitDeferringCondition {
public:
TestCondition(NavigationRequest& request, base::RunLoop* run_loop)
: CommitDeferringCondition(request), run_loop_(run_loop) {}
~TestCondition() override = default;
Result WillCommitNavigation(base::OnceClosure resume) override {
GetUIThreadTaskRunner()->PostTask(FROM_HERE, run_loop_->QuitClosure());
return Result::kDefer;
}
const char* TraceEventName() const override { return "TestCondition"; }
private:
raw_ptr<base::RunLoop> run_loop_;
};
ViewTransitionBrowserTest() {
feature_list_.InitWithFeatures(
/*enabled_features=*/
{viz::mojom::EnableVizTestApis},
/*disabled_features=*/{});
}
void SetUpOnMainThread() override {
ContentBrowserTest::SetUpOnMainThread();
host_resolver()->AddRule("*", "127.0.0.1");
embedded_test_server()->ServeFilesFromSourceDirectory(
GetTestDataFilePath());
net::test_server::RegisterDefaultHandlers(embedded_test_server());
ASSERT_TRUE(embedded_test_server()->Start());
}
void WaitForConditionsDone(NavigationRequest* request) {
// Inject a condition to know when the VT response has been received but
// before the NavigationRequest is notified.
run_loop_ = std::make_unique<base::RunLoop>();
request->RegisterCommitDeferringConditionForTesting(
std::make_unique<TestCondition>(*request, run_loop_.get()));
run_loop_->Run();
}
bool HasVTOptIn(RenderFrameHost* rfh) {
auto* opt_in_state = ViewTransitionOptInState::GetForCurrentDocument(
static_cast<RenderFrameHostImpl*>(rfh));
return opt_in_state &&
opt_in_state->same_origin_opt_in() ==
blink::mojom::ViewTransitionSameOriginOptIn::kEnabled;
}
private:
base::test::ScopedFeatureList feature_list_;
std::unique_ptr<base::RunLoop> run_loop_;
};
IN_PROC_BROWSER_TEST_F(ViewTransitionBrowserTest,
NavigationCancelledAfterScreenshot) {
// Start with a page which has an opt-in for VT.
GURL test_url(
embedded_test_server()->GetURL("/view_transitions/basic-vt-opt-in.html"));
ASSERT_TRUE(NavigateToURL(shell()->web_contents(), test_url));
WaitForCopyableViewInWebContents(shell()->web_contents());
TestNavigationManager navigation_manager(shell()->web_contents(), test_url);
ASSERT_TRUE(
ExecJs(shell()->web_contents(), "location.href = location.href;"));
// Wait for response and resume. The navigation should be blocked by the view
// transition condition.
ASSERT_TRUE(navigation_manager.WaitForResponse());
navigation_manager.ResumeNavigation();
auto* navigation_request =
NavigationRequest::From(navigation_manager.GetNavigationHandle());
ASSERT_TRUE(navigation_request);
ASSERT_TRUE(
navigation_request->IsCommitDeferringConditionDeferredForTesting());
ASSERT_FALSE(navigation_request->commit_params().view_transition_state);
WaitForConditionsDone(navigation_request);
ASSERT_TRUE(navigation_request->commit_params().view_transition_state);
mojo::ScopedAllowSyncCallForTesting allow_sync;
bool has_resources = false;
GetHostFrameSinkManager()
->GetFrameSinkManagerTestApi()
.HasUnclaimedViewTransitionResources(&has_resources);
ASSERT_TRUE(has_resources);
shell()->web_contents()->Stop();
ASSERT_FALSE(navigation_manager.was_committed());
GetHostFrameSinkManager()
->GetFrameSinkManagerTestApi()
.HasUnclaimedViewTransitionResources(&has_resources);
ASSERT_FALSE(has_resources);
// Ensure the old renderer discards the outgoing transition.
EXPECT_TRUE(ExecJs(
shell()->web_contents()->GetPrimaryMainFrame(),
"(async () => { await document.startViewTransition().ready; })()"));
}
IN_PROC_BROWSER_TEST_F(ViewTransitionBrowserTest,
NavigationCancelledBeforeScreenshot) {
// Start with a page which has an opt-in for VT.
GURL test_url(
embedded_test_server()->GetURL("/view_transitions/basic-vt-opt-in.html"));
ASSERT_TRUE(NavigateToURL(shell()->web_contents(), test_url));
WaitForCopyableViewInWebContents(shell()->web_contents());
TestNavigationManager navigation_manager(shell()->web_contents(), test_url);
ASSERT_TRUE(
ExecJs(shell()->web_contents(), "location.href = location.href;"));
// Wait for response and resume. The navigation should be blocked by the view
// transition condition.
ASSERT_TRUE(navigation_manager.WaitForResponse());
navigation_manager.ResumeNavigation();
auto* navigation_request =
NavigationRequest::From(navigation_manager.GetNavigationHandle());
ASSERT_TRUE(navigation_request);
ASSERT_TRUE(
navigation_request->IsCommitDeferringConditionDeferredForTesting());
ASSERT_FALSE(navigation_request->commit_params().view_transition_state);
// Stop the navigation while the screenshot request is in flight.
shell()->web_contents()->Stop();
ASSERT_FALSE(navigation_manager.was_committed());
// Ensure the old renderer discards the outgoing transition.
EXPECT_TRUE(ExecJs(
shell()->web_contents()->GetPrimaryMainFrame(),
"(async () => { await document.startViewTransition().ready; })()"));
}
IN_PROC_BROWSER_TEST_F(ViewTransitionBrowserTest,
OwnershipTransferredToNewRenderer) {
// Start with a page which has an opt-in for VT.
GURL test_url(
embedded_test_server()->GetURL("/view_transitions/basic-vt-opt-in.html"));
ASSERT_TRUE(NavigateToURL(shell()->web_contents(), test_url));
WaitForCopyableViewInWebContents(shell()->web_contents());
TestNavigationManager navigation_manager(shell()->web_contents(), test_url);
ASSERT_TRUE(
ExecJs(shell()->web_contents(), "location.href = location.href;"));
ASSERT_TRUE(navigation_manager.WaitForNavigationFinished());
ASSERT_TRUE(static_cast<RenderWidgetHostViewBase*>(
shell()->web_contents()->GetRenderWidgetHostView())
->HasViewTransitionResourcesForTesting());
}
// Ensure a browser-initiated navigation (i.e. typing URL into omnibox) does
// not trigger a view transitions.
IN_PROC_BROWSER_TEST_F(ViewTransitionBrowserTest,
NoOpOnBrowserInitiatedNavigations) {
// Start with a page which has an opt-in for VT.
GURL test_url(
embedded_test_server()->GetURL("/view_transitions/basic-vt-opt-in.html"));
ASSERT_TRUE(NavigateToURL(shell()->web_contents(), test_url));
GURL test_url_next(embedded_test_server()->GetURL(
"/view_transitions/basic-vt-opt-in.html?next"));
ASSERT_TRUE(NavigateToURL(shell()->web_contents(), test_url_next));
WaitForCopyableViewInWebContents(shell()->web_contents());
EXPECT_EQ(false, EvalJs(shell()->web_contents(), "had_incoming_transition"));
}
class ViewTransitionDownloadBrowserTest : public ViewTransitionBrowserTest {
public:
void SetUpOnMainThread() override {
ViewTransitionBrowserTest::SetUpOnMainThread();
// Set up a test download directory, in order to prevent prompting for
// handling downloads.
ASSERT_TRUE(downloads_directory_.CreateUniqueTempDir());
ShellDownloadManagerDelegate* delegate =
static_cast<ShellDownloadManagerDelegate*>(
shell()
->web_contents()
->GetBrowserContext()
->GetDownloadManagerDelegate());
delegate->SetDownloadBehaviorForTesting(downloads_directory_.GetPath());
}
private:
base::ScopedTempDir downloads_directory_;
};
IN_PROC_BROWSER_TEST_F(ViewTransitionDownloadBrowserTest,
NavigationToDownloadLink) {
GURL test_url(
embedded_test_server()->GetURL("/view_transitions/basic-vt-opt-in.html"));
ASSERT_TRUE(NavigateToURL(shell()->web_contents(), test_url));
WaitForCopyableViewInWebContents(shell()->web_contents());
GURL download_url(embedded_test_server()->GetURL("/download-test1.lib"));
TestNavigationManager navigation_manager(shell()->web_contents(),
download_url);
ASSERT_TRUE(ExecJs(shell()->web_contents(),
JsReplace("location.href = $1", download_url)));
// Wait for response and resume. The navigation should not be blocked by the
// view transition condition.
ASSERT_TRUE(navigation_manager.WaitForRequestStart());
ASSERT_TRUE(HasVTOptIn(shell()->web_contents()->GetPrimaryMainFrame()));
auto* navigation_request =
NavigationRequest::From(navigation_manager.GetNavigationHandle());
ASSERT_EQ(
shell()->web_contents()->GetPrimaryMainFrame()->GetLastCommittedOrigin(),
navigation_request->GetTentativeOriginAtRequestTime());
ASSERT_TRUE(navigation_manager.WaitForNavigationFinished());
ASSERT_FALSE(navigation_manager.was_committed());
}
class ViewTransitionBrowserTestTraverse
: public ViewTransitionBrowserTest,
public testing::WithParamInterface<bool> {
public:
bool BFCacheEnabled() const { return GetParam(); }
bool NavigateBack(GURL back_url, WebContents* contents = nullptr) {
if (!contents) {
contents = shell()->web_contents();
}
// We need to trigger the navigation *after* executing the script below so
// the event handlers the script relies on are set before they're dispatched
// by the navigation.
//
// We pass this as a callback to EvalJs so the navigation is initiated
// before we wait for the script result since it relies on events dispatched
// during the navigation.
auto trigger_navigation = base::BindOnce(
&ViewTransitionBrowserTestTraverse::TriggerBackNavigation,
base::Unretained(this), back_url, contents);
auto result =
EvalJs(contents,
JsReplace(
R"(
(async () => {
let navigateFired = false;
navigation.onnavigate = (event) => {
navigateFired = (event.navigationType === "traverse");
};
let pageswapfired = new Promise((resolve) => {
onpageswap = (e) => {
if (!navigateFired || e.viewTransition == null) {
resolve(null);
return;
}
activation = e.activation;
resolve(activation);
};
});
let result = await pageswapfired;
return result != null;
})();
)"),
EXECUTE_SCRIPT_DEFAULT_OPTIONS, ISOLATED_WORLD_ID_GLOBAL,
std::move(trigger_navigation));
return result.ExtractBool();
}
void TriggerBackNavigation(GURL back_url, WebContents* web_contents) {
if (BFCacheEnabled()) {
TestActivationManager manager(web_contents, back_url);
web_contents->GetController().GoBack();
manager.WaitForNavigationFinished();
} else {
TestNavigationManager manager(web_contents, back_url);
web_contents->GetController().GoBack();
ASSERT_TRUE(manager.WaitForNavigationFinished());
}
}
};
IN_PROC_BROWSER_TEST_P(ViewTransitionBrowserTestTraverse,
NavigateEventFiresBeforeCapture) {
if (!BFCacheEnabled()) {
DisableBackForwardCacheForTesting(
shell()->web_contents(),
BackForwardCache::DisableForTestingReason::TEST_REQUIRES_NO_CACHING);
} else if (!base::FeatureList::IsEnabled(features::kBackForwardCache)) {
GTEST_SKIP();
}
GURL test_url(
embedded_test_server()->GetURL("/view_transitions/basic-vt-opt-in.html"));
ASSERT_TRUE(NavigateToURL(shell()->web_contents(), test_url));
GURL second_url(embedded_test_server()->GetURL(
"/view_transitions/basic-vt-opt-in.html?new"));
ASSERT_TRUE(NavigateToURL(shell()->web_contents(), second_url));
WaitForCopyableViewInWebContents(shell()->web_contents());
auto& nav_controller = static_cast<NavigationControllerImpl&>(
shell()->web_contents()->GetController());
ASSERT_TRUE(nav_controller.CanGoBack());
ASSERT_TRUE(NavigateBack(test_url));
}
// A session restore (e.g. "Duplicate Tab", "Undo Close Tab") uses RESTORE
// navigation types when traversing the session history. Ensure these
// navigations trigger a view transition.
IN_PROC_BROWSER_TEST_P(ViewTransitionBrowserTestTraverse,
TransitionOnSessionRestoreTraversal) {
// A restored session will never have its session history in BFCache so
// there's no need to run a BFCache version of the test.
if (BFCacheEnabled()) {
GTEST_SKIP();
}
// Start with a page which has an opt-in for VT.
GURL url_a(
embedded_test_server()->GetURL("/view_transitions/basic-vt-opt-in.html"));
ASSERT_TRUE(NavigateToURL(shell()->web_contents(), url_a));
// Navigate to another page with an opt-in. (There's no transition due to
// being browser-initiated)
GURL url_b(embedded_test_server()->GetURL(
"/view_transitions/basic-vt-opt-in.html?next"));
ASSERT_TRUE(NavigateToURL(shell()->web_contents(), url_b));
// Clone the tab and load the page. Note: the cloned web contents must be put
// into a window to generate BeginFrames which are required since a view
// transition will not trigger unless a frame has been generated and the page
// revealed.
std::unique_ptr<WebContents> new_tab = shell()->web_contents()->Clone();
WebContentsImpl* new_tab_impl = static_cast<WebContentsImpl*>(new_tab.get());
shell()->AddNewContents(nullptr, std::move(new_tab), url_b,
WindowOpenDisposition::NEW_FOREGROUND_TAB,
blink::mojom::WindowFeatures(), false, nullptr);
NavigationController& new_controller = new_tab_impl->GetController();
{
TestNavigationObserver clone_observer(new_tab_impl);
new_controller.LoadIfNecessary();
clone_observer.Wait();
}
// Ensure the page has been revealed before navigating back so that a
// transition will be triggered.
WaitForCopyableViewInWebContents(new_tab_impl);
// TODO(crbug.com/331226127) Intentionally ignore the return value as the
// navigation API (erroneously?) doesn't fire events for restored traversals.
NavigateBack(url_a, new_tab_impl);
// Ensure a frame has been generated so that the reveal event would have been
// fired.
WaitForCopyableViewInWebContents(new_tab_impl);
EXPECT_EQ(true, EvalJs(new_tab_impl, "had_incoming_transition"));
}
INSTANTIATE_TEST_SUITE_P(P,
ViewTransitionBrowserTestTraverse,
::testing::Bool());
class ViewTransitionCaptureTest
: public ContentBrowserTest,
public ::testing::WithParamInterface<std::pair<bool, std::string>> {
public:
ViewTransitionCaptureTest() {
EnablePixelOutput(1.f);
feature_list_.InitWithFeatures(
/*enabled_features=*/
{viz::mojom::EnableVizTestApis,
features::kViewTransitionCaptureAndDisplay},
/*disabled_features=*/
{blink::features::kPaintHolding});
}
void SetUpOnMainThread() override {
ContentBrowserTest::SetUpOnMainThread();
host_resolver()->AddRule("*", "127.0.0.1");
embedded_test_server()->ServeFilesFromSourceDirectory(
GetTestDataFilePath());
net::test_server::RegisterDefaultHandlers(embedded_test_server());
ASSERT_TRUE(embedded_test_server()->Start());
}
protected:
SkBitmap TakeScreenshot() {
base::test::TestFuture<const SkBitmap&> future_bitmap;
shell()->web_contents()->GetRenderWidgetHostView()->CopyFromSurface(
gfx::Rect(), gfx::Size(), future_bitmap.GetCallback());
return future_bitmap.Take();
}
void WaitForSurfaceAnimationManager(RenderFrameHost* render_frame_host) {
mojo::ScopedAllowSyncCallForTesting sync_scope;
GetHostFrameSinkManager()
->GetFrameSinkManagerTestApi()
.WaitForSurfaceAnimationManager(
static_cast<RenderFrameHostImpl*>(render_frame_host)
->GetRenderWidgetHost()
->GetFrameSinkId());
}
private:
base::test::ScopedFeatureList feature_list_;
};
IN_PROC_BROWSER_TEST_P(ViewTransitionCaptureTest,
ViewTransitionNoArtifactDuringCapture) {
const auto& [frametest, url] = GetParam();
GURL test_url(embedded_test_server()->GetURL(url));
auto* web_contents = shell()->web_contents();
ASSERT_TRUE(NavigateToURL(web_contents, test_url));
shell()->ResizeWebContentForTests(gfx::Size(100, 100));
ASSERT_EQ(EvalJs(web_contents, JsReplace(R"(
new Promise(resolve => {
requestAnimationFrame(() => {
requestAnimationFrame(() => resolve("ok"));
});
}))")),
"ok");
WaitForCopyableViewInWebContents(shell()->web_contents());
SkBitmap before_bitmap = TakeScreenshot();
// Sanity to see that we've captured something.
ASSERT_NE(before_bitmap.getColor(5, 5), 0u);
// This starts a view transition with a callback that signals that we're ok
// to capture, but otherwise never finishes running the callback.
if (frametest) {
ASSERT_EQ(EvalJs(web_contents, JsReplace(R"(
new Promise(dom_callback_started => {
frame.contentDocument.startViewTransition(async () => {
dom_callback_started('ok');
await new Promise(() => {});
});
}))")),
"ok");
} else {
ASSERT_EQ(EvalJs(web_contents, JsReplace(R"(
new Promise(dom_callback_started => {
document.startViewTransition(async () => {
dom_callback_started('ok');
await new Promise(() => {});
});
}))")),
"ok");
}
WaitForSurfaceAnimationManager(
shell()->web_contents()->GetPrimaryMainFrame());
auto after_bitmap = TakeScreenshot();
ASSERT_EQ(before_bitmap.width(), after_bitmap.width());
ASSERT_EQ(before_bitmap.height(), after_bitmap.height());
cc::FuzzyPixelComparator comparator;
// Allow 50% of pixels to different by at most 3 in all channels.
// The small differences on some platforms seem to be noise, and don't
// invalidate the test intent.
comparator.SetAbsErrorLimit(255, 3);
comparator.SetErrorPixelsPercentageLimit(0, 50);
EXPECT_TRUE(cc::MatchesBitmap(after_bitmap, before_bitmap, comparator));
}
INSTANTIATE_TEST_SUITE_P(
P,
ViewTransitionCaptureTest,
// The pair parameter has the following meaning:
// - The first boolean indicates whether this test should invoke
// startViewTransition() on the `frame` DOM element's contentDocument (if
// true) or on the main frame's document (if false).
// - The second string indicates the location of the test to load.
testing::Values(
std::make_pair(false, "/view_transitions/parent-child.html"),
std::make_pair(false, "/view_transitions/parent-child-opacity.html"),
std::make_pair(true,
"/view_transitions/parent-child-opacity-iframe.html")));
} // namespace content
|