diff --git a/.gn b/.gn index c894baf..80cd194 100644 --- a/.gn +++ b/.gn
@@ -80,6 +80,7 @@ "//chrome/test:sync_integration_tests", "//chrome/test:sync_integration_test_support", "//chrome/test:sync_performance_tests", + "//chrome/test:test_support", "//chrome/test:test_support_ui", "//chrome/test:test_support_ui_android", "//chrome/test:test_support_unit",
diff --git a/AUTHORS b/AUTHORS index 47dc9b0..5a9c35a 100644 --- a/AUTHORS +++ b/AUTHORS
@@ -1198,6 +1198,7 @@ Zach Bjornson <zbbjornson@gmail.com> Zeno Albisser <zeno.albisser@digia.com> Zeqin Chen <talonchen@tencent.com> +Zhang Hao <15686357310a@gmail.com> Zhaoze Zhou <zhaoze.zhou@partner.samsung.com> Zheda Chen <zheda.chen@intel.com> Zheng Chuang <zhengchuangscu@gmail.com>
diff --git a/BUILD.gn b/BUILD.gn index cbf465a..21298781 100644 --- a/BUILD.gn +++ b/BUILD.gn
@@ -114,6 +114,15 @@ deps += [ ":webui_closure_compile" ] } + if (!is_ios && !is_android && !is_chromecast) { + deps += [ + "//ui/accessibility:accessibility_perftests", + "//ui/accessibility:accessibility_unittests", + "//ui/accessibility/extensions:extension_tests", + "//ui/accessibility/extensions:extensions", + ] + } + if (!is_ios && !is_android && !is_chromecast && !is_fuchsia) { deps += [ "//chrome", @@ -161,10 +170,6 @@ "//tools/perf/clear_system_cache", "//tools/polymer:polymer_tools_python_unittests", "//tools/privacy_budget:privacy_budget_tools", - "//ui/accessibility:accessibility_perftests", - "//ui/accessibility:accessibility_unittests", - "//ui/accessibility/extensions:extension_tests", - "//ui/accessibility/extensions:extensions", ] }
diff --git a/DEPS b/DEPS index 54090e1..f450f2a 100644 --- a/DEPS +++ b/DEPS
@@ -177,7 +177,7 @@ # luci-go CIPD package version. # Make sure the revision is uploaded by infra-packagers builder. # https://ci.chromium.org/p/infra-internal/g/infra-packagers/console - 'luci_go': 'git_revision:1b257aacd4934e5a8b2508b240ffc7d866df9273', + 'luci_go': 'git_revision:fa78eb7ab25ca5d574c0741c8c1a02d6fd7ed66d', # This can be overridden, e.g. with custom_vars, to build clang from HEAD # instead of downloading the prebuilt pinned revision. @@ -209,11 +209,11 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling Skia # and whatever else without interference from each other. - 'skia_revision': '703f68e660ab05db9a14b4a9b67f7146a39d75ca', + 'skia_revision': 'bb4bf6eaafd3b70ae89b64b00de94d3a0978dccf', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling V8 # and whatever else without interference from each other. - 'v8_revision': '1f85f125ecdfee8f8e69f616a9dad385b4ecba69', + 'v8_revision': '90948ff16986234c86a25cb4d3e5643693faea9d', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling swarming_client # and whatever else without interference from each other. @@ -256,7 +256,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling NaCl # and whatever else without interference from each other. - 'nacl_revision': '86962315f50399ad80c3c518277852778c0eb462', + 'nacl_revision': '01c5602dc3e493d34ada24da50ebf5d411277be1', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling freetype # and whatever else without interference from each other. @@ -288,7 +288,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling devtools-frontend # and whatever else without interference from each other. - 'devtools_frontend_revision': '1484a2e537da537ecb4e53e61d85b477e465ed17', + 'devtools_frontend_revision': '83da551ffadcbb5054b9d0cec64755c4922afa8e', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libprotobuf-mutator # and whatever else without interference from each other. @@ -384,11 +384,11 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. - 'libjxl_revision': '9a8f5195e4d1c45112fd65f184ebe115f4163ba2', + 'libjxl_revision': '040eae8105b61b312a67791213091103f4c0d034', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. - 'highway_revision': '6cf3e578ee3f3c8f61668e0cb7c0f12f4b8d876e', + 'highway_revision': 'ca1a57c342cd815053abfcffa29b44eaead4f20b', # If you change this, also update the libc++ revision in # //buildtools/deps_revisions.gni. @@ -961,7 +961,7 @@ # For Linux and Chromium OS. 'src/third_party/cros_system_api': { - 'url': Var('chromium_git') + '/chromiumos/platform2/system_api.git' + '@' + 'a174dc2a7a92856ad39ae3c0e2890e856151d7ab', + 'url': Var('chromium_git') + '/chromiumos/platform2/system_api.git' + '@' + '68a81d40157b67aaf937483f2c3b4692e8b109ff', 'condition': 'checkout_linux', }, @@ -1338,7 +1338,7 @@ }, 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + '2b0fcfa349ac5ccd7851e459ec683a8e687f7c75', + Var('android_git') + '/platform/external/perfetto.git' + '@' + '2e55bf4f07c1dd4ab28fff9f468b4eb33731670f', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + '6f3e5028eb65d0b4c5fdd792106ac4c84eee1eb3', @@ -1525,7 +1525,7 @@ 'src/third_party/usrsctp/usrsctplib': Var('chromium_git') + '/external/github.com/sctplab/usrsctp' + '@' + '0bd8b8110bc1a388649e504de1e673114e91013f', - 'src/third_party/vulkan-deps': '{chromium_git}/vulkan-deps@69094b7855b5b314f6af08c10bea65934f3385d0', + 'src/third_party/vulkan-deps': '{chromium_git}/vulkan-deps@cbc752b97bc51a1d4068c81a425acb4a818fa8f1', 'src/third_party/vulkan_memory_allocator': Var('chromium_git') + '/external/github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator.git' + '@' + '732a76d9d3c70d6aa487216495eeb28518349c3a', @@ -1552,7 +1552,7 @@ Var('chromium_git') + '/external/github.com/gpuweb/cts.git' + '@' + '239db71432f4e4fe1f6192a7d54717701ef84f66', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + '1c5c2178fed4068a94c4d3a71a7da428cac22151', + Var('webrtc_git') + '/src.git' + '@' + '793bac569fdf1be16cbf24d7871d20d00bbec81b', 'src/third_party/libgifcodec': Var('skia_git') + '/libgifcodec' + '@'+ Var('libgifcodec_revision'), @@ -1599,7 +1599,7 @@ 'packages': [ { 'package': 'skia/tools/goldctl/mac-amd64', - 'version': 'wEpZZg5Ap8EImS0KyVLAaILjjArMqHjI4T4y2MKKd5MC', + 'version': 'aG3drSoyskf8FOxdSDXo_p3ub85yK9mX_DmXJa605cUC', }, ], 'dep_type': 'cipd', @@ -1613,7 +1613,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@92d7f56527ca9051316c46c35f2654ce0d668482', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@3b957b128c903fff268e1889d8d0ed4566179f32', 'condition': 'checkout_src_internal', },
diff --git a/android_webview/browser/aw_autofill_client.cc b/android_webview/browser/aw_autofill_client.cc index 38a84ca2..faf3e3d 100644 --- a/android_webview/browser/aw_autofill_client.cc +++ b/android_webview/browser/aw_autofill_client.cc
@@ -177,6 +177,7 @@ void AwAutofillClient::ConfirmSaveAddressProfile( const autofill::AutofillProfile& profile, const autofill::AutofillProfile* original_profile, + SaveAddressProfilePromptOptions options, AddressProfileSavePromptCallback callback) { NOTIMPLEMENTED(); }
diff --git a/android_webview/browser/aw_autofill_client.h b/android_webview/browser/aw_autofill_client.h index 07ab97a..4be1b68 100644 --- a/android_webview/browser/aw_autofill_client.h +++ b/android_webview/browser/aw_autofill_client.h
@@ -104,6 +104,7 @@ void ConfirmSaveAddressProfile( const autofill::AutofillProfile& profile, const autofill::AutofillProfile* original_profile, + SaveAddressProfilePromptOptions options, AddressProfileSavePromptCallback callback) override; bool HasCreditCardScanFeature() override; void ScanCreditCard(CreditCardScanCallback callback) override;
diff --git a/ash/BUILD.gn b/ash/BUILD.gn index a3d7ce8c..d7c50e9 100644 --- a/ash/BUILD.gn +++ b/ash/BUILD.gn
@@ -2616,7 +2616,6 @@ ":*", "//ash/app_list:*", "//ash/shortcut_viewer:*", - "//chrome/test:test_support", "//components/exo:*", "//components/exo/wayland:*", "//ash/public/cpp/external_arc:*",
diff --git a/ash/accessibility/magnifier/partial_magnification_controller.cc b/ash/accessibility/magnifier/partial_magnification_controller.cc index 76273f4c..89f9ae3 100644 --- a/ash/accessibility/magnifier/partial_magnification_controller.cc +++ b/ash/accessibility/magnifier/partial_magnification_controller.cc
@@ -46,24 +46,9 @@ Shell::Get()->RemovePreTargetHandler(this); } -void PartialMagnificationController::AddObserver( - PartialMagnificationController::Observer* observer) { - observers_.AddObserver(observer); -} - -void PartialMagnificationController::RemoveObserver( - PartialMagnificationController::Observer* observer) { - observers_.RemoveObserver(observer); -} - void PartialMagnificationController::SetEnabled(bool enabled) { - if (is_enabled_ == enabled) - return; - is_enabled_ = enabled; SetActive(false); - for (auto& observer : observers_) - observer.OnPartialMagnificationStateChanged(enabled); } void PartialMagnificationController::SwitchTargetRootWindowIfNeeded( @@ -82,10 +67,6 @@ OnLocatedEvent(event, event->pointer_details()); } -void PartialMagnificationController::OnMouseEvent(ui::MouseEvent* event) { - OnLocatedEvent(event, event->pointer_details()); -} - void PartialMagnificationController::SetActive(bool active) { // Fail if we're trying to activate while disabled. DCHECK(is_enabled_ || !active); @@ -107,12 +88,6 @@ if (!is_enabled_) return; - if (allow_mouse_following_ && - pointer_details.pointer_type == ui::EventPointerType::kMouse) { - SetActive(true); - return; - } - if (pointer_details.pointer_type != ui::EventPointerType::kPen) return;
diff --git a/ash/accessibility/magnifier/partial_magnification_controller.h b/ash/accessibility/magnifier/partial_magnification_controller.h index a5cf97b5..ca634193 100644 --- a/ash/accessibility/magnifier/partial_magnification_controller.h +++ b/ash/accessibility/magnifier/partial_magnification_controller.h
@@ -9,8 +9,6 @@ #include "ash/ash_export.h" #include "base/macros.h" -#include "base/observer_list.h" -#include "base/observer_list_types.h" #include "ui/events/event_handler.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/size.h" @@ -32,18 +30,9 @@ // which is zoomed in. The zoomed area follows the mouse cursor when enabled. class ASH_EXPORT PartialMagnificationController : public ui::EventHandler { public: - class Observer : public base::CheckedObserver { - public: - // Called when the partial magnification enabled state changes. - virtual void OnPartialMagnificationStateChanged(bool enabled) = 0; - }; - PartialMagnificationController(); ~PartialMagnificationController() override; - void AddObserver(Observer* observer); - void RemoveObserver(Observer* observer); - // Turns the partial screen magnifier feature on or off. Turning the magnifier // on does not imply that it will be displayed; the magnifier is only // displayed when it is both enabled and active. @@ -56,18 +45,11 @@ // - Switch the target window from current window to |new_root_window|. void SwitchTargetRootWindowIfNeeded(aura::Window* new_root_window); - void set_allow_mouse_following(bool enabled) { - allow_mouse_following_ = enabled; - } - - bool is_enabled() const { return is_enabled_; } - private: friend class PartialMagnificationControllerTestApi; // ui::EventHandler: void OnTouchEvent(ui::TouchEvent* event) override; - void OnMouseEvent(ui::MouseEvent* event) override; // Enables or disables the actual magnifier window. void SetActive(bool active); @@ -79,14 +61,8 @@ bool is_enabled_ = false; bool is_active_ = false; - // If enabled, allows the magnifier glass to follow the mouse without the need - // to pressing and holding the mouse. - bool allow_mouse_following_ = false; - std::unique_ptr<MagnifierGlass> magnifier_glass_; - base::ObserverList<Observer> observers_; - DISALLOW_COPY_AND_ASSIGN(PartialMagnificationController); };
diff --git a/ash/accessibility/magnifier/partial_magnification_controller_unittest.cc b/ash/accessibility/magnifier/partial_magnification_controller_unittest.cc index bdc1992..e5bf21e 100644 --- a/ash/accessibility/magnifier/partial_magnification_controller_unittest.cc +++ b/ash/accessibility/magnifier/partial_magnification_controller_unittest.cc
@@ -134,15 +134,6 @@ EXPECT_FALSE(GetTestApi().is_active()); } -// The magnifier activates for mouse events. -TEST_F(PartialMagnificationControllerTest, ActivatesForMouseEvents) { - GetController()->SetEnabled(true); - GetController()->set_allow_mouse_following(true); - ui::test::EventGenerator* event_generator = GetEventGenerator(); - event_generator->MoveMouseBy(1, 1); - EXPECT_TRUE(GetTestApi().is_active()); -} - // The magnifier is always located at pointer. TEST_F(PartialMagnificationControllerTest, MagnifierFollowsPointer) { ui::test::EventGenerator* event_generator = GetEventGenerator();
diff --git a/ash/login/ui/lock_contents_view.cc b/ash/login/ui/lock_contents_view.cc index b8540827..c95a7f2 100644 --- a/ash/login/ui/lock_contents_view.cc +++ b/ash/login/ui/lock_contents_view.cc
@@ -1639,17 +1639,26 @@ primary_big_view_ = main_view_->AddChildView(std::move(primary_big_view)); auto* spacing_middle = main_view_->AddChildView(std::make_unique<NonAccessibleView>()); - users_list_ = main_view_->AddChildView( - BuildScrollableUsersListView(users, LoginDisplayStyle::kSmall)); + users_list_ = + main_view_->AddChildView(std::make_unique<ScrollableUsersListView>( + users, + base::BindRepeating(&LockContentsView::SwapToBigUser, + base::Unretained(this)), + LoginDisplayStyle::kSmall)); auto* spacing_right = main_view_->AddChildView(std::make_unique<NonAccessibleView>()); // Set width for the |spacing_*| views. AddDisplayLayoutAction(base::BindRepeating( [](views::View* host_view, views::View* big_user_view, - views::View* users_list, views::View* spacing_left, + ScrollableUsersListView* users_list, views::View* spacing_left, views::View* spacing_middle, views::View* spacing_right, bool landscape) { + // `users_list` has margins that depend on the current orientation. + // Update these here so that the following calculations see the correct + // bounds. + users_list->UpdateUserViewHostLayoutInsets(); + int total_width = host_view->GetPreferredSize().width(); int available_width = total_width - (big_user_view->GetPreferredSize().width() + @@ -1694,8 +1703,12 @@ fill = main_view_->AddChildView(std::make_unique<NonAccessibleView>()); main_layout->SetFlexForView(fill, 1); - users_list_ = main_view_->AddChildView( - BuildScrollableUsersListView(users, LoginDisplayStyle::kExtraSmall)); + users_list_ = + main_view_->AddChildView(std::make_unique<ScrollableUsersListView>( + users, + base::BindRepeating(&LockContentsView::SwapToBigUser, + base::Unretained(this)), + LoginDisplayStyle::kExtraSmall)); // User list size may change after a display metric change. AddDisplayLayoutAction(base::BindRepeating( @@ -2248,20 +2261,6 @@ return users_list_->GetUserView(user); } -std::unique_ptr<ScrollableUsersListView> -LockContentsView::BuildScrollableUsersListView( - const std::vector<LoginUserInfo>& users, - LoginDisplayStyle display_style) { - auto user_list_view = std::make_unique<ScrollableUsersListView>( - users, - base::BindRepeating(&LockContentsView::SwapToBigUser, - base::Unretained(this)), - display_style); - user_list_view->ClipHeightTo(user_list_view->contents()->size().height(), - size().height()); - return user_list_view; -} - void LockContentsView::SetDisplayStyle(DisplayStyle style) { const bool show_expanded_view = style == DisplayStyle::kExclusivePublicAccountExpandedView;
diff --git a/ash/login/ui/lock_contents_view.h b/ash/login/ui/lock_contents_view.h index 9482ba0..2e03ce77 100644 --- a/ash/login/ui/lock_contents_view.h +++ b/ash/login/ui/lock_contents_view.h
@@ -390,11 +390,6 @@ // Returns the user view for |user|. LoginUserView* TryToFindUserView(const AccountId& user); - // Returns scrollable view with initialized size and rows for all |users|. - std::unique_ptr<ScrollableUsersListView> BuildScrollableUsersListView( - const std::vector<LoginUserInfo>& users, - LoginDisplayStyle display_style); - // Change the visibility of child views based on the |style|. void SetDisplayStyle(DisplayStyle style);
diff --git a/ash/login/ui/lock_contents_view_unittest.cc b/ash/login/ui/lock_contents_view_unittest.cc index d1a4d14d..bca05a1f 100644 --- a/ash/login/ui/lock_contents_view_unittest.cc +++ b/ash/login/ui/lock_contents_view_unittest.cc
@@ -278,9 +278,9 @@ mojom::TrayActionState::kNotAvailable, LockScreen::ScreenType::kLock, DataDispatcher(), std::make_unique<FakeLoginDetachableBaseModel>(DataDispatcher())); + std::unique_ptr<views::Widget> widget = CreateWidgetWithContent(contents); LockContentsView::TestApi lock_contents(contents); SetUserCount(3); - std::unique_ptr<views::Widget> widget = CreateWidgetWithContent(contents); // Returns the distance between the auth user view and the user view. auto calculate_distance = [&]() { @@ -298,11 +298,13 @@ widget->GetNativeWindow()); for (int i = 2; i < 10; ++i) { SetUserCount(i); + SCOPED_TRACE(testing::Message() << "User count: " << i); // Start at 0 degrees (landscape). display_manager()->SetDisplayRotation( display.id(), display::Display::ROTATE_0, display::Display::RotationSource::ACTIVE); + widget->LayoutRootViewIfNecessary(); int distance_0deg = calculate_distance(); EXPECT_NE(distance_0deg, 0); @@ -310,16 +312,18 @@ display_manager()->SetDisplayRotation( display.id(), display::Display::ROTATE_90, display::Display::RotationSource::ACTIVE); + widget->LayoutRootViewIfNecessary(); int distance_90deg = calculate_distance(); - EXPECT_GT(distance_0deg, distance_90deg); + EXPECT_LT(distance_90deg, distance_0deg); // Rotate the display back to 0 degrees (landscape). display_manager()->SetDisplayRotation( display.id(), display::Display::ROTATE_0, display::Display::RotationSource::ACTIVE); - int distance_180deg = calculate_distance(); - EXPECT_EQ(distance_0deg, distance_180deg); - EXPECT_NE(distance_0deg, distance_90deg); + widget->LayoutRootViewIfNecessary(); + int distance_0deg_2 = calculate_distance(); + EXPECT_EQ(distance_0deg_2, distance_0deg); + EXPECT_NE(distance_0deg_2, distance_90deg); } } @@ -329,10 +333,10 @@ mojom::TrayActionState::kNotAvailable, LockScreen::ScreenType::kLock, DataDispatcher(), std::make_unique<FakeLoginDetachableBaseModel>(DataDispatcher())); + std::unique_ptr<views::Widget> widget = CreateWidgetWithContent(contents); SetUserCount(9); ScrollableUsersListView* users_list = LockContentsView::TestApi(contents).users_list(); - std::unique_ptr<views::Widget> widget = CreateWidgetWithContent(contents); // Users list in extra small layout should adjust its height to parent. EXPECT_EQ(contents->height(), users_list->height()); @@ -366,10 +370,10 @@ mojom::TrayActionState::kNotAvailable, LockScreen::ScreenType::kLock, DataDispatcher(), std::make_unique<FakeLoginDetachableBaseModel>(DataDispatcher())); + std::unique_ptr<views::Widget> widget = CreateWidgetWithContent(contents); SetUserCount(4); ScrollableUsersListView* users_list = LockContentsView::TestApi(contents).users_list(); - std::unique_ptr<views::Widget> widget = CreateWidgetWithContent(contents); // Calculate top spacing between users list and lock screen contents. auto top_margin = [&]() { @@ -547,11 +551,11 @@ mojom::TrayActionState::kNotAvailable, LockScreen::ScreenType::kLock, DataDispatcher(), std::make_unique<FakeLoginDetachableBaseModel>(DataDispatcher())); + std::unique_ptr<views::Widget> widget = CreateWidgetWithContent(contents); LockContentsView::TestApi lock_contents(contents); SetUserCount(5); ScrollableUsersListView::TestApi users_list(lock_contents.users_list()); EXPECT_EQ(users().size() - 1, users_list.user_views().size()); - std::unique_ptr<views::Widget> widget = CreateWidgetWithContent(contents); LoginBigUserView* auth_view = lock_contents.primary_big_view(); @@ -1896,9 +1900,9 @@ mojom::TrayActionState::kNotAvailable, LockScreen::ScreenType::kLock, DataDispatcher(), std::make_unique<FakeLoginDetachableBaseModel>(DataDispatcher())); + std::unique_ptr<views::Widget> widget = CreateWidgetWithContent(contents); LockContentsView::TestApi contents_test_api(contents); AddUsers(3); - std::unique_ptr<views::Widget> widget = CreateWidgetWithContent(contents); LoginPasswordView* password_view = LoginAuthUserView::TestApi( @@ -1922,8 +1926,8 @@ auto* contents = new LockContentsView( mojom::TrayActionState::kNotAvailable, LockScreen::ScreenType::kLock, DataDispatcher(), std::move(fake_detachable_base_model)); - SetUserCount(3); std::unique_ptr<views::Widget> widget = CreateWidgetWithContent(contents); + SetUserCount(3); LockContentsView::TestApi test_api(contents); LoginBigUserView* primary_view = test_api.primary_big_view(); @@ -2672,8 +2676,8 @@ mojom::TrayActionState::kNotAvailable, LockScreen::ScreenType::kLogin, DataDispatcher(), std::make_unique<FakeLoginDetachableBaseModel>(DataDispatcher())); - SetUserCount(3); SetWidget(CreateWidgetWithContent(contents)); + SetUserCount(3); LockContentsView::TestApi lock_contents(contents); ScrollableUsersListView::TestApi users_list(lock_contents.users_list());
diff --git a/ash/login/ui/scrollable_users_list_view.cc b/ash/login/ui/scrollable_users_list_view.cc index 62a49748..0562f5a 100644 --- a/ash/login/ui/scrollable_users_list_view.cc +++ b/ash/login/ui/scrollable_users_list_view.cc
@@ -353,6 +353,16 @@ return nullptr; } +void ScrollableUsersListView::UpdateUserViewHostLayoutInsets() { + DCHECK(GetWidget()); + bool should_show_landscape = + login_views_utils::ShouldShowLandscape(GetWidget()); + LayoutParams layout_params = BuildLayoutForStyle(display_style_); + user_view_host_layout_->set_inside_border_insets( + should_show_landscape ? layout_params.insets_landscape + : layout_params.insets_portrait); +} + void ScrollableUsersListView::Layout() { DCHECK(user_view_host_layout_); @@ -364,13 +374,7 @@ PreferredSizeChanged(); } - // Update the user view layout. - bool should_show_landscape = - login_views_utils::ShouldShowLandscape(GetWidget()); - LayoutParams layout_params = BuildLayoutForStyle(display_style_); - user_view_host_layout_->set_inside_border_insets( - should_show_landscape ? layout_params.insets_landscape - : layout_params.insets_portrait); + UpdateUserViewHostLayoutInsets(); // Layout everything. ScrollView::Layout();
diff --git a/ash/login/ui/scrollable_users_list_view.h b/ash/login/ui/scrollable_users_list_view.h index a5e7ee9..11034f2 100644 --- a/ash/login/ui/scrollable_users_list_view.h +++ b/ash/login/ui/scrollable_users_list_view.h
@@ -63,6 +63,10 @@ // Returns user view with |account_id| if it exists or nullptr otherwise. LoginUserView* GetUserView(const AccountId& account_id); + // Updates the insets for the `user_view_host_layout_` based on whether the + // view is in landscape or portrait mode. + void UpdateUserViewHostLayoutInsets(); + // views::View: void Layout() override; void OnPaintBackground(gfx::Canvas* canvas) override;
diff --git a/ash/projector/projector_controller_impl.cc b/ash/projector/projector_controller_impl.cc index 861f87f..c6d708cf 100644 --- a/ash/projector/projector_controller_impl.cc +++ b/ash/projector/projector_controller_impl.cc
@@ -134,10 +134,6 @@ ui_controller_->OnSelfieCamPressed(enabled); } -void ProjectorControllerImpl::OnMagnifierButtonPressed(bool enabled) { - ui_controller_->OnMagnifierButtonPressed(enabled); -} - void ProjectorControllerImpl::SetProjectorUiControllerForTest( std::unique_ptr<ProjectorUiController> ui_controller) { ui_controller_ = std::move(ui_controller);
diff --git a/ash/projector/projector_controller_impl.h b/ash/projector/projector_controller_impl.h index ddc50bce..caf82af 100644 --- a/ash/projector/projector_controller_impl.h +++ b/ash/projector/projector_controller_impl.h
@@ -73,8 +73,6 @@ void OnClearAllMarkersPressed(); // Invoked when selfie cam button is pressed. void OnSelfieCamPressed(bool enabled); - // Invoked when magnifier button is pressed. - void OnMagnifierButtonPressed(bool enabled); void SetProjectorUiControllerForTest( std::unique_ptr<ProjectorUiController> ui_controller);
diff --git a/ash/projector/projector_controller_unittest.cc b/ash/projector/projector_controller_unittest.cc index e6b0ab5..9eb11b5 100644 --- a/ash/projector/projector_controller_unittest.cc +++ b/ash/projector/projector_controller_unittest.cc
@@ -211,9 +211,4 @@ controller_->SetCaptionBubbleState(true); } -TEST_F(ProjectorControllerTest, MagnifierButtonPressed) { - EXPECT_CALL(*mock_ui_controller_, OnMagnifierButtonPressed(true)); - controller_->OnMagnifierButtonPressed(true); -} - } // namespace ash
diff --git a/ash/projector/projector_ui_controller.cc b/ash/projector/projector_ui_controller.cc index 5f349a5c..8df51a8a 100644 --- a/ash/projector/projector_ui_controller.cc +++ b/ash/projector/projector_ui_controller.cc
@@ -4,7 +4,6 @@ #include "ash/projector/projector_ui_controller.h" -#include "ash/accessibility/magnifier/partial_magnification_controller.h" #include "ash/projector/projector_controller_impl.h" #include "ash/projector/ui/projector_bar_view.h" #include "ash/public/cpp/toast_data.h" @@ -57,13 +56,6 @@ MarkerController::Get()->SetEnabled(enabled); } -void EnableMagnifier(bool enabled) { - auto* magnifier_controller = Shell::Get()->partial_magnification_controller(); - DCHECK(magnifier_controller); - magnifier_controller->SetEnabled(enabled); - magnifier_controller->set_allow_mouse_following(enabled); -} - } // namespace // This class controls the interaction with the caption bubble. It keeps track @@ -145,11 +137,6 @@ DCHECK(marker_controller); marker_controller_observation_.Observe(marker_controller); - auto* partial_magnification_controller = - Shell::Get()->partial_magnification_controller(); - DCHECK(partial_magnification_controller); - partial_magnification_observation_.Observe(partial_magnification_controller); - caption_bubble_ = std::make_unique<ProjectorUiController::CaptionBubbleController>(this); @@ -242,10 +229,6 @@ caption_bubble_->Close(); } -void ProjectorUiController::OnMagnifierButtonPressed(bool enabled) { - EnableMagnifier(enabled); -} - bool ProjectorUiController::IsToolbarVisible() const { return model_.bar_enabled(); } @@ -260,27 +243,21 @@ EnableLaserPointer(false); // Reset marker. EnableMarker(false); - // Reset magnifier. - EnableMagnifier(false); } void ProjectorUiController::OnLaserPointerStateChanged(bool enabled) { - // If laser pointer is enabled, disable marker and magnifier. - if (enabled) { - EnableMarker(false); - EnableMagnifier(false); - } + // Disable marker if laser pointer is enabled; + if (enabled) + MarkerController::Get()->SetEnabled(false); if (projector_bar_view_) projector_bar_view_->OnLaserPointerStateChanged(enabled); } void ProjectorUiController::OnMarkerStateChanged(bool enabled) { - // If marker is enabled, disable laser pointer and magnifier. - if (enabled) { - EnableLaserPointer(false); - EnableMagnifier(false); - } + // Disable laser pointer since marker if enabled; + if (enabled) + Shell::Get()->laser_pointer_controller()->SetEnabled(false); if (projector_bar_view_) projector_bar_view_->OnMarkerStateChanged(enabled); @@ -291,15 +268,4 @@ MarkerController::Get()->Clear(); } -void ProjectorUiController::OnPartialMagnificationStateChanged(bool enabled) { - // If magnifier is enabled, disable laser pointer and marker. - if (enabled) { - EnableMarker(false); - EnableLaserPointer(false); - } - - if (projector_bar_view_) - projector_bar_view_->OnMagnifierStateChanged(enabled); -} - } // namespace ash
diff --git a/ash/projector/projector_ui_controller.h b/ash/projector/projector_ui_controller.h index d1ae621..6cd6a652e 100644 --- a/ash/projector/projector_ui_controller.h +++ b/ash/projector/projector_ui_controller.h
@@ -9,7 +9,6 @@ #include <string> #include <vector> -#include "ash/accessibility/magnifier/partial_magnification_controller.h" #include "ash/ash_export.h" #include "ash/fast_ink/laser/laser_pointer_controller.h" #include "ash/marker/marker_controller.h" @@ -24,11 +23,9 @@ class ProjectorBarView; // The controller in charge of UI. -class ASH_EXPORT ProjectorUiController - : public LaserPointerObserver, - public MarkerObserver, - public ProjectorSessionObserver, - public PartialMagnificationController::Observer { +class ASH_EXPORT ProjectorUiController : public LaserPointerObserver, + public MarkerObserver, + public ProjectorSessionObserver { public: explicit ProjectorUiController(ProjectorControllerImpl* projector_controller); ProjectorUiController(const ProjectorUiController&) = delete; @@ -53,14 +50,11 @@ virtual void OnTranscription(const std::string& transcription, bool is_final); // Invoked when the selfie cam button is pressed. Virtual for testing. virtual void OnSelfieCamPressed(bool enabled); - // Invoked when the recording started or stopped. Virtual for testing. + // Called when the recording started or stopped. Virtual for testing. virtual void OnRecordingStateChanged(bool started); // Notifies the ProjectorControllerImpl and ProjectorBarView when the caption // bubble model's state changes. void OnCaptionBubbleModelStateChanged(bool visible); - // Invoked when magnification is set to be enabled or not. Virtual for - // testing. - virtual void OnMagnifierButtonPressed(bool enabled); bool IsToolbarVisible() const; @@ -86,9 +80,6 @@ // ProjectorSessionObserver: void OnProjectorSessionActiveStateChanged(bool active) override; - // PartialMagnificationController::OnPartialMagnificationStateChanged: - void OnPartialMagnificationStateChanged(bool enabled) override; - ProjectorUiModel model_; views::UniqueWidgetPtr projector_bar_widget_; ProjectorBarView* projector_bar_view_ = nullptr; @@ -105,10 +96,6 @@ base::ScopedObservation<ProjectorSession, ProjectorSessionObserver> projector_session_observation_{this}; - - base::ScopedObservation<PartialMagnificationController, - PartialMagnificationController::Observer> - partial_magnification_observation_{this}; }; } // namespace ash
diff --git a/ash/projector/projector_ui_controller_unittest.cc b/ash/projector/projector_ui_controller_unittest.cc index c857625e..e73056d 100644 --- a/ash/projector/projector_ui_controller_unittest.cc +++ b/ash/projector/projector_ui_controller_unittest.cc
@@ -74,16 +74,6 @@ controller_->OnLaserPointerPressed(); EXPECT_FALSE(marker_controller_->is_enabled()); EXPECT_TRUE(laser_pointer_controller_->is_enabled()); - - // Verify that toggling laser pointer disables magnifier when it was enabled. - auto* magnification_controller = - Shell::Get()->partial_magnification_controller(); - controller_->OnMagnifierButtonPressed(true); - EXPECT_TRUE(magnification_controller->is_enabled()); - EXPECT_FALSE(laser_pointer_controller_->is_enabled()); - controller_->OnLaserPointerPressed(); - EXPECT_TRUE(laser_pointer_controller_->is_enabled()); - EXPECT_FALSE(magnification_controller->is_enabled()); } // Verifies that toggling on the marker on Projector tools propagates to @@ -126,15 +116,6 @@ laser_pointer_controller_->SetEnabled(false); EXPECT_FALSE(marker_controller_->is_enabled()); EXPECT_FALSE(laser_pointer_controller_->is_enabled()); - - // Verify that toggling marker disables magnifier when it was enabled. - auto* magnification_controller = - Shell::Get()->partial_magnification_controller(); - controller_->OnMagnifierButtonPressed(true); - EXPECT_TRUE(magnification_controller->is_enabled()); - controller_->OnMarkerPressed(); - EXPECT_TRUE(marker_controller_->is_enabled()); - EXPECT_FALSE(magnification_controller->is_enabled()); } // Verifies that clicking the Clear All Markers button and disabling marker mode @@ -203,21 +184,4 @@ EXPECT_FALSE(controller_->IsCaptionBubbleModelOpen()); } -TEST_F(ProjectorUiControllerTest, EnablingDisablingMagnifierGlass) { - // Ensure that enabling magnifier disables marker if it was enabled. - controller_->ShowToolbar(); - auto* marker_controller_ = MarkerController::Get(); - marker_controller_->SetEnabled(true); - EXPECT_TRUE(marker_controller_->is_enabled()); - controller_->OnMagnifierButtonPressed(true); - EXPECT_FALSE(marker_controller_->is_enabled()); - - // Ensures that enabling magnifier disables laser pointer if it was enabled. - auto* laser_pointer_controller_ = Shell::Get()->laser_pointer_controller(); - laser_pointer_controller_->SetEnabled(true); - EXPECT_TRUE(laser_pointer_controller_->is_enabled()); - controller_->OnMagnifierButtonPressed(true); - EXPECT_FALSE(laser_pointer_controller_->is_enabled()); -} - } // namespace ash
diff --git a/ash/projector/test/mock_projector_ui_controller.h b/ash/projector/test/mock_projector_ui_controller.h index 5fc58d7..0bcab62 100644 --- a/ash/projector/test/mock_projector_ui_controller.h +++ b/ash/projector/test/mock_projector_ui_controller.h
@@ -35,7 +35,6 @@ MOCK_METHOD1(OnSelfieCamPressed, void(bool enabled)); MOCK_METHOD1(OnRecordingStateChanged, void(bool started)); MOCK_METHOD1(SetCaptionBubbleState, void(bool)); - MOCK_METHOD1(OnMagnifierButtonPressed, void(bool)); }; } // namespace ash
diff --git a/ash/projector/ui/projector_bar_view.cc b/ash/projector/ui/projector_bar_view.cc index 768ab79..a3b45b5b 100644 --- a/ash/projector/ui/projector_bar_view.cc +++ b/ash/projector/ui/projector_bar_view.cc
@@ -131,11 +131,6 @@ projector_controller_->OnClearAllMarkersPressed(); } -void ProjectorBarView::OnMagnifierStateChanged(bool enabled) { - magnifier_start_button_->SetVisible(!enabled); - magnifier_stop_button_->SetVisible(enabled); -} - void ProjectorBarView::OnThemeChanged() { views::View::OnThemeChanged(); } @@ -291,7 +286,7 @@ magnifier_start_button_ = box_layout->AddChildView(std::make_unique<ProjectorImageButton>( base::BindRepeating(&ProjectorBarView::OnMagnifierButtonPressed, - base::Unretained(this), /* enabled =*/true), + base::Unretained(this), /* enabled =*/false), kZoomInIcon)); magnifier_start_button_->SetVisible(true); magnifier_stop_button_ = @@ -379,7 +374,7 @@ } void ProjectorBarView::OnMagnifierButtonPressed(bool enabled) { - projector_controller_->OnMagnifierButtonPressed(enabled); + // TODO(crbug/1203444) Implement the magnifier button functionality. } void ProjectorBarView::OnChangeBarLocationButtonPressed() {
diff --git a/ash/projector/ui/projector_bar_view.h b/ash/projector/ui/projector_bar_view.h index 3f902e2..01fc84c 100644 --- a/ash/projector/ui/projector_bar_view.h +++ b/ash/projector/ui/projector_bar_view.h
@@ -44,8 +44,6 @@ void OnLaserPointerStateChanged(bool enabled); // Invoke when marker activation state changed. void OnMarkerStateChanged(bool enabled); - // Invoked when the magnifier state changed. - void OnMagnifierStateChanged(bool enabled); // views::View: void OnThemeChanged() override;
diff --git a/base/allocator/allocator_shim_default_dispatch_to_partition_alloc.cc b/base/allocator/allocator_shim_default_dispatch_to_partition_alloc.cc index a2e0520e..8b378b0c 100644 --- a/base/allocator/allocator_shim_default_dispatch_to_partition_alloc.cc +++ b/base/allocator/allocator_shim_default_dispatch_to_partition_alloc.cc
@@ -3,6 +3,8 @@ // found in the LICENSE file. #include "base/allocator/allocator_shim_default_dispatch_to_partition_alloc.h" + +#include <atomic> #include <cstddef> #include "base/allocator/allocator_shim_internals.h" @@ -29,59 +31,61 @@ namespace { -// We would usually make g_root a static local variable, as these are guaranteed -// to be thread-safe in C++11. However this does not work on Windows, as the -// initialization calls into the runtime, which is not prepared to handle it. +std::atomic<bool> g_initialization_lock{false}; + +// We can't use a "static local" or a base::LazyInstance, as: +// - static local variables call into the runtime on Windows, which is not +// prepared to handle it, as the first allocation happens during CRT init. +// - We don't want to depend on base::LazyInstance, which may be converted to +// static locals one day. // -// To sidestep that, we implement our own equivalent to a local `static -// base::NoDestructor<base::ThreadSafePartitionRoot> root`. -// -// The ingredients are: -// - Placement new to avoid a static constructor, and a static destructor. -// - Double-checked locking to get the same guarantees as a static local -// variable. +// Nevertheless, this provides essentially the same thing. +template <typename T, typename Constructor> +class LeakySingleton { + public: + constexpr LeakySingleton() = default; -// Lock for double-checked locking. -std::atomic<bool> g_initialization_lock; -std::atomic<base::ThreadSafePartitionRoot*> g_root_; -// Buffer for placement new. -alignas(base::ThreadSafePartitionRoot) uint8_t - g_allocator_buffer[sizeof(base::ThreadSafePartitionRoot)]; + ALWAYS_INLINE T* Get() { + auto* instance = instance_.load(std::memory_order_acquire); + if (LIKELY(instance)) + return instance; -// Original g_root_ if it was replaced by ConfigurePartitionRefCountSupport(). -std::atomic<base::ThreadSafePartitionRoot*> g_original_root_(nullptr); + return GetSlowPath(); + } -base::ThreadSafePartitionRoot* Allocator() { - // Double-checked locking. + // Replaces the instance pointer with a new one. + void Replace(T* new_instance) { + instance_.store(new_instance, std::memory_order_release); + } + + private: + T* GetSlowPath(); + + std::atomic<T*> instance_; + alignas(T) uint8_t instance_buffer_[sizeof(T)]; +}; + +template <typename T, typename Constructor> +T* LeakySingleton<T, Constructor>::GetSlowPath() { + // The instance has not been set, the proper way to proceed (correct + // double-checked locking) is: // - // The proper way to proceed is: - // - // auto* root = load_acquire(g_root); - // if (!root) { + // auto* instance = instance_.load(std::memory_order_acquire); + // if (!instance) { // ScopedLock initialization_lock; - // root = load_relaxed(g_root); + // root = instance_.load(std::memory_order_relaxed); // if (root) // return root; - // new_root = Create new root. - // release_store(g_root, new_root); + // instance = Create new root; + // instance_.store(instance, std::memory_order_release); + // return instance; // } // - // We don't want to use a base::Lock here, so instead we use the - // compare-and-exchange on a lock variable, but this provides the same - // guarantees as a regular lock. The code could be made simpler as we have - // stricter requirements, but we stick to something close to a regular lock - // for ease of reading, as none of this is performance-critical anyway. + // However, we don't want to use a base::Lock here, so instead we use + // compare-and-exchange on a lock variable, which provides the same + // guarantees. // - // If we boldly assume that initialization will always be single-threaded, - // then we could remove all these atomic operations, but this seems a bit too - // bold to try yet. Might be worth revisiting though, since this would remove - // a memory barrier at each load. We could probably guarantee single-threaded - // init by adding a static constructor which allocates (and hence triggers - // initialization before any other thread is created). - auto* root = g_root_.load(std::memory_order_acquire); - if (LIKELY(root)) - return root; - + // Lock. bool expected = false; // Semantically equivalent to base::Lock::Acquire(). while (!g_initialization_lock.compare_exchange_strong( @@ -89,60 +93,107 @@ expected = false; } - root = g_root_.load(std::memory_order_relaxed); + T* instance = instance_.load(std::memory_order_relaxed); // Someone beat us. - if (root) { - // Semantically equivalent to base::Lock::Release(). + if (instance) { + // Unlock. g_initialization_lock.store(false, std::memory_order_release); - return root; + return instance; } - auto* new_root = new (g_allocator_buffer) base::ThreadSafePartitionRoot({ + instance = Constructor::New(reinterpret_cast<void*>(instance_buffer_)); + instance_.store(instance, std::memory_order_release); + + // Unlock. + g_initialization_lock.store(false, std::memory_order_release); + + return instance; +} + +class MainPartitionConstructor { + public: + static base::ThreadSafePartitionRoot* New(void* buffer) { + auto* new_root = new (buffer) base::ThreadSafePartitionRoot({ #if BUILDFLAG(USE_DEDICATED_PARTITION_FOR_ALIGNED_ALLOC) - base::PartitionOptions::AlignedAlloc::kDisallowed, + base::PartitionOptions::AlignedAlloc::kDisallowed, #else - base::PartitionOptions::AlignedAlloc::kAllowed, + base::PartitionOptions::AlignedAlloc::kAllowed, #endif #if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && \ !BUILDFLAG(ENABLE_RUNTIME_BACKUP_REF_PTR_CONTROL) - base::PartitionOptions::ThreadCache::kEnabled, + base::PartitionOptions::ThreadCache::kEnabled, #elif BUILDFLAG(ENABLE_RUNTIME_BACKUP_REF_PTR_CONTROL) - // With ENABLE_RUNTIME_BACKUP_REF_PTR_CONTROL, if GigaCage is enabled, - // this partition is only temporary until BackupRefPtr is re-configured - // at run-time. Leave the ability to have a thread cache to the main - // partition. (Note that ENABLE_RUNTIME_BACKUP_REF_PTR_CONTROL implies - // that USE_BACKUP_REF_PTR is true.) - // - // Note that it is ok to use RefCount::kEnabled below regardless of the - // GigaCage check, because the constructor will disable ref-count if - // GigaCage is disabled. - base::features::IsPartitionAllocGigaCageEnabled() - ? base::PartitionOptions::ThreadCache::kDisabled - : base::PartitionOptions::ThreadCache::kEnabled, + // With ENABLE_RUNTIME_BACKUP_REF_PTR_CONTROL, if GigaCage is enabled, + // this partition is only temporary until BackupRefPtr is + // re-configured at run-time. Leave the ability to have a thread cache + // to the main partition. (Note that + // ENABLE_RUNTIME_BACKUP_REF_PTR_CONTROL implies that + // USE_BACKUP_REF_PTR is true.) + // + // Note that it is ok to use RefCount::kEnabled below regardless of + // the GigaCage check, because the constructor will disable ref-count + // if GigaCage is disabled. + base::features::IsPartitionAllocGigaCageEnabled() + ? base::PartitionOptions::ThreadCache::kDisabled + : base::PartitionOptions::ThreadCache::kEnabled, #else - // Other tests, such as the ThreadCache tests create a thread cache, and - // only one is supported at a time. - base::PartitionOptions::ThreadCache::kDisabled, + // Other tests, such as the ThreadCache tests create a thread cache, and + // only one is supported at a time. + base::PartitionOptions::ThreadCache::kDisabled, #endif // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && // !BUILDFLAG(ENABLE_RUNTIME_BACKUP_REF_PTR_CONTROL) - base::PartitionOptions::Quarantine::kAllowed, + base::PartitionOptions::Quarantine::kAllowed, #if BUILDFLAG(USE_DEDICATED_PARTITION_FOR_ALIGNED_ALLOC) - base::PartitionOptions::Cookies::kAllowed, + base::PartitionOptions::Cookies::kAllowed, #else - base::PartitionOptions::Cookies::kDisallowed, + base::PartitionOptions::Cookies::kDisallowed, #endif #if BUILDFLAG(USE_DEDICATED_PARTITION_FOR_ALIGNED_ALLOC) || \ BUILDFLAG(PUT_REF_COUNT_IN_PREVIOUS_SLOT) - base::PartitionOptions::RefCount::kAllowed, + base::PartitionOptions::RefCount::kAllowed, #else - base::PartitionOptions::RefCount::kDisallowed, + base::PartitionOptions::RefCount::kDisallowed, #endif - }); - g_root_.store(new_root, std::memory_order_release); + }); - // Semantically equivalent to base::Lock::Release(). - g_initialization_lock.store(false, std::memory_order_release); - return new_root; + return new_root; + } +}; + +#if BUILDFLAG(USE_DEDICATED_PARTITION_FOR_ALIGNED_ALLOC) +class AlignedPartitionConstructor { + public: + static base::ThreadSafePartitionRoot* New(void* buffer) { + // Since the general-purpose allocator uses the thread cache, this one + // cannot. + auto* new_root = + new (buffer) base::ThreadSafePartitionRoot(base::PartitionOptions { + base::PartitionOptions::AlignedAlloc::kAllowed, + base::PartitionOptions::ThreadCache::kDisabled, + base::PartitionOptions::Quarantine::kAllowed, + base::PartitionOptions::Cookies::kDisallowed, +#if BUILDFLAG(PUT_REF_COUNT_IN_PREVIOUS_SLOT) + // Given the outer #if, this is possible only when DCHECK_IS_ON(). + base::PartitionOptions::RefCount::kAllowed, +#else + base::PartitionOptions::RefCount::kDisallowed, +#endif + }); + return new_root; + } +}; + +LeakySingleton<base::ThreadSafePartitionRoot, AlignedPartitionConstructor> + g_aligned_root = {}; +#endif // BUILDFLAG(USE_DEDICATED_PARTITION_FOR_ALIGNED_ALLOC) + +// Original g_root_ if it was replaced by ConfigurePartitionRefCountSupport(). +std::atomic<base::ThreadSafePartitionRoot*> g_original_root_(nullptr); + +LeakySingleton<base::ThreadSafePartitionRoot, MainPartitionConstructor> g_root = + {}; +base::ThreadSafePartitionRoot* Allocator() { + return g_root.Get(); } base::ThreadSafePartitionRoot* OriginalAllocator() { @@ -151,21 +202,7 @@ base::ThreadSafePartitionRoot* AlignedAllocator() { #if BUILDFLAG(USE_DEDICATED_PARTITION_FOR_ALIGNED_ALLOC) - // Since the general-purpose allocator uses the thread cache, this one cannot. - static base::NoDestructor<base::ThreadSafePartitionRoot> aligned_allocator( - base::PartitionOptions { - base::PartitionOptions::AlignedAlloc::kAllowed, - base::PartitionOptions::ThreadCache::kDisabled, - base::PartitionOptions::Quarantine::kAllowed, - base::PartitionOptions::Cookies::kDisallowed, -#if BUILDFLAG(PUT_REF_COUNT_IN_PREVIOUS_SLOT) - // Given the outer #if, this is possible only when DCHECK_IS_ON(). - base::PartitionOptions::RefCount::kAllowed, -#else - base::PartitionOptions::RefCount::kDisallowed, -#endif - }); - return aligned_allocator.get(); + return g_aligned_root.Get(); #else // BUILDFLAG(USE_DEDICATED_PARTITION_FOR_ALIGNED_ALLOC) return Allocator(); #endif // BUILDFLAG(USE_DEDICATED_PARTITION_FOR_ALIGNED_ALLOC) @@ -424,10 +461,7 @@ if (!base::features::IsPartitionAllocGigaCageEnabled()) return; - auto* current_root = g_root_.load(std::memory_order_acquire); - // We expect a number of heap allocations to be made before this function is - // called, which should force the `g_root` initialization. - PA_CHECK(current_root); + auto* current_root = g_root.Get(); current_root->PurgeMemory(PartitionPurgeDecommitEmptySlotSpans | PartitionPurgeDiscardUnusedSystemPages); @@ -448,7 +482,7 @@ enable_ref_count ? base::PartitionOptions::RefCount::kAllowed : base::PartitionOptions::RefCount::kDisallowed, }); - g_root_.store(new_root, std::memory_order_release); + g_root.Replace(new_root); g_original_root_ = current_root; } #endif // BUILDFLAG(ENABLE_RUNTIME_BACKUP_REF_PTR_CONTROL)
diff --git a/base/allocator/partition_allocator/address_pool_manager.cc b/base/allocator/partition_allocator/address_pool_manager.cc index 61852bf0..409071a 100644 --- a/base/allocator/partition_allocator/address_pool_manager.cc +++ b/base/allocator/partition_allocator/address_pool_manager.cc
@@ -51,6 +51,7 @@ MAP_FIXED | MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); PA_CHECK(ptr == address); #else + static_assert(DecommittedMemoryIsAlwaysZeroed(), ""); DecommitSystemPages(address, size, PageUpdatePermissions); #endif }
diff --git a/base/allocator/partition_allocator/page_allocator.h b/base/allocator/partition_allocator/page_allocator.h index 30d4c44..68ed0f3 100644 --- a/base/allocator/partition_allocator/page_allocator.h +++ b/base/allocator/partition_allocator/page_allocator.h
@@ -12,6 +12,7 @@ #include "base/allocator/partition_allocator/page_allocator_constants.h" #include "base/base_export.h" #include "base/compiler_specific.h" +#include "build/build_config.h" namespace base { @@ -121,8 +122,9 @@ // virtual address range may be released back to the system, but the address // space is still allocated to the process (possibly using up page table entries // or other accounting resources). There is no guarantee that the pages are -// zeroed. Unless PageKeepPermissionsIfPossible disposition is used, any access -// to a decommitted region of memory is an error and will generate a fault. +// zeroed, see |DecommittedMemoryIsAlwaysZeroed()| for such a guarantee. Unless +// PageKeepPermissionsIfPossible disposition is used, any access to a +// decommitted region of memory is an error and will generate a fault. // // This operation is not atomic on all platforms. // @@ -141,6 +143,16 @@ size_t length, PageAccessibilityDisposition accessibility_disposition); +// Whether decommitted memory is guaranteed to be zeroed when it is +// recommitted. Do not assume that this will not change over time. +constexpr BASE_EXPORT bool DecommittedMemoryIsAlwaysZeroed() { +#if defined(OS_APPLE) + return false; +#else + return true; +#endif +} + // Recommit one or more system pages, starting at |address| and continuing for // |length| bytes with the given |page_accessibility| (must not be // PageInaccsessible). |address| and |length| must be aligned to a system page
diff --git a/base/allocator/partition_allocator/page_allocator_constants.h b/base/allocator/partition_allocator/page_allocator_constants.h index beabba9..f5e1057a 100644 --- a/base/allocator/partition_allocator/page_allocator_constants.h +++ b/base/allocator/partition_allocator/page_allocator_constants.h
@@ -112,15 +112,6 @@ static constexpr size_t kPageMetadataShift = 5; // 32 bytes per partition page. static constexpr size_t kPageMetadataSize = 1 << kPageMetadataShift; -// See DecommitSystemPages(), this is not guaranteed to be synchronous on all -// platforms. -static constexpr bool kDecommittedPagesAreAlwaysZeroed = -#if defined(OS_APPLE) - false; -#else - true; -#endif - } // namespace base #endif // BASE_ALLOCATOR_PARTITION_ALLOCATOR_PAGE_ALLOCATOR_CONSTANTS_H_
diff --git a/base/allocator/partition_allocator/page_allocator_internals_posix.h b/base/allocator/partition_allocator/page_allocator_internals_posix.h index f13cf58..eda62f57 100644 --- a/base/allocator/partition_allocator/page_allocator_internals_posix.h +++ b/base/allocator/partition_allocator/page_allocator_internals_posix.h
@@ -6,10 +6,13 @@ #define BASE_ALLOCATOR_PARTITION_ALLOCATOR_PAGE_ALLOCATOR_INTERNALS_POSIX_H_ #include <errno.h> +#include <string.h> #include <sys/mman.h> +#include <algorithm> #include "base/allocator/partition_allocator/oom.h" #include "base/allocator/partition_allocator/partition_alloc_check.h" +#include "base/dcheck_is_on.h" #include "base/posix/eintr_wrapper.h" #include "build/build_config.h" @@ -27,8 +30,6 @@ #endif #if defined(OS_LINUX) || defined(OS_CHROMEOS) #include <sys/resource.h> - -#include <algorithm> #endif #include "base/allocator/partition_allocator/page_allocator.h" @@ -253,13 +254,32 @@ // pages in the region. DiscardSystemPages(address, length); + bool change_permissions = accessibility_disposition == PageUpdatePermissions; +#if DCHECK_IS_ON() + // This is not guaranteed, show that we're serious. + // + // More specifically, several callers have had issues with assuming that + // memory is zeroed, this would hopefully make these bugs more visible. We + // don't memset() everything, because ranges can be very large, and doing it + // over the entire range could make Chrome unusable with DCHECK_IS_ON(). + // + // Only do it when we are about to change the permissions, since we don't know + // the previous permissions, and cannot restore them. + if (!DecommittedMemoryIsAlwaysZeroed() && change_permissions) { + // Memory may not be writable. + size_t size = std::min(length, 2 * SystemPageSize()); + PA_CHECK(mprotect(address, size, PROT_WRITE) == 0); + memset(address, 0xcc, size); + } +#endif + // Make pages inaccessible, unless the caller requested to keep permissions. // // Note, there is a small window between these calls when the pages can be // incorrectly touched and brought back to memory. Not ideal, but doing those - // operaions in the opposite order resulted in PMF regression on Mac (see + // operations in the opposite order resulted in PMF regression on Mac (see // crbug.com/1153021). - if (accessibility_disposition == PageUpdatePermissions) { + if (change_permissions) { SetSystemPagesAccess(address, length, PageInaccessible); } }
diff --git a/base/allocator/partition_allocator/page_allocator_unittest.cc b/base/allocator/partition_allocator/page_allocator_unittest.cc index 86ee08c2..a5d64ca 100644 --- a/base/allocator/partition_allocator/page_allocator_unittest.cc +++ b/base/allocator/partition_allocator/page_allocator_unittest.cc
@@ -422,7 +422,7 @@ #endif // defined(OS_ANDROID) TEST(PageAllocatorTest, DecommitErasesMemory) { - if (!kDecommittedPagesAreAlwaysZeroed) + if (!DecommittedMemoryIsAlwaysZeroed()) return; size_t size = PageAllocationGranularity();
diff --git a/base/allocator/partition_allocator/partition_bucket.cc b/base/allocator/partition_allocator/partition_bucket.cc index d796c0e3..06bd955e 100644 --- a/base/allocator/partition_allocator/partition_bucket.cc +++ b/base/allocator/partition_allocator/partition_bucket.cc
@@ -737,7 +737,7 @@ } new_slot_span->Reset(); - *is_already_zeroed = kDecommittedPagesAreAlwaysZeroed; + *is_already_zeroed = DecommittedMemoryIsAlwaysZeroed(); } PA_DCHECK(new_slot_span); } else {
diff --git a/base/i18n/break_iterator_unittest.cc b/base/i18n/break_iterator_unittest.cc index f91ea69b..a2364512 100644 --- a/base/i18n/break_iterator_unittest.cc +++ b/base/i18n/break_iterator_unittest.cc
@@ -95,7 +95,10 @@ } TEST(BreakIteratorTest, BreakWordWide32) { - const std::u16string str = u"\U0001d49c a"; + // U+1D49C MATHEMATICAL SCRIPT CAPITAL A + const char very_wide_char[] = "\xF0\x9D\x92\x9C"; + const std::u16string str( + UTF8ToUTF16(base::StringPrintf("%s a", very_wide_char))); const std::u16string very_wide_word(str.substr(0, 2)); BreakIterator iter(str, BreakIterator::BREAK_WORD); @@ -117,22 +120,23 @@ TEST(BreakIteratorTest, BreakWordThai) { // Terms in Thai, without spaces in between. - const char16_t term1[] = u"พิมพ์"; - const char16_t term2[] = u"น้อย"; - const char16_t term3[] = u"ลง"; - const std::u16string str(base::JoinString({term1, term2, term3}, u"")); + const char term1[] = "พิมพ์"; + const char term2[] = "น้อย"; + const char term3[] = "ลง"; + const std::u16string str( + UTF8ToUTF16(base::JoinString({term1, term2, term3}, ""))); BreakIterator iter(str, BreakIterator::BREAK_WORD); ASSERT_TRUE(iter.Init()); EXPECT_TRUE(iter.Advance()); EXPECT_TRUE(iter.IsWord()); - EXPECT_EQ(term1, iter.GetString()); + EXPECT_EQ(UTF8ToUTF16(term1), iter.GetString()); EXPECT_TRUE(iter.Advance()); EXPECT_TRUE(iter.IsWord()); - EXPECT_EQ(term2, iter.GetString()); + EXPECT_EQ(UTF8ToUTF16(term2), iter.GetString()); EXPECT_TRUE(iter.Advance()); EXPECT_TRUE(iter.IsWord()); - EXPECT_EQ(term3, iter.GetString()); + EXPECT_EQ(UTF8ToUTF16(term3), iter.GetString()); EXPECT_FALSE(iter.Advance()); EXPECT_FALSE(iter.IsWord()); } @@ -145,40 +149,41 @@ TEST(BreakIteratorTest, BreakWordChinese) { // Terms in Traditional Chinese, without spaces in between. - const char16_t term1[] = u"瀏覽"; - const char16_t term2[] = u"速度"; - const char16_t term3[] = u"飛快"; - const std::u16string str(base::JoinString({term1, term2, term3}, u"")); + const char term1[] = "瀏覽"; + const char term2[] = "速度"; + const char term3[] = "飛快"; + const std::u16string str( + UTF8ToUTF16(base::JoinString({term1, term2, term3}, ""))); BreakIterator iter(str, BreakIterator::BREAK_WORD); ASSERT_TRUE(iter.Init()); EXPECT_TRUE(iter.Advance()); EXPECT_TRUE(iter.IsWord()); - EXPECT_EQ(term1, iter.GetString()); + EXPECT_EQ(UTF8ToUTF16(term1), iter.GetString()); EXPECT_TRUE(iter.Advance()); EXPECT_TRUE(iter.IsWord()); - EXPECT_EQ(term2, iter.GetString()); + EXPECT_EQ(UTF8ToUTF16(term2), iter.GetString()); EXPECT_TRUE(iter.Advance()); EXPECT_TRUE(iter.IsWord()); - EXPECT_EQ(term3, iter.GetString()); + EXPECT_EQ(UTF8ToUTF16(term3), iter.GetString()); EXPECT_FALSE(iter.Advance()); EXPECT_FALSE(iter.IsWord()); } TEST(BreakIteratorTest, BreakWordJapanese) { // Terms in Japanese, without spaces in between. - const char16_t term1[] = u"モバイル"; - const char16_t term2[] = u"でも"; - const std::u16string str(base::JoinString({term1, term2}, u"")); + const char term1[] = "モバイル"; + const char term2[] = "でも"; + const std::u16string str(UTF8ToUTF16(base::JoinString({term1, term2}, ""))); BreakIterator iter(str, BreakIterator::BREAK_WORD); ASSERT_TRUE(iter.Init()); EXPECT_TRUE(iter.Advance()); EXPECT_TRUE(iter.IsWord()); - EXPECT_EQ(term1, iter.GetString()); + EXPECT_EQ(UTF8ToUTF16(term1), iter.GetString()); EXPECT_TRUE(iter.Advance()); EXPECT_TRUE(iter.IsWord()); - EXPECT_EQ(term2, iter.GetString()); + EXPECT_EQ(UTF8ToUTF16(term2), iter.GetString()); EXPECT_FALSE(iter.Advance()); EXPECT_FALSE(iter.IsWord()); } @@ -186,21 +191,21 @@ TEST(BreakIteratorTest, BreakWordChineseEnglish) { // Terms in Simplified Chinese mixed with English and wide punctuations. std::u16string space(u" "); - const char16_t token1[] = u"下载"; - const char16_t token2[] = u"Chrome"; - const char16_t token3[] = u"("; - const char16_t token4[] = u"Mac"; - const char16_t token5[] = u"版"; - const char16_t token6[] = u")"; - const std::u16string str(base::JoinString( - {token1, u" ", token2, token3, token4, u" ", token5, token6}, u"")); + const char token1[] = "下载"; + const char token2[] = "Chrome"; + const char token3[] = "("; + const char token4[] = "Mac"; + const char token5[] = "版"; + const char token6[] = ")"; + const std::u16string str(UTF8ToUTF16(base::JoinString( + {token1, " ", token2, token3, token4, " ", token5, token6}, ""))); BreakIterator iter(str, BreakIterator::BREAK_WORD); ASSERT_TRUE(iter.Init()); EXPECT_TRUE(iter.Advance()); EXPECT_TRUE(iter.IsWord()); - EXPECT_EQ(token1, iter.GetString()); + EXPECT_EQ(UTF8ToUTF16(token1), iter.GetString()); EXPECT_TRUE(iter.Advance()); EXPECT_FALSE(iter.IsWord()); @@ -208,15 +213,15 @@ EXPECT_TRUE(iter.Advance()); EXPECT_TRUE(iter.IsWord()); - EXPECT_EQ(token2, iter.GetString()); + EXPECT_EQ(UTF8ToUTF16(token2), iter.GetString()); EXPECT_TRUE(iter.Advance()); EXPECT_FALSE(iter.IsWord()); - EXPECT_EQ(token3, iter.GetString()); + EXPECT_EQ(UTF8ToUTF16(token3), iter.GetString()); EXPECT_TRUE(iter.Advance()); EXPECT_TRUE(iter.IsWord()); - EXPECT_EQ(token4, iter.GetString()); + EXPECT_EQ(UTF8ToUTF16(token4), iter.GetString()); EXPECT_TRUE(iter.Advance()); EXPECT_FALSE(iter.IsWord()); @@ -224,11 +229,11 @@ EXPECT_TRUE(iter.Advance()); EXPECT_TRUE(iter.IsWord()); - EXPECT_EQ(token5, iter.GetString()); + EXPECT_EQ(UTF8ToUTF16(token5), iter.GetString()); EXPECT_TRUE(iter.Advance()); EXPECT_FALSE(iter.IsWord()); - EXPECT_EQ(token6, iter.GetString()); + EXPECT_EQ(UTF8ToUTF16(token6), iter.GetString()); EXPECT_FALSE(iter.Advance()); EXPECT_FALSE(iter.IsWord()); @@ -318,7 +323,10 @@ } TEST(BreakIteratorTest, BreakSpaceWide32) { - const std::u16string str = u"\U0001d49c a"; + // U+1D49C MATHEMATICAL SCRIPT CAPITAL A + const char very_wide_char[] = "\xF0\x9D\x92\x9C"; + const std::u16string str( + UTF8ToUTF16(base::StringPrintf("%s a", very_wide_char))); const std::u16string very_wide_word(str.substr(0, 3)); BreakIterator iter(str, BreakIterator::BREAK_SPACE); @@ -370,8 +378,8 @@ TEST(BreakIteratorTest, BreakSentence) { std::u16string nl(u"\n"); - std::u16string str( - u"\nFoo bar!\nOne sentence.\n\n\tAnother sentence?One more thing"); + std::u16string str(UTF8ToUTF16( + "\nFoo bar!\nOne sentence.\n\n\tAnother sentence?One more thing")); BreakIterator iter(str, BreakIterator::BREAK_SENTENCE); ASSERT_TRUE(iter.Init()); EXPECT_TRUE(iter.Advance()); @@ -397,8 +405,8 @@ } TEST(BreakIteratorTest, IsSentenceBoundary) { - std::u16string str( - u"Foo bar!\nOne sentence.\n\n\tAnother sentence?One more thing"); + std::u16string str(UTF8ToUTF16( + "Foo bar!\nOne sentence.\n\n\tAnother sentence?One more thing")); BreakIterator iter(str, BreakIterator::BREAK_SENTENCE); ASSERT_TRUE(iter.Init()); @@ -462,7 +470,10 @@ } TEST(BreakIteratorTest, BreakLineWide32) { - const std::u16string str = u"\U0001d49c\na"; + // U+1D49C MATHEMATICAL SCRIPT CAPITAL A + const char very_wide_char[] = "\xF0\x9D\x92\x9C"; + const std::u16string str( + UTF8ToUTF16(base::StringPrintf("%s\na", very_wide_char))); const std::u16string very_wide_line(str.substr(0, 3)); BreakIterator iter(str, BreakIterator::BREAK_NEWLINE); ASSERT_TRUE(iter.Init()); @@ -479,29 +490,29 @@ } TEST(BreakIteratorTest, BreakCharacter) { - static const char16_t* const kCharacters[] = { + static const char* kCharacters[] = { // An English word consisting of four ASCII characters. - u"w", - u"o", - u"r", - u"d", - u" ", + "w", + "o", + "r", + "d", + " ", // A Hindi word (which means "Hindi") consisting of two Devanagari // grapheme clusters. - u"हि", - u"न्दी", - u" ", + "\u0939\u093F", + "\u0928\u094D\u0926\u0940", + " ", // A Thai word (which means "feel") consisting of three Thai grapheme // clusters. - u"รู้", - u"สึ", - u"ก", - u" ", + "\u0E23\u0E39\u0E49", + "\u0E2A\u0E36", + "\u0E01", + " ", }; std::vector<std::u16string> characters; std::u16string text; - for (const auto* i : kCharacters) { - characters.push_back(i); + for (auto*& i : kCharacters) { + characters.push_back(base::UTF8ToUTF16(i)); text.append(characters.back()); } BreakIterator iter(text, BreakIterator::BREAK_CHARACTER);
diff --git a/base/observer_list_threadsafe.h b/base/observer_list_threadsafe.h index dc6b7bb9d..c750bbb0 100644 --- a/base/observer_list_threadsafe.h +++ b/base/observer_list_threadsafe.h
@@ -7,7 +7,6 @@ #include <unordered_map> #include <utility> -#include <vector> #include "base/base_export.h" #include "base/bind.h" @@ -43,7 +42,11 @@ // The drawback of the threadsafe observer list is that notifications are not // as real-time as the non-threadsafe version of this class. Notifications // will always be done via PostTask() to another sequence, whereas with the -// non-thread-safe observer_list, notifications happen synchronously. +// non-thread-safe ObserverList, notifications happen synchronously. +// +// Note: this class previously supported synchronous notifications for +// same-sequence observers, but it was error-prone and removed in +// crbug.com/1193750, think twice before re-considering this paradigm. // /////////////////////////////////////////////////////////////////////////////// @@ -199,49 +202,6 @@ } } - // Like Notify() but attempts to synchronously invoke callbacks if they are - // associated with this thread. - template <typename Method, typename... Params> - void NotifySynchronously(const Location& from_here, - Method m, - Params&&... params) { - RepeatingCallback<void(ObserverType*)> method = - BindRepeating(&Dispatcher<ObserverType, Method>::Run, m, - std::forward<Params>(params)...); - - // The observers may make reentrant calls (which can be a problem due to the - // lock), so we extract a list to call synchronously. - struct PendingNotificationData { - ObserverType* observer; - size_t observer_id; - }; - std::vector<PendingNotificationData> current_sequence_observers; - - { - AutoLock lock(lock_); - current_sequence_observers.reserve(observers_.size()); - for (const auto& observer : observers_) { - if (observer.second.task_runner->RunsTasksInCurrentSequence()) { - current_sequence_observers.emplace_back(PendingNotificationData{ - observer.first, observer.second.observer_id}); - } else { - observer.second.task_runner->PostTask( - from_here, - BindOnce(&ObserverListThreadSafe<ObserverType>::NotifyWrapper, - this, observer.first, - NotificationData(this, observer.second.observer_id, - from_here, method))); - } - } - } - - for (const auto& pending_notification : current_sequence_observers) { - NotifyWrapper(pending_notification.observer, - NotificationData(this, pending_notification.observer_id, - from_here, method)); - } - } - private: friend class RefCountedThreadSafe<ObserverListThreadSafeBase>;
diff --git a/base/observer_list_threadsafe_unittest.cc b/base/observer_list_threadsafe_unittest.cc index 08f4aa4..3dee47f 100644 --- a/base/observer_list_threadsafe_unittest.cc +++ b/base/observer_list_threadsafe_unittest.cc
@@ -514,59 +514,4 @@ EXPECT_EQ(1, c.total); } -TEST(ObserverListThreadSafeTest, NotifySynchronously) { - test::TaskEnvironment task_environment; - - scoped_refptr<ObserverListThreadSafe<Foo>> observer_list( - new ObserverListThreadSafe<Foo>); - Adder a(1); - Adder b(-1); - Adder c(1); - Adder d(-1); - - observer_list->AddObserver(&a); - observer_list->AddObserver(&b); - - observer_list->NotifySynchronously(FROM_HERE, &Foo::Observe, 10); - - observer_list->AddObserver(&c); - observer_list->AddObserver(&d); - - observer_list->NotifySynchronously(FROM_HERE, &Foo::Observe, 10); - - EXPECT_EQ(20, a.total); - EXPECT_EQ(-20, b.total); - EXPECT_EQ(10, c.total); - EXPECT_EQ(-10, d.total); -} - -TEST(ObserverListThreadSafeTest, NotifySynchronouslyCrossSequence) { - test::TaskEnvironment task_environment; - - scoped_refptr<ObserverListThreadSafe<Foo>> observer_list( - new ObserverListThreadSafe<Foo>); - Adder a(1); - observer_list->AddObserver(&a); - - WaitableEvent event(WaitableEvent::ResetPolicy::AUTOMATIC, - WaitableEvent::InitialState::NOT_SIGNALED); - // Call NotifySynchronously on a different sequence. - ThreadPool::PostTask(FROM_HERE, {}, BindLambdaForTesting([&]() { - observer_list->NotifySynchronously(FROM_HERE, - &Foo::Observe, 10); - event.Signal(); - })); - - event.Wait(); - - // Because it was run on a different sequence NotifySynchronously should have - // posted a task which hasn't run yet. - EXPECT_EQ(0, a.total); - - RunLoop().RunUntilIdle(); - - // Verify the task has now run. - EXPECT_EQ(10, a.total); -} - } // namespace base
diff --git a/base/strings/string_piece_unittest.cc b/base/strings/string_piece_unittest.cc index e7d46413..5cb60aa 100644 --- a/base/strings/string_piece_unittest.cc +++ b/base/strings/string_piece_unittest.cc
@@ -633,11 +633,12 @@ ASSERT_EQ(f.size(), 6U); } + + TEST(StringPiece16Test, CheckConversion) { - // Make sure that we can convert from UTF8 to UTF16 and back. We use a - // character (G clef) outside the BMP to test this. - const char kTest[] = "\U0001D11E"; - ASSERT_EQ(UTF16ToUTF8(UTF8ToUTF16(kTest)), kTest); + // Make sure that we can convert from UTF8 to UTF16 and back. We use a two + // byte character (G clef) to test this. + ASSERT_EQ(UTF16ToUTF8(UTF8ToUTF16("\xf0\x9d\x84\x9e")), "\xf0\x9d\x84\x9e"); } TYPED_TEST(CommonStringPieceTest, CheckConstructors) {
diff --git a/base/threading/thread_local.h b/base/threading/thread_local.h index 92f9907..d1ab40a 100644 --- a/base/threading/thread_local.h +++ b/base/threading/thread_local.h
@@ -53,7 +53,6 @@ #include "base/check_op.h" #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "base/threading/thread_local_internal.h" #include "base/threading/thread_local_storage.h" @@ -103,15 +102,11 @@ T* Get() const { return static_cast<T*>(slot_.Get()); } - // Sets a new value, returns the old. - std::unique_ptr<T> Set(std::unique_ptr<T> ptr) { - auto existing = WrapUnique(Get()); + void Set(std::unique_ptr<T> ptr) { + delete Get(); slot_.Set(const_cast<void*>(static_cast<const void*>(ptr.release()))); - return existing; } - T& operator*() { return *Get(); } - private: static void DeleteTlsPtr(void* ptr) { delete static_cast<T*>(ptr); }
diff --git a/base/threading/thread_local_internal.h b/base/threading/thread_local_internal.h index 7d23b1f..184b2d3 100644 --- a/base/threading/thread_local_internal.h +++ b/base/threading/thread_local_internal.h
@@ -40,24 +40,14 @@ return ptr_tracker ? ptr_tracker->ptr_.get() : nullptr; } - std::unique_ptr<T> Set(std::unique_ptr<T> ptr) { - std::unique_ptr<T> existing_ptr; - auto existing_tracker = static_cast<PtrTracker*>(slot_.Get()); - if (existing_tracker) { - existing_ptr = std::move(existing_tracker->ptr_); - delete existing_tracker; - } - + void Set(std::unique_ptr<T> ptr) { + delete static_cast<PtrTracker*>(slot_.Get()); if (ptr) slot_.Set(new PtrTracker(this, std::move(ptr))); else slot_.Set(nullptr); - - return existing_ptr; } - T& operator*() { return *Get(); } - private: struct PtrTracker { public: @@ -71,7 +61,7 @@ } CheckedThreadLocalOwnedPointer<T>* const outer_; - std::unique_ptr<T> ptr_; + const std::unique_ptr<T> ptr_; }; static void DeleteTlsPtr(void* ptr) { delete static_cast<PtrTracker*>(ptr); }
diff --git a/base/threading/thread_restrictions.cc b/base/threading/thread_restrictions.cc index e67d23c..499d0c74 100644 --- a/base/threading/thread_restrictions.cc +++ b/base/threading/thread_restrictions.cc
@@ -8,228 +8,204 @@ #if DCHECK_IS_ON() -#include <utility> - #include "base/check_op.h" #include "base/debug/stack_trace.h" -#include "base/no_destructor.h" -#include "base/optional.h" +#include "base/lazy_instance.h" #include "base/threading/thread_local.h" #include "base/trace_event/base_tracing.h" #include "build/build_config.h" namespace base { -struct BooleanWithStack { - // Default value. - BooleanWithStack() : value_(false) {} - - // Value when explicitly set. - explicit BooleanWithStack(bool value) - : value_(value) -#if !defined(OS_NACL) && !defined(OS_ANDROID) - , - stack_(in_place) -#endif - { - } - - explicit operator bool() const { return value_; } - - friend std::ostream& operator<<(std::ostream& out, - const BooleanWithStack& bws) { - out << bws.value_; -#if !defined(OS_NACL) && !defined(OS_ANDROID) - if (bws.stack_.has_value()) { - out << " set by\n" << bws.stack_.value(); - } else { - out << " (value by default)"; - } -#endif - return out; - } - - const bool value_; - -// NaCL doesn't support stack sampling and Android is slow at stack -// sampling and this causes timeouts (crbug.com/959139). -#if !defined(OS_NACL) && !defined(OS_ANDROID) - const Optional<debug::StackTrace> stack_; -#endif -}; +std::ostream& operator<<(std::ostream&out, const ThreadLocalBoolean& tl) { + out << "currently set to " << (tl.Get() ? "true" : "false"); + return out; +} namespace { -ThreadLocalOwnedPointer<BooleanWithStack>& GetBlockingDisallowedTls() { - static NoDestructor<ThreadLocalOwnedPointer<BooleanWithStack>> instance; - auto& tls = *instance; - if (!tls.Get()) - tls.Set(std::make_unique<BooleanWithStack>()); - return tls; -} -ThreadLocalOwnedPointer<BooleanWithStack>& GetSingletonDisallowedTls() { - static NoDestructor<ThreadLocalOwnedPointer<BooleanWithStack>> instance; - auto& tls = *instance; - if (!tls.Get()) - tls.Set(std::make_unique<BooleanWithStack>()); - return tls; -} -ThreadLocalOwnedPointer<BooleanWithStack>& -GetBaseSyncPrimitivesDisallowedTls() { - static NoDestructor<ThreadLocalOwnedPointer<BooleanWithStack>> instance; - auto& tls = *instance; - if (!tls.Get()) - tls.Set(std::make_unique<BooleanWithStack>()); - return tls; -} -ThreadLocalOwnedPointer<BooleanWithStack>& GetCPUIntensiveWorkDisallowedTls() { - static NoDestructor<ThreadLocalOwnedPointer<BooleanWithStack>> instance; - auto& tls = *instance; - if (!tls.Get()) - tls.Set(std::make_unique<BooleanWithStack>()); - return tls; -} +#if defined(OS_NACL) || defined(OS_ANDROID) +// NaCL doesn't support stack sampling and Android is slow at stack +// sampling and this causes timeouts (crbug.com/959139). +using ThreadLocalBooleanWithStacks = ThreadLocalBoolean; +#else +class ThreadLocalBooleanWithStacks { + public: + ThreadLocalBooleanWithStacks() = default; + + bool Get() const { return bool_.Get(); } + + void Set(bool val) { + stack_.Set(std::make_unique<debug::StackTrace>()); + bool_.Set(val); + } + + friend std::ostream& operator<<(std::ostream& out, + const ThreadLocalBooleanWithStacks& tl) { + out << tl.bool_ << " by "; + + if (!tl.stack_.Get()) + return out << "default value\n"; + out << "\n"; + tl.stack_.Get()->OutputToStream(&out); + return out; + } + + private: + ThreadLocalBoolean bool_; + ThreadLocalOwnedPointer<debug::StackTrace> stack_; + + DISALLOW_COPY_AND_ASSIGN(ThreadLocalBooleanWithStacks); +}; +#endif // defined(OS_NACL) + +LazyInstance<ThreadLocalBooleanWithStacks>::Leaky g_blocking_disallowed = + LAZY_INSTANCE_INITIALIZER; + +LazyInstance<ThreadLocalBooleanWithStacks>::Leaky g_singleton_disallowed = + LAZY_INSTANCE_INITIALIZER; + +LazyInstance<ThreadLocalBooleanWithStacks>::Leaky + g_base_sync_primitives_disallowed = LAZY_INSTANCE_INITIALIZER; + +LazyInstance<ThreadLocalBooleanWithStacks>::Leaky + g_cpu_intensive_work_disallowed = LAZY_INSTANCE_INITIALIZER; } // namespace namespace internal { void AssertBlockingAllowed() { - DCHECK(!*GetBlockingDisallowedTls()) + DCHECK(!g_blocking_disallowed.Get().Get()) << "Function marked as blocking was called from a scope that disallows " "blocking! If this task is running inside the ThreadPool, it needs " "to have MayBlock() in its TaskTraits. Otherwise, consider making " "this blocking work asynchronous or, as a last resort, you may use " "ScopedAllowBlocking (see its documentation for best practices).\n" - << "g_blocking_disallowed " << *GetBlockingDisallowedTls(); + << "g_blocking_disallowed " << g_blocking_disallowed.Get(); } } // namespace internal void DisallowBlocking() { - GetBlockingDisallowedTls().Set(std::make_unique<BooleanWithStack>(true)); + g_blocking_disallowed.Get().Set(true); } ScopedDisallowBlocking::ScopedDisallowBlocking() - : was_disallowed_(GetBlockingDisallowedTls().Set( - std::make_unique<BooleanWithStack>(true))) {} + : was_disallowed_(g_blocking_disallowed.Get().Get()) { + g_blocking_disallowed.Get().Set(true); +} ScopedDisallowBlocking::~ScopedDisallowBlocking() { - DCHECK(*GetBlockingDisallowedTls()) - << "~ScopedDisallowBlocking() running while surprisingly already no " - "longer disallowed.\n" - << "g_blocking_disallowed " << *GetBlockingDisallowedTls(); - GetBlockingDisallowedTls().Set(std::move(was_disallowed_)); + DCHECK(g_blocking_disallowed.Get().Get()); + g_blocking_disallowed.Get().Set(was_disallowed_); } void DisallowBaseSyncPrimitives() { - GetBaseSyncPrimitivesDisallowedTls().Set( - std::make_unique<BooleanWithStack>(true)); + g_base_sync_primitives_disallowed.Get().Set(true); } ScopedAllowBaseSyncPrimitives::ScopedAllowBaseSyncPrimitives() - : was_disallowed_(GetBaseSyncPrimitivesDisallowedTls().Set( - std::make_unique<BooleanWithStack>(false))) { - DCHECK(!*GetBlockingDisallowedTls()) + : was_disallowed_(g_base_sync_primitives_disallowed.Get().Get()) { + DCHECK(!g_blocking_disallowed.Get().Get()) << "To allow //base sync primitives in a scope where blocking is " "disallowed use ScopedAllowBaseSyncPrimitivesOutsideBlockingScope.\n" - << "g_blocking_disallowed " << *GetBlockingDisallowedTls(); + << "g_blocking_disallowed " << g_blocking_disallowed.Get(); + g_base_sync_primitives_disallowed.Get().Set(false); } ScopedAllowBaseSyncPrimitives::~ScopedAllowBaseSyncPrimitives() { - DCHECK(!*GetBaseSyncPrimitivesDisallowedTls()); - GetBaseSyncPrimitivesDisallowedTls().Set(std::move(was_disallowed_)); + DCHECK(!g_base_sync_primitives_disallowed.Get().Get()); + g_base_sync_primitives_disallowed.Get().Set(was_disallowed_); } ScopedAllowBaseSyncPrimitivesForTesting:: ScopedAllowBaseSyncPrimitivesForTesting() - : was_disallowed_(GetBaseSyncPrimitivesDisallowedTls().Set( - std::make_unique<BooleanWithStack>(false))) {} + : was_disallowed_(g_base_sync_primitives_disallowed.Get().Get()) { + g_base_sync_primitives_disallowed.Get().Set(false); +} ScopedAllowBaseSyncPrimitivesForTesting:: ~ScopedAllowBaseSyncPrimitivesForTesting() { - DCHECK(!*GetBaseSyncPrimitivesDisallowedTls()); - GetBaseSyncPrimitivesDisallowedTls().Set(std::move(was_disallowed_)); + DCHECK(!g_base_sync_primitives_disallowed.Get().Get()); + g_base_sync_primitives_disallowed.Get().Set(was_disallowed_); } ScopedAllowUnresponsiveTasksForTesting::ScopedAllowUnresponsiveTasksForTesting() - : was_disallowed_base_sync_(GetBaseSyncPrimitivesDisallowedTls().Set( - std::make_unique<BooleanWithStack>(false))), - was_disallowed_blocking_(GetBlockingDisallowedTls().Set( - std::make_unique<BooleanWithStack>(false))), - was_disallowed_cpu_(GetCPUIntensiveWorkDisallowedTls().Set( - std::make_unique<BooleanWithStack>(false))) {} + : was_disallowed_base_sync_(g_base_sync_primitives_disallowed.Get().Get()), + was_disallowed_blocking_(g_blocking_disallowed.Get().Get()), + was_disallowed_cpu_(g_cpu_intensive_work_disallowed.Get().Get()) { + g_base_sync_primitives_disallowed.Get().Set(false); + g_blocking_disallowed.Get().Set(false); + g_cpu_intensive_work_disallowed.Get().Set(false); +} ScopedAllowUnresponsiveTasksForTesting:: ~ScopedAllowUnresponsiveTasksForTesting() { - DCHECK(!*GetBaseSyncPrimitivesDisallowedTls()); - DCHECK(!*GetBlockingDisallowedTls()); - DCHECK(!*GetCPUIntensiveWorkDisallowedTls()); - GetBaseSyncPrimitivesDisallowedTls().Set( - std::move(was_disallowed_base_sync_)); - GetBlockingDisallowedTls().Set(std::move(was_disallowed_blocking_)); - GetCPUIntensiveWorkDisallowedTls().Set(std::move(was_disallowed_cpu_)); + DCHECK(!g_base_sync_primitives_disallowed.Get().Get()); + DCHECK(!g_blocking_disallowed.Get().Get()); + DCHECK(!g_cpu_intensive_work_disallowed.Get().Get()); + g_base_sync_primitives_disallowed.Get().Set(was_disallowed_base_sync_); + g_blocking_disallowed.Get().Set(was_disallowed_blocking_); + g_cpu_intensive_work_disallowed.Get().Set(was_disallowed_cpu_); } namespace internal { void AssertBaseSyncPrimitivesAllowed() { - DCHECK(!*GetBaseSyncPrimitivesDisallowedTls()) + DCHECK(!g_base_sync_primitives_disallowed.Get().Get()) << "Waiting on a //base sync primitive is not allowed on this thread to " "prevent jank and deadlock. If waiting on a //base sync primitive is " "unavoidable, do it within the scope of a " "ScopedAllowBaseSyncPrimitives. If in a test, " "use ScopedAllowBaseSyncPrimitivesForTesting.\n" << "g_base_sync_primitives_disallowed " - << *GetBaseSyncPrimitivesDisallowedTls() + << g_base_sync_primitives_disallowed.Get() << "It can be useful to know that g_blocking_disallowed is " - << *GetBlockingDisallowedTls(); + << g_blocking_disallowed.Get(); } void ResetThreadRestrictionsForTesting() { - GetBlockingDisallowedTls().Set(std::make_unique<BooleanWithStack>(false)); - GetSingletonDisallowedTls().Set(std::make_unique<BooleanWithStack>(false)); - GetBaseSyncPrimitivesDisallowedTls().Set( - std::make_unique<BooleanWithStack>(false)); - GetCPUIntensiveWorkDisallowedTls().Set( - std::make_unique<BooleanWithStack>(false)); + g_blocking_disallowed.Get().Set(false); + g_singleton_disallowed.Get().Set(false); + g_base_sync_primitives_disallowed.Get().Set(false); + g_cpu_intensive_work_disallowed.Get().Set(false); } } // namespace internal void AssertLongCPUWorkAllowed() { - DCHECK(!*GetCPUIntensiveWorkDisallowedTls()) + DCHECK(!g_cpu_intensive_work_disallowed.Get().Get()) << "Function marked as CPU intensive was called from a scope that " "disallows this kind of work! Consider making this work " "asynchronous.\n" << "g_cpu_intensive_work_disallowed " - << *GetCPUIntensiveWorkDisallowedTls(); + << g_cpu_intensive_work_disallowed.Get(); } void DisallowUnresponsiveTasks() { DisallowBlocking(); DisallowBaseSyncPrimitives(); - GetCPUIntensiveWorkDisallowedTls().Set( - std::make_unique<BooleanWithStack>(true)); + g_cpu_intensive_work_disallowed.Get().Set(true); } // static bool ThreadRestrictions::SetIOAllowed(bool allowed) { - const bool previously_allowed = !*GetBlockingDisallowedTls().Set( - std::make_unique<BooleanWithStack>(!allowed)); - return previously_allowed; + bool previous_disallowed = g_blocking_disallowed.Get().Get(); + g_blocking_disallowed.Get().Set(!allowed); + return !previous_disallowed; } // static bool ThreadRestrictions::SetSingletonAllowed(bool allowed) { - const bool previously_allowed = !*GetSingletonDisallowedTls().Set( - std::make_unique<BooleanWithStack>(!allowed)); - return previously_allowed; + bool previous_disallowed = g_singleton_disallowed.Get().Get(); + g_singleton_disallowed.Get().Set(!allowed); + return !previous_disallowed; } // static void ThreadRestrictions::AssertSingletonAllowed() { - DCHECK(!*GetSingletonDisallowedTls()) + DCHECK(!g_singleton_disallowed.Get().Get()) << "LazyInstance/Singleton is not allowed to be used on this thread. " "Most likely it's because this thread is not joinable (or the current " "task is running with TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN " @@ -237,7 +213,7 @@ "shutdown, leading to a potential shutdown crash. If you need to use " "the object from this context, it'll have to be updated to use Leaky " "traits.\n" - << "g_singleton_disallowed " << *GetSingletonDisallowedTls(); + << "g_singleton_disallowed " << g_singleton_disallowed.Get(); } // static @@ -246,9 +222,9 @@ } bool ThreadRestrictions::SetWaitAllowed(bool allowed) { - const bool previously_allowed = !*GetBaseSyncPrimitivesDisallowedTls().Set( - std::make_unique<BooleanWithStack>(!allowed)); - return previously_allowed; + bool previous_disallowed = g_base_sync_primitives_disallowed.Get().Get(); + g_base_sync_primitives_disallowed.Get().Set(!allowed); + return !previous_disallowed; } } // namespace base @@ -259,8 +235,7 @@ ScopedAllowBlocking::ScopedAllowBlocking(const Location& from_here) #if DCHECK_IS_ON() - : was_disallowed_(GetBlockingDisallowedTls().Set( - std::make_unique<BooleanWithStack>(false))) + : was_disallowed_(g_blocking_disallowed.Get().Get()) #endif { TRACE_EVENT_BEGIN( @@ -269,22 +244,25 @@ base::trace_event::InternedSourceLocation::Get( &ctx, base::trace_event::TraceSourceLocation(from_here))); }); + +#if DCHECK_IS_ON() + g_blocking_disallowed.Get().Set(false); +#endif } ScopedAllowBlocking::~ScopedAllowBlocking() { TRACE_EVENT_END0("base", "ScopedAllowBlocking"); #if DCHECK_IS_ON() - DCHECK(!*GetBlockingDisallowedTls()); - GetBlockingDisallowedTls().Set(std::move(was_disallowed_)); + DCHECK(!g_blocking_disallowed.Get().Get()); + g_blocking_disallowed.Get().Set(was_disallowed_); #endif } ScopedAllowBaseSyncPrimitivesOutsideBlockingScope:: ScopedAllowBaseSyncPrimitivesOutsideBlockingScope(const Location& from_here) #if DCHECK_IS_ON() - : was_disallowed_(GetBaseSyncPrimitivesDisallowedTls().Set( - std::make_unique<BooleanWithStack>(false))) + : was_disallowed_(g_base_sync_primitives_disallowed.Get().Get()) #endif { TRACE_EVENT_BEGIN( @@ -294,6 +272,10 @@ base::trace_event::InternedSourceLocation::Get( &ctx, base::trace_event::TraceSourceLocation(from_here))); }); + +#if DCHECK_IS_ON() + g_base_sync_primitives_disallowed.Get().Set(false); +#endif } ScopedAllowBaseSyncPrimitivesOutsideBlockingScope:: @@ -301,15 +283,14 @@ TRACE_EVENT_END0("base", "ScopedAllowBaseSyncPrimitivesOutsideBlockingScope"); #if DCHECK_IS_ON() - DCHECK(!*GetBaseSyncPrimitivesDisallowedTls()); - GetBaseSyncPrimitivesDisallowedTls().Set(std::move(was_disallowed_)); + DCHECK(!g_base_sync_primitives_disallowed.Get().Get()); + g_base_sync_primitives_disallowed.Get().Set(was_disallowed_); #endif } ThreadRestrictions::ScopedAllowIO::ScopedAllowIO(const Location& from_here) #if DCHECK_IS_ON() - : was_disallowed_(GetBlockingDisallowedTls().Set( - std::make_unique<BooleanWithStack>(false))) + : was_allowed_(SetIOAllowed(true)) #endif { TRACE_EVENT_BEGIN("base", "ScopedAllowIO", [&](perfetto::EventContext ctx) { @@ -323,7 +304,7 @@ TRACE_EVENT_END0("base", "ScopedAllowIO"); #if DCHECK_IS_ON() - GetBlockingDisallowedTls().Set(std::move(was_disallowed_)); + SetIOAllowed(was_allowed_); #endif }
diff --git a/base/threading/thread_restrictions.h b/base/threading/thread_restrictions.h index 261e474..8fdd58d 100644 --- a/base/threading/thread_restrictions.h +++ b/base/threading/thread_restrictions.h
@@ -5,12 +5,8 @@ #ifndef BASE_THREADING_THREAD_RESTRICTIONS_H_ #define BASE_THREADING_THREAD_RESTRICTIONS_H_ -#include <memory> - #include "base/base_export.h" #include "base/check_op.h" -#include "base/compiler_specific.h" -#include "base/dcheck_is_on.h" #include "base/gtest_prod_util.h" #include "base/location.h" #include "base/macros.h" @@ -346,8 +342,6 @@ class Thread; class WaitableEvent; -struct BooleanWithStack; - bool PathProviderWin(int, FilePath*); #if DCHECK_IS_ON() @@ -385,7 +379,7 @@ private: #if DCHECK_IS_ON() - std::unique_ptr<BooleanWithStack> was_disallowed_; + const bool was_disallowed_; #endif DISALLOW_COPY_AND_ASSIGN(ScopedDisallowBlocking); @@ -393,8 +387,6 @@ class BASE_EXPORT ScopedAllowBlocking { private: - FRIEND_TEST_ALL_PREFIXES(ThreadRestrictionsTest, - NestedAllowRestoresPreviousStack); FRIEND_TEST_ALL_PREFIXES(ThreadRestrictionsTest, ScopedAllowBlocking); friend class ScopedAllowBlockingForTesting; @@ -437,7 +429,7 @@ ~ScopedAllowBlocking(); #if DCHECK_IS_ON() - std::unique_ptr<BooleanWithStack> was_disallowed_; + const bool was_disallowed_; #endif DISALLOW_COPY_AND_ASSIGN(ScopedAllowBlocking); @@ -511,7 +503,7 @@ ~ScopedAllowBaseSyncPrimitives() EMPTY_BODY_IF_DCHECK_IS_OFF; #if DCHECK_IS_ON() - std::unique_ptr<BooleanWithStack> was_disallowed_; + const bool was_disallowed_; #endif DISALLOW_COPY_AND_ASSIGN(ScopedAllowBaseSyncPrimitives); @@ -600,7 +592,7 @@ ~ScopedAllowBaseSyncPrimitivesOutsideBlockingScope(); #if DCHECK_IS_ON() - std::unique_ptr<BooleanWithStack> was_disallowed_; + const bool was_disallowed_; #endif // Since this object is used to indicate that sync primitives will be used to @@ -623,7 +615,7 @@ private: #if DCHECK_IS_ON() - std::unique_ptr<BooleanWithStack> was_disallowed_; + const bool was_disallowed_; #endif DISALLOW_COPY_AND_ASSIGN(ScopedAllowBaseSyncPrimitivesForTesting); @@ -638,9 +630,9 @@ private: #if DCHECK_IS_ON() - std::unique_ptr<BooleanWithStack> was_disallowed_base_sync_; - std::unique_ptr<BooleanWithStack> was_disallowed_blocking_; - std::unique_ptr<BooleanWithStack> was_disallowed_cpu_; + const bool was_disallowed_base_sync_; + const bool was_disallowed_blocking_; + const bool was_disallowed_cpu_; #endif DISALLOW_COPY_AND_ASSIGN(ScopedAllowUnresponsiveTasksForTesting); @@ -679,7 +671,7 @@ private: #if DCHECK_IS_ON() - std::unique_ptr<BooleanWithStack> was_disallowed_; + const bool was_allowed_; #endif DISALLOW_COPY_AND_ASSIGN(ScopedAllowIO); @@ -691,17 +683,11 @@ // Returns the previous value. // // DEPRECATED. Use ScopedAllowBlocking(ForTesting) or ScopedDisallowBlocking. - // - // NOT_TAIL_CALLED so it's always evident who irrevocably altered the - // allowance. - static bool NOT_TAIL_CALLED SetIOAllowed(bool allowed); + static bool SetIOAllowed(bool allowed); // Set whether the current thread can use singletons. Returns the previous // value. - // - // NOT_TAIL_CALLED so it's always evident who irrevocably altered the - // allowance. - static bool NOT_TAIL_CALLED SetSingletonAllowed(bool allowed); + static bool SetSingletonAllowed(bool allowed); // Check whether the current thread is allowed to use singletons (Singleton / // LazyInstance). DCHECKs if not. @@ -747,10 +733,7 @@ #if DCHECK_IS_ON() // DEPRECATED. Use ScopedAllowBaseSyncPrimitives. - // - // NOT_TAIL_CALLED so it's always evident who irrevocably altered the - // allowance. - static bool NOT_TAIL_CALLED SetWaitAllowed(bool allowed); + static bool SetWaitAllowed(bool allowed); #else static bool SetWaitAllowed(bool allowed) { return true; } #endif
diff --git a/base/threading/thread_restrictions_unittest.cc b/base/threading/thread_restrictions_unittest.cc index 44570f2..e44d97b 100644 --- a/base/threading/thread_restrictions_unittest.cc +++ b/base/threading/thread_restrictions_unittest.cc
@@ -8,12 +8,8 @@ #include "base/bind.h" #include "base/callback.h" -#include "base/compiler_specific.h" -#include "base/dcheck_is_on.h" -#include "base/debug/stack_trace.h" #include "base/macros.h" #include "base/test/gtest_util.h" -#include "build/build_config.h" #include "testing/gtest/include/gtest/gtest.h" namespace base { @@ -149,55 +145,4 @@ EXPECT_DCHECK_DEATH(AssertLongCPUWorkAllowed()); } -// thread_restriction_checks_enabled_and_has_death_tests -#if !defined(OS_NACL) && !defined(OS_ANDROID) && \ - defined(GTEST_HAS_DEATH_TEST) && DCHECK_IS_ON() - -TEST_F(ThreadRestrictionsTest, BlockingCheckEmitsStack) { - ScopedDisallowBlocking scoped_disallow_blocking; - // The above ScopedDisallowBlocking should be on the blame list for who set - // the ban. - EXPECT_DEATH({ internal::AssertBlockingAllowed(); }, - debug::StackTrace::WillSymbolizeToStreamForTesting() - ? "ScopedDisallowBlocking" - : ""); - // And the stack should mention this test body as source. - EXPECT_DEATH({ internal::AssertBlockingAllowed(); }, - debug::StackTrace::WillSymbolizeToStreamForTesting() - ? "BlockingCheckEmitsStack" - : ""); -} - -namespace { - -class CustomDisallow { - public: - NOINLINE CustomDisallow() { ThreadRestrictions::SetIOAllowed(false); } - NOINLINE ~CustomDisallow() { ThreadRestrictions::SetIOAllowed(true); } -}; - -} // namespace - -TEST_F(ThreadRestrictionsTest, NestedAllowRestoresPreviousStack) { - CustomDisallow custom_disallow; - { - ScopedAllowBlocking scoped_allow; - internal::AssertBlockingAllowed(); - } - // CustomDisallow should be back on the blame list (as opposed to - // ~ScopedAllowBlocking which is the last one to have changed the state but is - // no longer relevant). - EXPECT_DEATH({ internal::AssertBlockingAllowed(); }, - debug::StackTrace::WillSymbolizeToStreamForTesting() - ? "CustomDisallow" - : ""); - // And the stack should mention this test body as source. - EXPECT_DEATH({ internal::AssertBlockingAllowed(); }, - debug::StackTrace::WillSymbolizeToStreamForTesting() - ? "NestedAllowRestoresPreviousStack" - : ""); -} - -#endif // thread_restriction_checks_enabled_and_has_death_tests - } // namespace base
diff --git a/build/fuchsia/linux.sdk.sha1 b/build/fuchsia/linux.sdk.sha1 index c3fcd9d..e9a45a2 100644 --- a/build/fuchsia/linux.sdk.sha1 +++ b/build/fuchsia/linux.sdk.sha1
@@ -1 +1 @@ -4.20210506.3.1 +4.20210507.0.1
diff --git a/build/fuchsia/mac.sdk.sha1 b/build/fuchsia/mac.sdk.sha1 index c3fcd9d..4f0e934 100644 --- a/build/fuchsia/mac.sdk.sha1 +++ b/build/fuchsia/mac.sdk.sha1
@@ -1 +1 @@ -4.20210506.3.1 +4.20210507.1.1
diff --git a/build/fuchsia/target.py b/build/fuchsia/target.py index abe38f7..37601ea 100644 --- a/build/fuchsia/target.py +++ b/build/fuchsia/target.py
@@ -304,7 +304,8 @@ _GetPackageUri(package_name), '>/dev/null'], timeout_secs=_INSTALL_TIMEOUT_SECS) if return_code != 0: - raise Exception('Error while resolving %s.' % package_name) + raise Exception( + 'Error {} while resolving {}.'.format(return_code, package_name)) # Verify that the newly resolved versions of packages are reported. for package_path in package_paths:
diff --git a/cc/trees/layer_tree_host_single_thread_client.h b/cc/trees/layer_tree_host_single_thread_client.h index f35d3cfd..0a5f7d5 100644 --- a/cc/trees/layer_tree_host_single_thread_client.h +++ b/cc/trees/layer_tree_host_single_thread_client.h
@@ -17,6 +17,9 @@ // without a scheduler. virtual void RequestScheduleComposite() {} + // Tells single-threaded web tests that a new commit needs to be scheduled. + virtual void ScheduleAnimationForWebTests() {} + // Called whenever the begin frame interval changes. This interval can be used // for animations. virtual void FrameIntervalUpdated(base::TimeDelta interval) {}
diff --git a/cc/trees/single_thread_proxy.cc b/cc/trees/single_thread_proxy.cc index e7fe70a..29ed70d 100644 --- a/cc/trees/single_thread_proxy.cc +++ b/cc/trees/single_thread_proxy.cc
@@ -405,6 +405,7 @@ TRACE_EVENT0("cc", "SingleThreadProxy::SetNeedsOneBeginImplFrameOnImplThread"); single_thread_client_->RequestScheduleComposite(); + single_thread_client_->ScheduleAnimationForWebTests(); if (scheduler_on_impl_thread_) scheduler_on_impl_thread_->SetNeedsOneBeginImplFrame(); needs_impl_frame_ = true; @@ -418,6 +419,7 @@ void SingleThreadProxy::SetNeedsCommitOnImplThread() { single_thread_client_->RequestScheduleComposite(); + single_thread_client_->ScheduleAnimationForWebTests(); if (scheduler_on_impl_thread_) scheduler_on_impl_thread_->SetNeedsBeginMainFrame(); commit_requested_ = true;
diff --git a/chrome/android/chrome_junit_test_java_sources.gni b/chrome/android/chrome_junit_test_java_sources.gni index cc43b7d3..ccb6250 100644 --- a/chrome/android/chrome_junit_test_java_sources.gni +++ b/chrome/android/chrome_junit_test_java_sources.gni
@@ -95,7 +95,6 @@ "junit/src/org/chromium/chrome/browser/firstrun/FirstRunAppRestrictionInfoTest.java", "junit/src/org/chromium/chrome/browser/firstrun/FirstRunFlowSequencerTest.java", "junit/src/org/chromium/chrome/browser/firstrun/FirstRunIntegrationUnitTest.java", - "junit/src/org/chromium/chrome/browser/firstrun/ForcedSigninProcessorTest.java", "junit/src/org/chromium/chrome/browser/firstrun/PolicyLoadListenerUnitTest.java", "junit/src/org/chromium/chrome/browser/firstrun/SkipTosDialogPolicyListenerUnitTest.java", "junit/src/org/chromium/chrome/browser/firstrun/TosDialogBehaviorSharedPrefInvalidatorUnitTest.java",
diff --git a/chrome/android/chrome_test_java_sources.gni b/chrome/android/chrome_test_java_sources.gni index da5d20e..40f11cf 100644 --- a/chrome/android/chrome_test_java_sources.gni +++ b/chrome/android/chrome_test_java_sources.gni
@@ -369,7 +369,6 @@ "javatests/src/org/chromium/chrome/browser/payments/AndroidPaymentAppFinderTest.java", "javatests/src/org/chromium/chrome/browser/payments/AndroidPaymentAppFinderUnitTest.java", "javatests/src/org/chromium/chrome/browser/payments/CurrencyFormatterTest.java", - "javatests/src/org/chromium/chrome/browser/payments/ExpandablePaymentHandlerChangePaymentMethodTest.java", "javatests/src/org/chromium/chrome/browser/payments/ExpandablePaymentHandlerTest.java", "javatests/src/org/chromium/chrome/browser/payments/IsReadyToPayServiceHelperTest.java", "javatests/src/org/chromium/chrome/browser/payments/MockPackageManagerDelegate.java", @@ -502,6 +501,7 @@ "javatests/src/org/chromium/chrome/browser/share/ShareDelegateImplTest.java", "javatests/src/org/chromium/chrome/browser/share/ShareUrlTest.java", "javatests/src/org/chromium/chrome/browser/signin/IdentityManagerIntegrationTest.java", + "javatests/src/org/chromium/chrome/browser/signin/SigninCheckerTest.java", "javatests/src/org/chromium/chrome/browser/signin/SigninSignoutIntegrationTest.java", "javatests/src/org/chromium/chrome/browser/signin/SyncConsentFragmentTest.java", "javatests/src/org/chromium/chrome/browser/site_settings/ChromeSiteSettingsDelegateTest.java",
diff --git a/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantAccessibilityIntegrationTest.java b/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantAccessibilityIntegrationTest.java index da11782..6e6e959c 100644 --- a/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantAccessibilityIntegrationTest.java +++ b/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantAccessibilityIntegrationTest.java
@@ -40,7 +40,6 @@ import org.junit.runner.RunWith; import org.chromium.base.test.util.CommandLineFlags; -import org.chromium.base.test.util.DisableIf; import org.chromium.base.test.util.DisabledTest; import org.chromium.chrome.autofill_assistant.R; import org.chromium.chrome.browser.autofill_assistant.proto.ActionProto; @@ -118,7 +117,6 @@ @Test @MediumTest - @DisableIf.Build(sdk_is_less_than = 23) // see: https://crbug.com/1202724 public void testBottomSheetHasRestrictedFixedHeight() throws Exception { ArrayList<ActionProto> list = new ArrayList<>();
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/firstrun/ForcedSigninProcessor.java b/chrome/android/java/src/org/chromium/chrome/browser/firstrun/ForcedSigninProcessor.java index 81555a3..2da57681 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/firstrun/ForcedSigninProcessor.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/firstrun/ForcedSigninProcessor.java
@@ -4,37 +4,15 @@ package org.chromium.chrome.browser.firstrun; -import android.accounts.Account; import android.app.Activity; -import org.chromium.base.task.AsyncTask; -import org.chromium.chrome.browser.SyncFirstSetupCompleteSource; -import org.chromium.chrome.browser.childaccounts.ChildAccountService; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.browser.signin.services.IdentityServicesProvider; -import org.chromium.chrome.browser.signin.services.SigninManager; -import org.chromium.chrome.browser.sync.ProfileSyncService; import org.chromium.components.externalauth.ExternalAuthUtils; import org.chromium.components.externalauth.UserRecoverableErrorHandler; -import org.chromium.components.signin.AccountManagerFacade; -import org.chromium.components.signin.AccountManagerFacadeProvider; -import org.chromium.components.signin.ChildAccountStatus; -import org.chromium.components.signin.base.CoreAccountInfo; -import org.chromium.components.signin.metrics.SigninAccessPoint; - -import java.util.List; /** * A helper to perform all necessary steps for forced sign in. - * The helper performs: - * - necessary child account checks; - * - automatic non-interactive sign in for child accounts; and - * The helper calls the observer's onSignInComplete() if - * - nothing needs to be done, or when - * - the sign in is complete. - * - * Usage: - * ForcedSigninProcessor.start(). */ public final class ForcedSigninProcessor { /* @@ -43,72 +21,6 @@ private ForcedSigninProcessor() {} /** - * Check whether an automatic signin is required and process it if it is. - * This is triggered once per Chrome Application lifetime and every time the Account state - * changes with early exit if an account has already been signed in. - */ - public static void start() { - ChildAccountService.checkChildAccountStatus(status -> { - if (ChildAccountStatus.isChild(status)) { - final AccountManagerFacade accountManagerFacade = - AccountManagerFacadeProvider.getInstance(); - // Account cache is already available when child account status is ready. - final List<Account> accounts = accountManagerFacade.tryGetGoogleAccounts(); - assert accounts.size() == 1 : "Child account should be the only account on device!"; - new AsyncTask<String>() { - @Override - protected String doInBackground() { - return accountManagerFacade.getAccountGaiaId(accounts.get(0).name); - } - - @Override - protected void onPostExecute(String accountGaiaId) { - final CoreAccountInfo coreAccountInfo = - CoreAccountInfo.createFromEmailAndGaiaId( - accounts.get(0).name, accountGaiaId); - signinAndEnableSync(coreAccountInfo); - } - }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - } - }); - } - - /** - * Processes the fully automatic non-FRE-related forced sign-in. - * This is used to enforce the environment for child accounts. - */ - private static void signinAndEnableSync(final CoreAccountInfo childAccount) { - final Profile profile = Profile.getLastUsedRegularProfile(); - if (IdentityServicesProvider.get().getIdentityManager(profile).hasPrimaryAccount()) { - // TODO(https://crbug.com/1044206): Remove this. - ProfileSyncService.get().setFirstSetupComplete(SyncFirstSetupCompleteSource.BASIC_FLOW); - } - final SigninManager signinManager = - IdentityServicesProvider.get().getSigninManager(profile); - // By definition we have finished all the checks for first run. - signinManager.onFirstRunCheckDone(); - if (signinManager.isSignInAllowed()) { - signinManager.signinAndEnableSync(SigninAccessPoint.FORCED_SIGNIN, childAccount, - new SigninManager.SignInCallback() { - @Override - public void onSignInComplete() { - // TODO(https://crbug.com/1044206): Remove this. - ProfileSyncService syncService = ProfileSyncService.get(); - if (syncService == null) { - // Sync was disabled with a command-line flag, skip sign-in. - return; - } - syncService.setFirstSetupComplete( - SyncFirstSetupCompleteSource.BASIC_FLOW); - } - - @Override - public void onSignInAborted() {} - }); - } - } - - /** * If forced signin is required by policy, check that Google Play Services is available, and * show a non-cancelable dialog otherwise. * @param activity The activity for which to show the dialog.
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/init/ProcessInitializationHandler.java b/chrome/android/java/src/org/chromium/chrome/browser/init/ProcessInitializationHandler.java index be363db..cb7dc66d 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/init/ProcessInitializationHandler.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/init/ProcessInitializationHandler.java
@@ -45,7 +45,6 @@ import org.chromium.chrome.browser.download.DownloadController; import org.chromium.chrome.browser.download.DownloadManagerService; import org.chromium.chrome.browser.download.OfflineContentAvailabilityStatusProvider; -import org.chromium.chrome.browser.firstrun.ForcedSigninProcessor; import org.chromium.chrome.browser.firstrun.TosDialogBehaviorSharedPrefInvalidator; import org.chromium.chrome.browser.flags.CachedFeatureFlags; import org.chromium.chrome.browser.flags.ChromeFeatureList; @@ -87,7 +86,6 @@ import org.chromium.components.minidump_uploader.CrashFileManager; import org.chromium.components.signin.AccountManagerFacadeImpl; import org.chromium.components.signin.AccountManagerFacadeProvider; -import org.chromium.components.signin.AccountsChangeObserver; import org.chromium.components.viz.common.VizSwitches; import org.chromium.components.viz.common.display.DeJellyUtils; import org.chromium.components.webapps.AppBannerManager; @@ -95,7 +93,6 @@ import org.chromium.content_public.browser.ChildProcessLauncherHelper; import org.chromium.content_public.browser.ContactsPicker; import org.chromium.content_public.browser.ContactsPickerListener; -import org.chromium.content_public.browser.UiThreadTaskTraits; import org.chromium.content_public.common.ContentSwitches; import org.chromium.ui.base.Clipboard; import org.chromium.ui.base.PhotoPicker; @@ -347,21 +344,6 @@ deferredStartupHandler.addDeferredTask(new Runnable() { @Override public void run() { - ForcedSigninProcessor.start(); - AccountManagerFacadeProvider.getInstance().addObserver( - new AccountsChangeObserver() { - @Override - public void onAccountsChanged() { - PostTask.runOrPostTask(UiThreadTaskTraits.DEFAULT, - () -> { ForcedSigninProcessor.start(); }); - } - }); - } - }); - - deferredStartupHandler.addDeferredTask(new Runnable() { - @Override - public void run() { SigninHelperProvider.get().onMainActivityStart(); RevenueStats.getInstance(); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninChecker.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninChecker.java index cc74662..2a579b0 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninChecker.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninChecker.java
@@ -6,16 +6,22 @@ import android.accounts.Account; +import androidx.annotation.VisibleForTesting; + import org.chromium.base.ApplicationState; import org.chromium.base.ApplicationStatus; +import org.chromium.base.Log; import org.chromium.base.TraceEvent; import org.chromium.chrome.browser.SyncFirstSetupCompleteSource; import org.chromium.chrome.browser.signin.services.SigninManager; import org.chromium.chrome.browser.signin.services.SigninManager.SignInCallback; import org.chromium.chrome.browser.sync.ProfileSyncService; +import org.chromium.components.signin.AccountManagerFacade; import org.chromium.components.signin.AccountManagerFacadeProvider; import org.chromium.components.signin.AccountRenameChecker; import org.chromium.components.signin.AccountUtils; +import org.chromium.components.signin.ChildAccountStatus; +import org.chromium.components.signin.ChildAccountStatus.Status; import org.chromium.components.signin.base.CoreAccountInfo; import org.chromium.components.signin.identitymanager.AccountTrackerService; import org.chromium.components.signin.identitymanager.ConsentLevel; @@ -29,17 +35,12 @@ */ public class SigninChecker implements ApplicationStatus.ApplicationStateListener, AccountTrackerService.Observer { + private static final String TAG = "SigninChecker"; private final SigninManager mSigninManager; private final AccountTrackerService mAccountTrackerService; - private final SignInCallback mSigninCallback = new SignInCallback() { - @Override - public void onSignInComplete() { - ProfileSyncService.get().setFirstSetupComplete(SyncFirstSetupCompleteSource.BASIC_FLOW); - } - - @Override - public void onSignInAborted() {} - }; + private final AccountManagerFacade mAccountManagerFacade; + // Counter to record the number of child account checks done for tests. + private int mNumOfChildAccountChecksDone; /** * Please use SigninHelperProvider to get {@link SigninChecker} instance instead of creating it @@ -48,15 +49,20 @@ public SigninChecker(SigninManager signinManager, AccountTrackerService accountTrackerService) { mSigninManager = signinManager; mAccountTrackerService = accountTrackerService; + mAccountManagerFacade = AccountManagerFacadeProvider.getInstance(); + mNumOfChildAccountChecksDone = 0; + ApplicationStatus.registerApplicationStateListener(this); mAccountTrackerService.addObserver(this); } private void validateAccountSettings() { - AccountManagerFacadeProvider.getInstance().tryGetGoogleAccounts(accounts -> { + mAccountManagerFacade.tryGetGoogleAccounts(accounts -> { mAccountTrackerService.seedAccountsIfNeeded(() -> { - mSigninManager.runAfterOperationInProgress( - () -> { validatePrimaryAccountExists(accounts); }); + mSigninManager.runAfterOperationInProgress(() -> { + validatePrimaryAccountExists(accounts); + checkChildAccount(accounts); + }); }); }); } @@ -66,11 +72,18 @@ */ @Override public void onAccountsSeeded(List<CoreAccountInfo> accountInfos) { + final List<Account> accounts = AccountUtils.toAndroidAccounts(accountInfos); mSigninManager.runAfterOperationInProgress(() -> { - validatePrimaryAccountExists(AccountUtils.toAndroidAccounts(accountInfos)); + validatePrimaryAccountExists(accounts); + checkChildAccount(accounts); }); } + @VisibleForTesting + public int getNumOfChildAccountChecksDoneForTests() { + return mNumOfChildAccountChecksDone; + } + /** * Validates that the primary account exists on device. */ @@ -92,7 +105,16 @@ mSigninManager.signOut(SignoutReason.USER_CLICKED_SIGNOUT_SETTINGS, () -> { mSigninManager.signinAndEnableSync(SigninAccessPoint.ACCOUNT_RENAMED, AccountUtils.createAccountFromName(newAccountName), - mSigninCallback); + new SignInCallback() { + @Override + public void onSignInComplete() { + ProfileSyncService.get().setFirstSetupComplete( + SyncFirstSetupCompleteSource.BASIC_FLOW); + } + + @Override + public void onSignInAborted() {} + }); }, false); } else { // Sign out if the current primary account is not renamed @@ -101,6 +123,44 @@ }); } + private void checkChildAccount(List<Account> accounts) { + if (accounts.size() == 1) { + // Child accounts can't share a device. + final Account account = accounts.get(0); + mAccountManagerFacade.checkChildAccountStatus( + account, status -> { onChildAccountStatusReady(account, status); }); + } else { + ++mNumOfChildAccountChecksDone; + } + } + + private void onChildAccountStatusReady(Account account, @Status int status) { + if (ChildAccountStatus.isChild(status)) { + mSigninManager.onFirstRunCheckDone(); + if (mSigninManager.isSignInAllowed()) { + Log.d(TAG, "The child account sign-in starts."); + mSigninManager.signinAndEnableSync( + SigninAccessPoint.FORCED_SIGNIN, account, new SignInCallback() { + @Override + public void onSignInComplete() { + final ProfileSyncService profileSyncService = + ProfileSyncService.get(); + if (profileSyncService != null) { + profileSyncService.setFirstSetupComplete( + SyncFirstSetupCompleteSource.BASIC_FLOW); + } + ++mNumOfChildAccountChecksDone; + } + + @Override + public void onSignInAborted() {} + }); + return; + } + } + ++mNumOfChildAccountChecksDone; + } + /** * Called once during initialization and then again for every start (warm-start). * Responsible for checking if configuration has changed since Chrome was last launched
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/AndroidPaymentAppFinderTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/AndroidPaymentAppFinderTest.java index b1f6a93..340c2dc5 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/AndroidPaymentAppFinderTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/AndroidPaymentAppFinderTest.java
@@ -264,39 +264,6 @@ } /** - * Payment apps without default payment method name in metadata should still be able to use - * non-URL payment method names. - */ - @Test - @Feature({"Payments"}) - public void testNoDefaultPaymentMethodNameWithNonUrlPaymentMethodName() throws Throwable { - Set<String> methods = new HashSet<>(); - methods.add("basic-card"); - mPackageManager.installPaymentApp("AlicePay", "com.alicepay", - "" /* no default payment method name in metadata */, /*signature=*/"AA"); - mPackageManager.setStringArrayMetaData("com.alicepay", new String[] {"basic-card"}); - - findApps(methods); - - Assert.assertEquals("1 app should match the query", 1, mPaymentApps.size()); - Assert.assertEquals("com.alicepay", mPaymentApps.get(0).getIdentifier()); - Assert.assertEquals(1, mPaymentApps.get(0).getInstrumentMethodNames().size()); - Assert.assertEquals( - "basic-card", mPaymentApps.get(0).getInstrumentMethodNames().iterator().next()); - - mPaymentApps.clear(); - mAllPaymentAppsCreated = false; - - findApps(methods); - - Assert.assertEquals("1 app should still match the query", 1, mPaymentApps.size()); - Assert.assertEquals("com.alicepay", mPaymentApps.get(0).getIdentifier()); - Assert.assertEquals(1, mPaymentApps.get(0).getInstrumentMethodNames().size()); - Assert.assertEquals( - "basic-card", mPaymentApps.get(0).getInstrumentMethodNames().iterator().next()); - } - - /** * Payment apps cannot use a payment method without explicit authorization. */ @Test @@ -371,27 +338,6 @@ } /** - * Test "basic-card" payment method with a payment app that supports IS_READY_TO_PAY service. - * Another non-payment app also supports IS_READY_TO_PAY service, but it should be filtered - * out, because it's not a payment app. - */ - @Test - @Feature({"Payments"}) - public void testOneBasicCardAppWithAFewIsReadyToPayServices() throws Throwable { - Set<String> methods = new HashSet<>(); - methods.add("basic-card"); - mPackageManager.installPaymentApp( - "BobPay", "com.bobpay", "basic-card", /*signature=*/"01020304050607080900"); - mPackageManager.addIsReadyToPayService("com.bobpay"); - mPackageManager.addIsReadyToPayService("com.alicepay"); - - findApps(methods); - - Assert.assertEquals("1 app should match the query", 1, mPaymentApps.size()); - Assert.assertEquals("com.bobpay", mPaymentApps.get(0).getIdentifier()); - } - - /** * Test BobPay with https://bobpay.com/webpay payment method name, which the payment app * supports through the "default_applications" directive in the * https://bobpay.com/payment-manifest.json file. BobPay has the correct signature that @@ -471,30 +417,6 @@ } /** - * If two payment apps both support "basic-card" payment method name, then they both should be - * found. - */ - @Test - @Feature({"Payments"}) - public void testTwoBasicCardApps() throws Throwable { - Set<String> methods = new HashSet<>(); - methods.add("basic-card"); - mPackageManager.installPaymentApp( - "BobPay", "com.bobpay", "basic-card", /*signature=*/"01020304050607080900"); - mPackageManager.installPaymentApp( - "AlicePay", "com.alicepay", "basic-card", /*signature=*/"ABCDEFABCDEFABCDEFAB"); - - findApps(methods); - - Assert.assertEquals("2 apps should match the query", 2, mPaymentApps.size()); - Set<String> appIdentifiers = new HashSet<>(); - appIdentifiers.add(mPaymentApps.get(0).getIdentifier()); - appIdentifiers.add(mPaymentApps.get(1).getIdentifier()); - Assert.assertTrue(appIdentifiers.contains("com.bobpay")); - Assert.assertTrue(appIdentifiers.contains("com.alicepay")); - } - - /** * Test https://davepay.com/webpay payment method, the "default_applications" of which * supports two different package names: one for production and one for development version * of the payment app. Both of these apps should be found. Repeated lookups should continue @@ -1426,12 +1348,10 @@ assertPaymentAppsCreated("com.alicepay", "com.bobpay"); } - /** - * All known payment method names are valid. - */ + /** Non-URL payment methods are not supported. */ @Test @Feature({"Payments"}) - public void testAllKnownPaymentMethodNames() throws Throwable { + public void testNonUrlPaymentMethodNames() throws Throwable { Set<String> methods = new HashSet<>(); methods.add("basic-card"); methods.add("interledger"); @@ -1447,33 +1367,7 @@ findApps(methods); - Assert.assertEquals("1 app should match the query", 1, mPaymentApps.size()); - Assert.assertEquals("com.alicepay", mPaymentApps.get(0).getIdentifier()); - Assert.assertEquals(5, mPaymentApps.get(0).getInstrumentMethodNames().size()); - Assert.assertTrue(mPaymentApps.get(0).getInstrumentMethodNames().contains("basic-card")); - Assert.assertTrue(mPaymentApps.get(0).getInstrumentMethodNames().contains("interledger")); - Assert.assertTrue( - mPaymentApps.get(0).getInstrumentMethodNames().contains("payee-credit-transfer")); - Assert.assertTrue( - mPaymentApps.get(0).getInstrumentMethodNames().contains("payer-credit-transfer")); - Assert.assertTrue( - mPaymentApps.get(0).getInstrumentMethodNames().contains("tokenized-card")); - - mPaymentApps.clear(); - mAllPaymentAppsCreated = false; - - findApps(methods); - - assertPaymentAppsCreated("com.alicepay"); - Assert.assertEquals(5, mPaymentApps.get(0).getInstrumentMethodNames().size()); - Assert.assertTrue(mPaymentApps.get(0).getInstrumentMethodNames().contains("basic-card")); - Assert.assertTrue(mPaymentApps.get(0).getInstrumentMethodNames().contains("interledger")); - Assert.assertTrue( - mPaymentApps.get(0).getInstrumentMethodNames().contains("payee-credit-transfer")); - Assert.assertTrue( - mPaymentApps.get(0).getInstrumentMethodNames().contains("payer-credit-transfer")); - Assert.assertTrue( - mPaymentApps.get(0).getInstrumentMethodNames().contains("tokenized-card")); + Assert.assertTrue(mPaymentApps.isEmpty()); } /**
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/AndroidPaymentAppFinderUnitTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/AndroidPaymentAppFinderUnitTest.java index db68c3b..730246d 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/AndroidPaymentAppFinderUnitTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/AndroidPaymentAppFinderUnitTest.java
@@ -310,67 +310,6 @@ @SmallTest @Test @UiThreadTest - public void testQueryBasicCardsWithTwoApps() { - List<ResolveInfo> activities = new ArrayList<>(); - ResolveInfo alicePay = new ResolveInfo(); - alicePay.activityInfo = new ActivityInfo(); - alicePay.activityInfo.packageName = "com.alicepay.app"; - alicePay.activityInfo.name = "com.alicepay.app.WebPaymentActivity"; - alicePay.activityInfo.applicationInfo = new ApplicationInfo(); - Bundle alicePayMetaData = new Bundle(); - alicePayMetaData.putString( - AndroidPaymentAppFinder.META_DATA_NAME_OF_DEFAULT_PAYMENT_METHOD_NAME, - "basic-card"); - alicePayMetaData.putInt(AndroidPaymentAppFinder.META_DATA_NAME_OF_PAYMENT_METHOD_NAMES, 1); - alicePay.activityInfo.metaData = alicePayMetaData; - activities.add(alicePay); - - ResolveInfo bobPay = new ResolveInfo(); - bobPay.activityInfo = new ActivityInfo(); - bobPay.activityInfo.packageName = "com.bobpay.app"; - bobPay.activityInfo.name = "com.bobpay.app.WebPaymentActivity"; - bobPay.activityInfo.applicationInfo = new ApplicationInfo(); - Bundle bobPayMetaData = new Bundle(); - bobPayMetaData.putString( - AndroidPaymentAppFinder.META_DATA_NAME_OF_DEFAULT_PAYMENT_METHOD_NAME, - "basic-card"); - bobPayMetaData.putInt(AndroidPaymentAppFinder.META_DATA_NAME_OF_PAYMENT_METHOD_NAMES, 2); - bobPay.activityInfo.metaData = bobPayMetaData; - activities.add(bobPay); - - Mockito.when(mPackageManagerDelegate.getAppLabel(Mockito.any(ResolveInfo.class))) - .thenReturn("A non-empty label"); - Mockito.when(mPackageManagerDelegate.getActivitiesThatCanRespondToIntentWithMetaData( - ArgumentMatchers.argThat(sPayIntentArgumentMatcher))) - .thenReturn(activities); - Mockito.when(mPackageManagerDelegate.getServicesThatCanRespondToIntent( - ArgumentMatchers.argThat(new IntentArgumentMatcher( - new Intent(AndroidPaymentAppFinder.ACTION_IS_READY_TO_PAY))))) - .thenReturn(new ArrayList<ResolveInfo>()); - - Mockito.when(mPackageManagerDelegate.getStringArrayResourceForApplication( - ArgumentMatchers.eq(alicePay.activityInfo.applicationInfo), - ArgumentMatchers.eq(1))) - .thenReturn(new String[] {"https://alicepay.com"}); - Mockito.when(mPackageManagerDelegate.getStringArrayResourceForApplication( - ArgumentMatchers.eq(bobPay.activityInfo.applicationInfo), - ArgumentMatchers.eq(2))) - .thenReturn(new String[] {"https://bobpay.com"}); - - PaymentAppFactoryDelegate delegate = findApps(new String[] {"basic-card"}, - mPaymentManifestDownloader, mPaymentManifestParser, mPackageManagerDelegate); - - Mockito.verify(delegate).onCanMakePaymentCalculated(true); - Mockito.verify(delegate).onPaymentAppCreated( - ArgumentMatchers.argThat(Matches.paymentAppIdentifier("com.alicepay.app"))); - Mockito.verify(delegate).onPaymentAppCreated( - ArgumentMatchers.argThat(Matches.paymentAppIdentifier("com.bobpay.app"))); - Mockito.verify(delegate).onDoneCreatingPaymentApps(/*factory=*/null); - } - - @SmallTest - @Test - @UiThreadTest public void testQueryBobPayWithOneAppThatHasIsReadyToPayService() { List<ResolveInfo> activities = new ArrayList<>(); ResolveInfo bobPay = new ResolveInfo();
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/ExpandablePaymentHandlerChangePaymentMethodTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/ExpandablePaymentHandlerChangePaymentMethodTest.java deleted file mode 100644 index a14441e..0000000 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/ExpandablePaymentHandlerChangePaymentMethodTest.java +++ /dev/null
@@ -1,197 +0,0 @@ -// Copyright 2020 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. - -package org.chromium.chrome.browser.payments; - -import android.support.test.InstrumentationRegistry; - -import androidx.test.filters.MediumTest; - -import org.junit.After; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.chromium.base.test.util.CommandLineFlags; -import org.chromium.base.test.util.Feature; -import org.chromium.chrome.R; -import org.chromium.chrome.browser.flags.ChromeSwitches; -import org.chromium.chrome.test.ChromeJUnit4ClassRunner; -import org.chromium.net.test.EmbeddedTestServer; -import org.chromium.net.test.ServerCertificate; -import org.chromium.ui.test.util.DisableAnimationsTestRule; - -/** An integration test for PaymentRequestEvent.changePaymentMethod(). */ -@RunWith(ChromeJUnit4ClassRunner.class) -@CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE, - "enable-blink-features=PaymentMethodChangeEvent,PaymentHandlerChangePaymentMethod"}) -@MediumTest -public class ExpandablePaymentHandlerChangePaymentMethodTest { - // Disable animations to reduce flakiness. - @ClassRule - public static DisableAnimationsTestRule sNoAnimationsRule = new DisableAnimationsTestRule(); - - // Open a tab on the blank page first to initiate the native bindings required by the test - // server. - @Rule - public PaymentRequestTestRule mRule = new PaymentRequestTestRule("about:blank", null, true); - - // Host the tests on https://127.0.0.1, because file:// URLs cannot have service workers. - private EmbeddedTestServer mServer; - - @Before - public void setUp() throws Throwable { - mServer = EmbeddedTestServer.createAndStartHTTPSServer( - InstrumentationRegistry.getContext(), ServerCertificate.CERT_OK); - mRule.startMainActivityWithURL( - mServer.getURL("/components/test/data/payments/change_payment_method.html")); - - // Find the web contents where JavaScript will be executed and instrument the browser - // payment sheet. - mRule.openPage(); - } - - private void installPaymentHandler() throws Throwable { - mRule.runJavaScriptCodeInCurrentTab("install();"); - mRule.expectResultContains(new String[] {"instruments.set(): Payment handler installed."}); - } - - @After - public void tearDown() { - mServer.stopAndDestroyServer(); - } - - /** - * Verify that absence of the "paymentmethodchange" event handler in the merchant will cause - * PaymentRequestEvent.changePaymentMethod() to resolve with null. - */ - @Test - @Feature({"Payments"}) - public void testNoEventHandler() throws Throwable { - installPaymentHandler(); - mRule.clickNodeAndWait("testNoHandler", mRule.getDismissed()); - mRule.expectResultContains( - new String[] {"PaymentRequest.show(): changePaymentMethod() returned: null"}); - } - - /** - * Verify that absence of the "paymentmethodchange" event handler in the merchant will cause - * PaymentRequestEvent.changePaymentMethod() to resolve with null. - */ - @Test - @Feature({"Payments"}) - public void testNoEventHandlerBasicCard() throws Throwable { - mRule.clickNode("basicCardMethodName"); - installPaymentHandler(); - mRule.triggerUIAndWait("testNoHandler", mRule.getReadyToPay()); - mRule.clickAndWait(R.id.button_primary, mRule.getDismissed()); - mRule.expectResultContains( - new String[] {"PaymentRequest.show(): changePaymentMethod() returned: null"}); - } - - /** - * Verify that rejecting the promise passed into PaymentMethodChangeEvent.updateWith() will - * cause PaymentRequest.show() to reject and thus abort the transaction. - */ - @Test - @Feature({"Payments"}) - public void testReject() throws Throwable { - installPaymentHandler(); - mRule.clickNodeAndWait("testReject", mRule.getDismissed()); - mRule.expectResultContains( - new String[] {"PaymentRequest.show() rejected with: Error for test"}); - } - - /** - * Verify that rejecting the promise passed into PaymentMethodChangeEvent.updateWith() will - * cause PaymentRequest.show() to reject and thus abort the transaction. - */ - @Test - @Feature({"Payments"}) - public void testRejectBasicCard() throws Throwable { - mRule.clickNode("basicCardMethodName"); - installPaymentHandler(); - mRule.triggerUIAndWait("testReject", mRule.getReadyToPay()); - mRule.clickAndWait(R.id.button_primary, mRule.getDismissed()); - mRule.expectResultContains( - new String[] {"PaymentRequest.show() rejected with: Error for test"}); - } - - /** - * Verify that a JavaScript exception in the "paymentmethodchange" event handler will cause - * PaymentRequest.show() to reject and thus abort the transaction. - */ - @Test - @Feature({"Payments"}) - public void testThrow() throws Throwable { - installPaymentHandler(); - mRule.clickNodeAndWait("testThrow", mRule.getDismissed()); - mRule.expectResultContains( - new String[] {"PaymentRequest.show() rejected with: Error: Error for test"}); - } - - /** - * Verify that a JavaScript exception in the "paymentmethodchange" event handler will cause - * PaymentRequest.show() to reject and thus abort the transaction. - */ - @Test - @Feature({"Payments"}) - public void testThrowBasicCard() throws Throwable { - mRule.clickNode("basicCardMethodName"); - installPaymentHandler(); - mRule.triggerUIAndWait("testThrow", mRule.getReadyToPay()); - mRule.clickAndWait(R.id.button_primary, mRule.getDismissed()); - mRule.expectResultContains( - new String[] {"PaymentRequest.show() rejected with: Error: Error for test"}); - } - - /** - * Verify that the payment handler receives a subset of the payment details passed into - * PaymentMethodChangeEvent.updateWith() with URL-based payment method identifier. - */ - @Test - @Feature({"Payments"}) - public void testDetails() throws Throwable { - installPaymentHandler(); - mRule.clickNodeAndWait("testDetails", mRule.getDismissed()); - // Look for the this exact return value to ensure that the browser redacts some details - // before forwarding them to the payment handler. - mRule.expectResultContains( - new String[] {"PaymentRequest.show(): changePaymentMethod() returned: " - + "{\"error\":\"Error for test\",\"modifiers\":" - + "[{\"data\":{\"soup\":\"potato\"}," - + "\"supportedMethods\":\"https://127.0.0.1:", - // Port changes every time, so don't hardcode it here. - "/pay\",\"total\":{\"amount\":{\"currency\":\"EUR\",\"value\":\"0.03\"}," - + "\"label\":\"\",\"pending\":false}}]," - + "\"paymentMethodErrors\":{\"country\":\"Unsupported country\"}," - + "\"total\":{\"currency\":\"GBP\",\"value\":\"0.02\"}}"}); - } - - /** - * Verify that the payment handler receives a subset of the payment details passed into - * PaymentMethodChangeEvent.updateWith() when basic-card payment method is used. - */ - @Test - @Feature({"Payments"}) - public void testDetailsBasicCard() throws Throwable { - mRule.clickNode("basicCardMethodName"); - installPaymentHandler(); - mRule.triggerUIAndWait("testDetails", mRule.getReadyToPay()); - mRule.clickAndWait(R.id.button_primary, mRule.getDismissed()); - // Look for the this exact return value to ensure that the browser redacts some details - // before forwarding them to the payment handler. - mRule.expectResultContains( - new String[] {"PaymentRequest.show(): changePaymentMethod() returned: " - + "{\"error\":\"Error for test\",\"modifiers\":" - + "[{\"data\":{\"soup\":\"potato\"}," - + "\"supportedMethods\":\"basic-card\"," - + "\"total\":{\"amount\":{\"currency\":\"EUR\",\"value\":\"0.03\"}," - + "\"label\":\"\",\"pending\":false}}]," - + "\"paymentMethodErrors\":{\"country\":\"Unsupported country\"}," - + "\"total\":{\"currency\":\"GBP\",\"value\":\"0.02\"}}"}); - } -}
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentHandlerChangePaymentMethodTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentHandlerChangePaymentMethodTest.java index bf9376d..1333f34e 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentHandlerChangePaymentMethodTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentHandlerChangePaymentMethodTest.java
@@ -17,9 +17,7 @@ import org.chromium.base.test.util.CommandLineFlags; import org.chromium.base.test.util.DisableIf; -import org.chromium.base.test.util.DisabledTest; import org.chromium.base.test.util.Feature; -import org.chromium.chrome.R; import org.chromium.chrome.browser.flags.ChromeSwitches; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; import org.chromium.net.test.EmbeddedTestServer; @@ -81,21 +79,6 @@ } /** - * Verify that absence of the "paymentmethodchange" event handler in the merchant will cause - * PaymentRequestEvent.changePaymentMethod() to resolve with null. - */ - @Test - @Feature({"Payments"}) - public void testNoEventHandlerBasicCard() throws Throwable { - mRule.clickNode("basicCardMethodName"); - installPaymentHandler(); - mRule.triggerUIAndWait("testNoHandler", mRule.getReadyToPay()); - mRule.clickAndWait(R.id.button_primary, mRule.getDismissed()); - mRule.expectResultContains( - new String[] {"PaymentRequest.show(): changePaymentMethod() returned: null"}); - } - - /** * Verify that rejecting the promise passed into PaymentMethodChangeEvent.updateWith() will * cause PaymentRequest.show() to reject and thus abort the transaction. */ @@ -110,22 +93,6 @@ } /** - * Verify that rejecting the promise passed into PaymentMethodChangeEvent.updateWith() will - * cause PaymentRequest.show() to reject and thus abort the transaction. - */ - @Test - @Feature({"Payments"}) - @DisableIf.Device(type = {UiDisableIf.TABLET}) // See https://crbug.com/1136100. - public void testRejectBasicCard() throws Throwable { - mRule.clickNode("basicCardMethodName"); - installPaymentHandler(); - mRule.triggerUIAndWait("testReject", mRule.getReadyToPay()); - mRule.clickAndWait(R.id.button_primary, mRule.getDismissed()); - mRule.expectResultContains( - new String[] {"PaymentRequest.show() rejected with: Error for test"}); - } - - /** * Verify that a JavaScript exception in the "paymentmethodchange" event handler will cause * PaymentRequest.show() to reject and thus abort the transaction. */ @@ -139,21 +106,6 @@ } /** - * Verify that a JavaScript exception in the "paymentmethodchange" event handler will cause - * PaymentRequest.show() to reject and thus abort the transaction. - */ - @Test - @Feature({"Payments"}) - public void testThrowBasicCard() throws Throwable { - mRule.clickNode("basicCardMethodName"); - installPaymentHandler(); - mRule.triggerUIAndWait("testThrow", mRule.getReadyToPay()); - mRule.clickAndWait(R.id.button_primary, mRule.getDismissed()); - mRule.expectResultContains( - new String[] {"PaymentRequest.show() rejected with: Error: Error for test"}); - } - - /** * Verify that the payment handler receives a subset of the payment details passed into * PaymentMethodChangeEvent.updateWith() with URL-based payment method identifier. */ @@ -176,29 +128,4 @@ + "\"paymentMethodErrors\":{\"country\":\"Unsupported country\"}," + "\"total\":{\"currency\":\"GBP\",\"value\":\"0.02\"}}"}); } - - /** - * Verify that the payment handler receives a subset of the payment details passed into - * PaymentMethodChangeEvent.updateWith() when basic-card payment method is used. - */ - @Test - @Feature({"Payments"}) - @DisabledTest(message = "crbug.com/1131674") - public void testDetailsBasicCard() throws Throwable { - mRule.clickNode("basicCardMethodName"); - installPaymentHandler(); - mRule.triggerUIAndWait("testDetails", mRule.getReadyToPay()); - mRule.clickAndWait(R.id.button_primary, mRule.getDismissed()); - // Look for the this exact return value to ensure that the browser redacts some details - // before forwarding them to the payment handler. - mRule.expectResultContains( - new String[] {"PaymentRequest.show(): changePaymentMethod() returned: " - + "{\"error\":\"Error for test\",\"modifiers\":" - + "[{\"data\":{\"soup\":\"potato\"}," - + "\"supportedMethods\":\"basic-card\"," - + "\"total\":{\"amount\":{\"currency\":\"EUR\",\"value\":\"0.03\"}," - + "\"label\":\"\",\"pending\":false}}]," - + "\"paymentMethodErrors\":{\"country\":\"Unsupported country\"}," - + "\"total\":{\"currency\":\"GBP\",\"value\":\"0.02\"}}"}); - } }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestShowPromiseDigitalGoodsTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestShowPromiseDigitalGoodsTest.java index 883c2fc..449fb79b 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestShowPromiseDigitalGoodsTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestShowPromiseDigitalGoodsTest.java
@@ -54,7 +54,7 @@ public void testDigitalGoodsFastApp() throws TimeoutException { mRule.addPaymentAppFactory("basic-card", AppPresence.HAVE_APPS, FactorySpeed.FAST_FACTORY); mRule.openPage(); - mRule.executeJavaScriptAndWaitForResult("create();"); + mRule.executeJavaScriptAndWaitForResult("create('basic-card');"); mRule.triggerUIAndWait(mRule.getReadyToPay()); Assert.assertEquals("USD $1.00", mRule.getOrderSummaryTotal()); @@ -77,7 +77,7 @@ mRule.addPaymentAppFactory( "basic-card", AppPresence.HAVE_APPS, FactorySpeed.SLOW_FACTORY, AppSpeed.SLOW_APP); mRule.openPage(); - mRule.executeJavaScriptAndWaitForResult("create();"); + mRule.executeJavaScriptAndWaitForResult("create('basic-card');"); mRule.triggerUIAndWait(mRule.getReadyToPay()); Assert.assertEquals("USD $1.00", mRule.getOrderSummaryTotal()); @@ -99,7 +99,7 @@ public void testSkipUIFastApp() throws TimeoutException { mRule.addPaymentAppFactory("basic-card", AppPresence.HAVE_APPS, FactorySpeed.FAST_FACTORY); mRule.openPage(); - mRule.executeJavaScriptAndWaitForResult("create();"); + mRule.executeJavaScriptAndWaitForResult("create('basic-card');"); mRule.enableSkipUIForBasicCard(); mRule.openPageAndClickNodeAndWait("buy", mRule.getDismissed()); @@ -114,7 +114,7 @@ mRule.addPaymentAppFactory( "basic-card", AppPresence.HAVE_APPS, FactorySpeed.SLOW_FACTORY, AppSpeed.SLOW_APP); mRule.openPage(); - mRule.executeJavaScriptAndWaitForResult("create();"); + mRule.executeJavaScriptAndWaitForResult("create('basic-card');"); mRule.enableSkipUIForBasicCard(); mRule.openPageAndClickNodeAndWait("buy", mRule.getDismissed());
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/signin/SigninCheckerTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/signin/SigninCheckerTest.java new file mode 100644 index 0000000..c780ad32 --- /dev/null +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/signin/SigninCheckerTest.java
@@ -0,0 +1,204 @@ +// Copyright 2021 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. + +package org.chromium.chrome.browser.signin; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +import android.accounts.Account; +import android.os.Build.VERSION_CODES; + +import androidx.test.filters.MediumTest; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnit; +import org.mockito.junit.MockitoRule; +import org.mockito.quality.Strictness; + +import org.chromium.base.test.util.CommandLineFlags; +import org.chromium.base.test.util.CriteriaHelper; +import org.chromium.base.test.util.DisableIf; +import org.chromium.chrome.browser.flags.ChromeFeatureList; +import org.chromium.chrome.browser.flags.ChromeSwitches; +import org.chromium.chrome.browser.profiles.Profile; +import org.chromium.chrome.browser.signin.services.IdentityServicesProvider; +import org.chromium.chrome.test.ChromeJUnit4ClassRunner; +import org.chromium.chrome.test.ChromeTabbedActivityTestRule; +import org.chromium.chrome.test.util.browser.Features; +import org.chromium.chrome.test.util.browser.signin.AccountManagerTestRule; +import org.chromium.components.externalauth.ExternalAuthUtils; +import org.chromium.components.signin.AccountRenameChecker; +import org.chromium.components.signin.ChildAccountStatus; +import org.chromium.components.signin.base.CoreAccountInfo; +import org.chromium.components.signin.test.util.FakeAccountManagerFacade; + +/** + * This class tests the sign-in checks done at Chrome start-up or when accounts + * change on device. + */ +@RunWith(ChromeJUnit4ClassRunner.class) +@CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE}) +@Features.DisableFeatures({ChromeFeatureList.DEPRECATE_MENAGERIE_API}) +@DisableIf.Build(sdk_is_less_than = VERSION_CODES.LOLLIPOP_MR1) +public class SigninCheckerTest { + private static final String CHILD_ACCOUNT_EMAIL = "child.account@gmail.com"; + + @Rule + public final MockitoRule mMockitoRule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS); + + @Rule + public final AccountManagerTestRule mAccountManagerTestRule = + new AccountManagerTestRule(new FakeAccountManagerFacade(null) { + @Override + public void checkChildAccountStatus( + Account account, ChildAccountStatusListener listener) { + listener.onStatusReady(CHILD_ACCOUNT_EMAIL.equals(account.name) + ? ChildAccountStatus.REGULAR_CHILD + : ChildAccountStatus.NOT_CHILD); + } + }); + + @Rule + public final ChromeTabbedActivityTestRule mActivityTestRule = + new ChromeTabbedActivityTestRule(); + + @Mock + private ExternalAuthUtils mExternalAuthUtilsMock; + + @Mock + private AccountRenameChecker.Delegate mAccountRenameCheckerDelegateMock; + + @Before + public void setUp() { + AccountRenameChecker.overrideDelegateForTests(mAccountRenameCheckerDelegateMock); + } + + @Test + @MediumTest + public void signinWhenPrimaryAccountIsRenamedToAKnownAccount() { + mActivityTestRule.startMainActivityOnBlankPage(); + mAccountManagerTestRule.addAccountAndWaitForSeeding("the.second.account@gmail.com"); + final CoreAccountInfo oldAccount = + mAccountManagerTestRule.addTestAccountThenSigninAndEnableSync(); + final String newAccountEmail = "test.new.account@gmail.com"; + when(mAccountRenameCheckerDelegateMock.getNewNameOfRenamedAccount(oldAccount.getEmail())) + .thenReturn(newAccountEmail); + final CoreAccountInfo expectedPrimaryAccount = + mAccountManagerTestRule.addAccount(newAccountEmail); + + mAccountManagerTestRule.removeAccount(oldAccount.getEmail()); + + CriteriaHelper.pollUiThread(() -> { + return expectedPrimaryAccount.equals( + mAccountManagerTestRule.getCurrentSignedInAccount()); + }); + } + + @Test + @MediumTest + public void signoutWhenPrimaryAccountIsRenamedToAnUnknownAccount() { + mActivityTestRule.startMainActivityOnBlankPage(); + mAccountManagerTestRule.addAccountAndWaitForSeeding("the.second.account@gmail.com"); + final CoreAccountInfo oldAccount = + mAccountManagerTestRule.addTestAccountThenSigninAndEnableSync(); + final String newAccountEmail = "test.new.account@gmail.com"; + when(mAccountRenameCheckerDelegateMock.getNewNameOfRenamedAccount(oldAccount.getEmail())) + .thenReturn(newAccountEmail); + + mAccountManagerTestRule.removeAccount(oldAccount.getEmail()); + + CriteriaHelper.pollUiThread(() -> { + return !IdentityServicesProvider.get() + .getIdentityManager(Profile.getLastUsedRegularProfile()) + .hasPrimaryAccount(); + }); + Assert.assertNull(mAccountManagerTestRule.getCurrentSignedInAccount()); + } + + @Test + @MediumTest + public void signoutWhenPrimaryAccountIsRemoved() { + mActivityTestRule.startMainActivityOnBlankPage(); + mAccountManagerTestRule.addAccountAndWaitForSeeding("the.second.account@gmail.com"); + final CoreAccountInfo oldAccount = + mAccountManagerTestRule.addTestAccountThenSigninAndEnableSync(); + + mAccountManagerTestRule.removeAccount(oldAccount.getEmail()); + + CriteriaHelper.pollUiThread(() -> { + return !IdentityServicesProvider.get() + .getIdentityManager(Profile.getLastUsedRegularProfile()) + .hasPrimaryAccount(); + }); + Assert.assertNull(mAccountManagerTestRule.getCurrentSignedInAccount()); + } + + @Test + @MediumTest + public void signinWhenChildAccountIsTheOnlyAccount() { + mActivityTestRule.startMainActivityOnBlankPage(); + + final CoreAccountInfo expectedPrimaryAccount = + mAccountManagerTestRule.addAccountAndWaitForSeeding(CHILD_ACCOUNT_EMAIL); + + CriteriaHelper.pollUiThread(() -> { + return expectedPrimaryAccount.equals( + mAccountManagerTestRule.getCurrentSignedInAccount()); + }); + Assert.assertEquals(2, SigninHelperProvider.get().getNumOfChildAccountChecksDoneForTests()); + } + + @Test + @MediumTest + public void noSigninWhenChildAccountIsTheOnlyAccountButSigninIsNotAllowed() { + mActivityTestRule.startMainActivityOnBlankPage(); + when(mExternalAuthUtilsMock.isGooglePlayServicesMissing(any())).thenReturn(true); + ExternalAuthUtils.setInstanceForTesting(mExternalAuthUtilsMock); + + mAccountManagerTestRule.addAccountAndWaitForSeeding(CHILD_ACCOUNT_EMAIL); + + // The check should be done twice, once at activity start-up, the other when account + // is added. + CriteriaHelper.pollUiThread(() -> { + return SigninHelperProvider.get().getNumOfChildAccountChecksDoneForTests() == 2; + }); + Assert.assertNull(mAccountManagerTestRule.getCurrentSignedInAccount()); + } + + @Test + @MediumTest + public void noSigninWhenChildAccountIsTheSecondaryAccount() { + mAccountManagerTestRule.addAccount("the.default.account@gmail.com"); + mAccountManagerTestRule.addAccount(CHILD_ACCOUNT_EMAIL); + + mActivityTestRule.startMainActivityOnBlankPage(); + + // The check should be done once at activity start-up + CriteriaHelper.pollUiThread(() -> { + return SigninHelperProvider.get().getNumOfChildAccountChecksDoneForTests() == 1; + }); + Assert.assertNull(mAccountManagerTestRule.getCurrentSignedInAccount()); + } + + @Test + @MediumTest + public void noSigninWhenChildAccountIsNotTheOnlyAccount() { + mAccountManagerTestRule.addAccount(CHILD_ACCOUNT_EMAIL); + mAccountManagerTestRule.addAccount("the.second.account@gmail.com"); + + mActivityTestRule.startMainActivityOnBlankPage(); + + // The check should be done once at activity start-up + CriteriaHelper.pollUiThread(() -> { + return SigninHelperProvider.get().getNumOfChildAccountChecksDoneForTests() == 1; + }); + Assert.assertNull(mAccountManagerTestRule.getCurrentSignedInAccount()); + } +}
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/firstrun/ForcedSigninProcessorTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/firstrun/ForcedSigninProcessorTest.java deleted file mode 100644 index 96277c0..0000000 --- a/chrome/android/junit/src/org/chromium/chrome/browser/firstrun/ForcedSigninProcessorTest.java +++ /dev/null
@@ -1,144 +0,0 @@ -// Copyright 2021 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. - -package org.chromium.chrome.browser.firstrun; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.notNull; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import android.accounts.Account; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.robolectric.annotation.Config; - -import org.chromium.base.task.test.CustomShadowAsyncTask; -import org.chromium.base.test.BaseRobolectricTestRunner; -import org.chromium.chrome.browser.SyncFirstSetupCompleteSource; -import org.chromium.chrome.browser.profiles.Profile; -import org.chromium.chrome.browser.signin.services.IdentityServicesProvider; -import org.chromium.chrome.browser.signin.services.SigninManager; -import org.chromium.chrome.browser.signin.services.SigninManager.SignInCallback; -import org.chromium.chrome.browser.sync.ProfileSyncService; -import org.chromium.chrome.test.util.browser.signin.AccountManagerTestRule; -import org.chromium.components.signin.AccountUtils; -import org.chromium.components.signin.ChildAccountStatus; -import org.chromium.components.signin.base.CoreAccountInfo; -import org.chromium.components.signin.identitymanager.IdentityManager; -import org.chromium.components.signin.metrics.SigninAccessPoint; -import org.chromium.components.signin.test.util.FakeAccountManagerFacade; - -/** - * JUnit tests for {@link ForcedSigninProcessor}. - */ -@RunWith(BaseRobolectricTestRunner.class) -@Config(shadows = {CustomShadowAsyncTask.class}) -public class ForcedSigninProcessorTest { - private static final Account CHILD_ACCOUNT = - AccountUtils.createAccountFromName("child.account@gmail.com"); - - private final FakeAccountManagerFacade mFakeFacade = new FakeAccountManagerFacade(null) { - @Override - public void checkChildAccountStatus(Account account, ChildAccountStatusListener listener) { - listener.onStatusReady(account.equals(CHILD_ACCOUNT) ? ChildAccountStatus.REGULAR_CHILD - : ChildAccountStatus.NOT_CHILD); - } - }; - - @Rule - public final MockitoRule mMockitoRule = MockitoJUnit.rule(); - - @Rule - public final AccountManagerTestRule mAccountManagerTestRule = - new AccountManagerTestRule(mFakeFacade); - - @Mock - private Profile mProfileMock; - - @Mock - private ProfileSyncService mProfileSyncServiceMock; - - @Mock - private SigninManager mSigninManagerMock; - - @Mock - private IdentityManager mIdentityManagerMock; - - @Before - public void setUp() { - Profile.setLastUsedProfileForTesting(mProfileMock); - ProfileSyncService.overrideForTests(mProfileSyncServiceMock); - IdentityServicesProvider.setInstanceForTests(mock(IdentityServicesProvider.class)); - - when(IdentityServicesProvider.get().getIdentityManager(mProfileMock)) - .thenReturn(mIdentityManagerMock); - when(mIdentityManagerMock.hasPrimaryAccount()).thenReturn(false); - - when(IdentityServicesProvider.get().getSigninManager(mProfileMock)) - .thenReturn(mSigninManagerMock); - doAnswer(invocation -> { - SignInCallback callback = invocation.getArgument(2); - callback.onSignInComplete(); - return null; - }) - .when(mSigninManagerMock) - .signinAndEnableSync(anyInt(), any(CoreAccountInfo.class), notNull()); - } - - @Test - public void testStartWhenMoreThanOneAccountsOnDevice() { - mAccountManagerTestRule.addAccount(CHILD_ACCOUNT); - mAccountManagerTestRule.addAccount("adult.account@gmail.com"); - - ForcedSigninProcessor.start(); - verify(mSigninManagerMock, never()).onFirstRunCheckDone(); - } - - @Test - public void testStartWhenAdultAccountOnDevice() { - mAccountManagerTestRule.addAccount("adult.account@gmail.com"); - - ForcedSigninProcessor.start(); - verify(mSigninManagerMock, never()).onFirstRunCheckDone(); - } - - @Test - public void testStartWhenSigninNotAllowed() { - mAccountManagerTestRule.addAccount(CHILD_ACCOUNT); - when(mSigninManagerMock.isSignInAllowed()).thenReturn(false); - - ForcedSigninProcessor.start(); - verify(mSigninManagerMock).onFirstRunCheckDone(); - verify(mSigninManagerMock, never()) - .signinAndEnableSync(anyInt(), any(CoreAccountInfo.class), any()); - verify(mProfileSyncServiceMock, never()) - .setFirstSetupComplete(SyncFirstSetupCompleteSource.BASIC_FLOW); - } - - @Test - public void testStartWhenSigninAllowed() { - CoreAccountInfo childAccount = mAccountManagerTestRule.addAccount(CHILD_ACCOUNT); - when(mSigninManagerMock.isSignInAllowed()).thenReturn(true); - - ForcedSigninProcessor.start(); - verify(mSigninManagerMock).onFirstRunCheckDone(); - verify(mSigninManagerMock) - .signinAndEnableSync( - eq(SigninAccessPoint.FORCED_SIGNIN), eq(childAccount), notNull()); - verify(mProfileSyncServiceMock) - .setFirstSetupComplete(SyncFirstSetupCompleteSource.BASIC_FLOW); - } -}
diff --git a/chrome/app/generated_resources.grd b/chrome/app/generated_resources.grd index 175ea9f..51bb4226 100644 --- a/chrome/app/generated_resources.grd +++ b/chrome/app/generated_resources.grd
@@ -5882,6 +5882,9 @@ <message name="IDS_TOOLTIP_CHROMELABS_BUTTON" desc="The tooltip for the Chrome Labs button in the toolbar"> Enable featured experiments </message> + <message name="IDS_TOOLTIP_LEFT_ALIGNED_SIDE_PANEL_BUTTON" desc="The tooltip for the left aligned side panel toggle button"> + Toggle left aligned side panel + </message> <message name="IDS_TOOLTIP_CHROMELABS_COMBOBOX" desc="The tooltip for the Chrome Labs combobox to select between experiment states"> Select experiment state for <ph name="EXPERIMENT_NAME">$1<ex>Tab Scrolling</ex></ph> </message> @@ -6016,6 +6019,9 @@ <message name="IDS_ACCNAME_CHROMELABS_BUTTON" desc="The accessible name for the Chrome Labs experiments button"> Experiments </message> + <message name="IDS_ACCNAME_LEFT_ALIGNED_SIDE_PANEL_BUTTON" desc="The accessible name for the left aligned side panel toggle button"> + Left aligned side panel + </message> <message name="IDS_ACCESSIBLE_TEXT_CHROMELABS_BUTTON_ADDED_BY_ENTERPRISE_POLICY" desc="The text read out by the screen reader when the Chrome Labs experiments button is added to the toolbar by an enterprise policy change."> Enterprise policy changed. Experiments button added to toolbar. Click the button to open a dialog to enable experiments. </message>
diff --git a/chrome/app/generated_resources_grd/IDS_ACCNAME_LEFT_ALIGNED_SIDE_PANEL_BUTTON.png.sha1 b/chrome/app/generated_resources_grd/IDS_ACCNAME_LEFT_ALIGNED_SIDE_PANEL_BUTTON.png.sha1 new file mode 100644 index 0000000..f52ee60 --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_ACCNAME_LEFT_ALIGNED_SIDE_PANEL_BUTTON.png.sha1
@@ -0,0 +1 @@ +18bff324ffbfc47c7b98ec0b11e8643afe9916ce \ No newline at end of file
diff --git a/chrome/app/generated_resources_grd/IDS_TOOLTIP_LEFT_ALIGNED_SIDE_PANEL_BUTTON.png.sha1 b/chrome/app/generated_resources_grd/IDS_TOOLTIP_LEFT_ALIGNED_SIDE_PANEL_BUTTON.png.sha1 new file mode 100644 index 0000000..1d43e4d --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_TOOLTIP_LEFT_ALIGNED_SIDE_PANEL_BUTTON.png.sha1
@@ -0,0 +1 @@ +9e750ab59eac78ddbe5ce91a71f4ed6afc5ec69c \ No newline at end of file
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index c77e67f..9a342647 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -5102,10 +5102,6 @@ #endif // !defined(OS_ANDROID) #if BUILDFLAG(ENABLE_DICE_SUPPORT) - {"use-multilogin-endpoint", flag_descriptions::kUseMultiloginEndpointName, - flag_descriptions::kUseMultiloginEndpointDescription, - kOsMac | kOsWin | kOsLinux, FEATURE_VALUE_TYPE(kUseMultiloginEndpoint)}, - {"enable-new-profile-picker", flag_descriptions::kNewProfilePickerName, flag_descriptions::kNewProfilePickerDescription, kOsMac | kOsWin | kOsLinux,
diff --git a/chrome/browser/app_controller_mac.h b/chrome/browser/app_controller_mac.h index 7a1f530..cf49287 100644 --- a/chrome/browser/app_controller_mac.h +++ b/chrome/browser/app_controller_mac.h
@@ -119,6 +119,11 @@ } @property(readonly, nonatomic) BOOL startupComplete; +@property(readonly, nonatomic) Profile* lastProfileIfLoaded; + +// DEPRECATED: use lastProfileIfLoaded instead. +// TODO(https://crbug.com/1176734): May be blocking, migrate all callers to +// |-lastProfileIfLoaded|. @property(readonly, nonatomic) Profile* lastProfile; // This method is called very early in application startup after the main menu
diff --git a/chrome/browser/app_controller_mac.mm b/chrome/browser/app_controller_mac.mm index 929e6cd..417816a 100644 --- a/chrome/browser/app_controller_mac.mm +++ b/chrome/browser/app_controller_mac.mm
@@ -297,6 +297,18 @@ } } +// Returns the profile path to be used at startup. +base::FilePath GetStartupProfilePathMac(const base::FilePath& user_data_dir) { + // This profile path is used to open URLs passed in application:openFiles: and + // should not default to Guest when the profile picker is shown. + // TODO(https://crbug.com/1155158): Remove the ignore_profile_picker parameter + // once the picker supports opening URLs. + return GetStartupProfilePath(user_data_dir, + /*current_directory=*/base::FilePath(), + *base::CommandLine::ForCurrentProcess(), + /*ignore_profile_picker=*/true); +} + } // namespace // Returns the last profile. This is extracted as a standalone function in order @@ -307,20 +319,11 @@ return nullptr; base::FilePath profile_path = - GetStartupProfilePath(profile_manager->user_data_dir(), - /*current_directory=*/base::FilePath(), - *base::CommandLine::ForCurrentProcess(), - /*ignore_profile_picker=*/true); - + GetStartupProfilePathMac(profile_manager->user_data_dir()); // ProfileManager::GetProfile() is blocking if the profile was not loaded yet. - // TODO(https://1176734): Change this code to return nullptr when the profile - // is not loaded, and update all callers to handle this case. + // TODO(https://crbug.com/1176734): Change this code to return nullptr when + // the profile is not loaded, and update all callers to handle this case. base::ScopedAllowBlocking allow_blocking; - - // lastProfile is used to open URLs passed in application:openFiles: and - // should not default to Guest, even if the profile picker is shown. - // TODO(https://crbug.com/1155158): Remove the ignore_profile_picker parameter - // once the picker supports opening URLs. return profile_manager->GetProfile(profile_path); } @@ -1037,8 +1040,11 @@ // Checks with the TabRestoreService to see if there's anything there to // restore and returns YES if so. - (BOOL)canRestoreTab { + Profile* lastProfile = [self lastProfileIfLoaded]; + if (!lastProfile) + return NO; sessions::TabRestoreService* service = - TabRestoreServiceFactory::GetForProfile([self lastProfile]); + TabRestoreServiceFactory::GetForProfile(lastProfile); return service && !service->entries().empty(); } @@ -1476,8 +1482,8 @@ [app registerServicesMenuSendTypes:types returnTypes:types]; } -// Return null if Chrome is not ready or there is no ProfileManager. -- (Profile*)lastProfile { +// Returns null if the profile is not loaded in memory. +- (Profile*)lastProfileIfLoaded { // Return the profile of the last-used Browser, if available. if (_lastProfile) return _lastProfile; @@ -1485,6 +1491,27 @@ if (![self isProfileReady]) return nullptr; + ProfileManager* profile_manager = g_browser_process->profile_manager(); + if (!profile_manager) + return nullptr; + + // GetProfileByPath() returns nullptr if the profile is not loaded. + return profile_manager->GetProfileByPath( + GetStartupProfilePathMac(profile_manager->user_data_dir())); +} + +// Returns null if Chrome is not ready or there is no ProfileManager. +// DEPRECATED: use lastProfileIfLoaded instead. +// TODO(https://crbug.com/1176734): May be blocking, migrate all callers to +// |-lastProfileIfLoaded|. +- (Profile*)lastProfile { + Profile* lastLoadedProfile = [self lastProfileIfLoaded]; + if (lastLoadedProfile) + return lastLoadedProfile; + + if (![self isProfileReady]) + return nullptr; + return GetLastProfileMac(); }
diff --git a/chrome/browser/banners/android/java/src/org/chromium/chrome/browser/banners/AppBannerManagerTest.java b/chrome/browser/banners/android/java/src/org/chromium/chrome/browser/banners/AppBannerManagerTest.java index 64f0435..b4a8ebe 100644 --- a/chrome/browser/banners/android/java/src/org/chromium/chrome/browser/banners/AppBannerManagerTest.java +++ b/chrome/browser/banners/android/java/src/org/chromium/chrome/browser/banners/AppBannerManagerTest.java
@@ -453,6 +453,7 @@ @Test @SmallTest @Feature({"AppBanners"}) + @CommandLineFlags.Add({"disable-features=" + FeatureConstants.PWA_INSTALL_AVAILABLE_FEATURE}) public void testAppInstalledEventModalWebAppBannerBrowserTab() throws Exception { // Sets the overridden factory to observer splash screen update. final TestDataStorageFactory dataStorageFactory = new TestDataStorageFactory(); @@ -847,8 +848,10 @@ @Test @MediumTest @Feature({"AppBanners"}) - @CommandLineFlags.Add("enable-features=" + ChromeFeatureList.PWA_INSTALL_USE_BOTTOMSHEET) - public void testAppInstalledEventBottomSheet() throws Exception { + @CommandLineFlags.Add({"enable-features=" + ChromeFeatureList.PWA_INSTALL_USE_BOTTOMSHEET, + "disable-features=" + FeatureConstants.PWA_INSTALL_AVAILABLE_FEATURE}) + public void + testAppInstalledEventBottomSheet() throws Exception { triggerBottomSheet(mTabbedActivityTestRule, WebappTestPage.getServiceWorkerUrlWithManifestAndAction(mTestServer, WEB_APP_MANIFEST_FOR_BOTTOM_SHEET_INSTALL,
diff --git a/chrome/browser/chrome_web_platform_security_metrics_browsertest.cc b/chrome/browser/chrome_web_platform_security_metrics_browsertest.cc index f83423f..a153c37 100644 --- a/chrome/browser/chrome_web_platform_security_metrics_browsertest.cc +++ b/chrome/browser/chrome_web_platform_security_metrics_browsertest.cc
@@ -1031,18 +1031,18 @@ "/set-header?" "Cross-Origin-Embedder-Policy: unsafe-none"); EXPECT_TRUE(content::NavigateToURL(web_contents(), url)); - CheckCounter(WebFeature::kCrossOriginEmbedderPolicyCorsOrCredentialless, 0); + CheckCounter(WebFeature::kCrossOriginEmbedderPolicyCredentialless, 0); CheckCounter(WebFeature::kCrossOriginEmbedderPolicyRequireCorp, 0); } IN_PROC_BROWSER_TEST_F(ChromeWebPlatformSecurityMetricsBrowserTest, - CoepCorsOrCredentiallessMainFrame) { - GURL url = https_server().GetURL( - "a.com", - "/set-header?" - "Cross-Origin-Embedder-Policy: cors-or-credentialless"); + CoepCredentiallessMainFrame) { + GURL url = + https_server().GetURL("a.com", + "/set-header?" + "Cross-Origin-Embedder-Policy: credentialless"); EXPECT_TRUE(content::NavigateToURL(web_contents(), url)); - CheckCounter(WebFeature::kCrossOriginEmbedderPolicyCorsOrCredentialless, 1); + CheckCounter(WebFeature::kCrossOriginEmbedderPolicyCredentialless, 1); CheckCounter(WebFeature::kCrossOriginEmbedderPolicyRequireCorp, 0); } @@ -1053,18 +1053,18 @@ "/set-header?" "Cross-Origin-Embedder-Policy: require-corp"); EXPECT_TRUE(content::NavigateToURL(web_contents(), url)); - CheckCounter(WebFeature::kCrossOriginEmbedderPolicyCorsOrCredentialless, 0); + CheckCounter(WebFeature::kCrossOriginEmbedderPolicyCredentialless, 0); CheckCounter(WebFeature::kCrossOriginEmbedderPolicyRequireCorp, 1); } IN_PROC_BROWSER_TEST_F(ChromeWebPlatformSecurityMetricsBrowserTest, - CoepReportOnlyCorsOrCredentiallessMainFrame) { + CoepReportOnlyCredentiallessMainFrame) { GURL url = https_server().GetURL( "a.com", "/set-header?" - "Cross-Origin-Embedder-Policy-Report-Only: cors-or-credentialless"); + "Cross-Origin-Embedder-Policy-Report-Only: credentialless"); EXPECT_TRUE(content::NavigateToURL(web_contents(), url)); - CheckCounter(WebFeature::kCrossOriginEmbedderPolicyCorsOrCredentialless, 0); + CheckCounter(WebFeature::kCrossOriginEmbedderPolicyCredentialless, 0); CheckCounter(WebFeature::kCrossOriginEmbedderPolicyRequireCorp, 0); } @@ -1073,46 +1073,46 @@ GURL url = https_server().GetURL( "a.com", "/set-header?" - "Cross-Origin-Embedder-Policy-Report-Only: cors-or-credentialless"); + "Cross-Origin-Embedder-Policy-Report-Only: credentialless"); EXPECT_TRUE(content::NavigateToURL(web_contents(), url)); - CheckCounter(WebFeature::kCrossOriginEmbedderPolicyCorsOrCredentialless, 0); + CheckCounter(WebFeature::kCrossOriginEmbedderPolicyCredentialless, 0); CheckCounter(WebFeature::kCrossOriginEmbedderPolicyRequireCorp, 0); } IN_PROC_BROWSER_TEST_F(ChromeWebPlatformSecurityMetricsBrowserTest, - CoepRequireCorpEmbedsCorsOrCredentialless) { + CoepRequireCorpEmbedsCredentialless) { GURL main_url = https_server().GetURL("a.com", "/set-header?" "Cross-Origin-Embedder-Policy: require-corp"); EXPECT_TRUE(content::NavigateToURL(web_contents(), main_url)); - CheckCounter(WebFeature::kCrossOriginEmbedderPolicyCorsOrCredentialless, 0); + CheckCounter(WebFeature::kCrossOriginEmbedderPolicyCredentialless, 0); CheckCounter(WebFeature::kCrossOriginEmbedderPolicyRequireCorp, 1); - GURL child_url = https_server().GetURL( - "a.com", - "/set-header?" - "Cross-Origin-Embedder-Policy: cors-or-credentialless"); + GURL child_url = + https_server().GetURL("a.com", + "/set-header?" + "Cross-Origin-Embedder-Policy: credentialless"); LoadIFrame(child_url); EXPECT_TRUE(content::WaitForLoadStop(web_contents())); - CheckCounter(WebFeature::kCrossOriginEmbedderPolicyCorsOrCredentialless, 1); + CheckCounter(WebFeature::kCrossOriginEmbedderPolicyCredentialless, 1); CheckCounter(WebFeature::kCrossOriginEmbedderPolicyRequireCorp, 1); } IN_PROC_BROWSER_TEST_F(ChromeWebPlatformSecurityMetricsBrowserTest, - CoepCorsOrCredentiallessEmbedsRequireCorp) { - GURL main_url = https_server().GetURL( - "a.com", - "/set-header?" - "Cross-Origin-Embedder-Policy: cors-or-credentialless"); + CoepCredentiallessEmbedsRequireCorp) { + GURL main_url = + https_server().GetURL("a.com", + "/set-header?" + "Cross-Origin-Embedder-Policy: credentialless"); EXPECT_TRUE(content::NavigateToURL(web_contents(), main_url)); - CheckCounter(WebFeature::kCrossOriginEmbedderPolicyCorsOrCredentialless, 1); + CheckCounter(WebFeature::kCrossOriginEmbedderPolicyCredentialless, 1); CheckCounter(WebFeature::kCrossOriginEmbedderPolicyRequireCorp, 0); GURL child_url = https_server().GetURL("a.com", "/set-header?" "Cross-Origin-Embedder-Policy: require-corp"); LoadIFrame(child_url); - CheckCounter(WebFeature::kCrossOriginEmbedderPolicyCorsOrCredentialless, 1); + CheckCounter(WebFeature::kCrossOriginEmbedderPolicyCredentialless, 1); CheckCounter(WebFeature::kCrossOriginEmbedderPolicyRequireCorp, 1); }
diff --git a/chrome/browser/chromeos/extensions/device_local_account_management_policy_provider.cc b/chrome/browser/chromeos/extensions/device_local_account_management_policy_provider.cc index 4e0e8d8c..d31a87b 100644 --- a/chrome/browser/chromeos/extensions/device_local_account_management_policy_provider.cc +++ b/chrome/browser/chromeos/extensions/device_local_account_management_policy_provider.cc
@@ -685,10 +685,10 @@ // Try to read as dictionary. const base::DictionaryValue *dict_value; if (entry.GetAsDictionary(&dict_value)) { - if (dict_value->size() != 1) { + if (dict_value->DictSize() != 1) { LOG(ERROR) << extension->id() << " has dict in permission list with size " - << dict_value->size() << "."; + << dict_value->DictSize() << "."; safe = false; continue; }
diff --git a/chrome/browser/chromeos/extensions/external_cache_impl.cc b/chrome/browser/chromeos/extensions/external_cache_impl.cc index ce10233..a54391a 100644 --- a/chrome/browser/chromeos/extensions/external_cache_impl.cc +++ b/chrome/browser/chromeos/extensions/external_cache_impl.cc
@@ -288,7 +288,7 @@ downloader_->StartAllPending(nullptr); VLOG(1) << "Updated ExternalCacheImpl, there are " - << cached_extensions_->size() << " extensions cached"; + << cached_extensions_->DictSize() << " extensions cached"; UpdateExtensionLoader(); }
diff --git a/chrome/browser/chromeos/policy/dlp/dlp_content_manager.cc b/chrome/browser/chromeos/policy/dlp/dlp_content_manager.cc index 969b7c8..a5c71bf 100644 --- a/chrome/browser/chromeos/policy/dlp/dlp_content_manager.cc +++ b/chrome/browser/chromeos/policy/dlp/dlp_content_manager.cc
@@ -39,7 +39,7 @@ base::TimeDelta::FromMilliseconds(500); // Reports events to `reporting_manager`. -void ReportEvent(content::WebContents* web_contents, +void ReportEvent(GURL url, DlpRulesManager::Restriction restriction, DlpRulesManager::Level level, const DlpReportingManager* reporting_manager) { @@ -50,11 +50,10 @@ if (!rules_manager) return; - const std::string src_url = rules_manager->GetSourceUrlPattern( - web_contents->GetLastCommittedURL(), restriction, level); + const std::string src_url = + rules_manager->GetSourceUrlPattern(url, restriction, level); - if (restriction == DlpRulesManager::Restriction::kPrinting) - reporting_manager->ReportPrintingEvent(src_url, level); + reporting_manager->ReportEvent(src_url, restriction, level); } } // namespace @@ -89,22 +88,36 @@ bool DlpContentManager::IsScreenshotRestricted( const ScreenshotArea& area) const { - const bool restricted = - IsAreaRestricted(area, DlpContentRestriction::kScreenshot); - if (restricted) + RestrictionLevelAndUrl restriction_info = + GetAreaRestrictionInfo(area, DlpContentRestriction::kScreenshot); + const bool is_blocked = + restriction_info.level == DlpRulesManager::Level::kBlock; + if (is_blocked || restriction_info.level == DlpRulesManager::Level::kReport) { SYSLOG(INFO) << "DLP blocked taking a screenshot"; - DlpBooleanHistogram(dlp::kScreenshotBlockedUMA, restricted); - return restricted; + if (reporting_manager_) + ReportEvent(restriction_info.url, + DlpRulesManager::Restriction::kScreenshot, + restriction_info.level, reporting_manager_); + } + DlpBooleanHistogram(dlp::kScreenshotBlockedUMA, is_blocked); + return is_blocked; } bool DlpContentManager::IsVideoCaptureRestricted( const ScreenshotArea& area) const { - const bool restricted = - IsAreaRestricted(area, DlpContentRestriction::kVideoCapture); - if (restricted) + RestrictionLevelAndUrl restriction_info = + GetAreaRestrictionInfo(area, DlpContentRestriction::kVideoCapture); + const bool is_blocked = + restriction_info.level == DlpRulesManager::Level::kBlock; + if (is_blocked || restriction_info.level == DlpRulesManager::Level::kReport) { SYSLOG(INFO) << "DLP blocked taking a video capture"; - DlpBooleanHistogram(dlp::kVideoCaptureBlockedUMA, restricted); - return restricted; + if (reporting_manager_) + ReportEvent(restriction_info.url, + DlpRulesManager::Restriction::kScreenshot, + restriction_info.level, reporting_manager_); + } + DlpBooleanHistogram(dlp::kVideoCaptureBlockedUMA, is_blocked); + return is_blocked; } bool DlpContentManager::IsPrintingRestricted( @@ -116,70 +129,37 @@ web_contents = guest_view ? guest_view->embedder_web_contents() : web_contents; - const DlpRulesManager::Level level = + RestrictionLevelAndUrl restriction_info = GetConfidentialRestrictions(web_contents) - .GetRestriction(DlpContentRestriction::kPrint); - DlpBooleanHistogram(dlp::kPrintingBlockedUMA, - level == DlpRulesManager::Level::kBlock); - if (level == DlpRulesManager::Level::kBlock || - level == DlpRulesManager::Level::kReport) { + .GetRestrictionLevelAndUrl(DlpContentRestriction::kPrint); + const bool is_blocked = + restriction_info.level == DlpRulesManager::Level::kBlock; + DlpBooleanHistogram(dlp::kPrintingBlockedUMA, is_blocked); + if (is_blocked || restriction_info.level == DlpRulesManager::Level::kReport) { SYSLOG(INFO) << "DLP blocked printing"; if (reporting_manager_) - ReportEvent(web_contents, DlpRulesManager::Restriction::kPrinting, level, - reporting_manager_); + ReportEvent(restriction_info.url, DlpRulesManager::Restriction::kPrinting, + restriction_info.level, reporting_manager_); } - return level == DlpRulesManager::Level::kBlock; + return is_blocked; } bool DlpContentManager::IsScreenCaptureRestricted( const content::DesktopMediaID& media_id) const { - if (media_id.type == content::DesktopMediaID::Type::TYPE_SCREEN) { - const bool restricted = GetOnScreenPresentRestrictions().GetRestriction( - DlpContentRestriction::kScreenShare) == - DlpRulesManager::Level::kBlock; - if (restricted) - SYSLOG(INFO) << "DLP blocked screen sharing"; - DlpBooleanHistogram(dlp::kScreenShareBlockedUMA, restricted); - return restricted; + RestrictionLevelAndUrl restriction_info = + GetScreenCaptureRestrictionInfo(media_id); + const bool is_blocked = + restriction_info.level == DlpRulesManager::Level::kBlock; + if (is_blocked || restriction_info.level == DlpRulesManager::Level::kReport) { + SYSLOG(INFO) << "DLP blocked screen sharing"; + if (reporting_manager_) + ReportEvent(restriction_info.url, + DlpRulesManager::Restriction::kScreenShare, + restriction_info.level, reporting_manager_); } - - content::WebContents* web_contents = - content::WebContents::FromRenderFrameHost( - content::RenderFrameHost::FromID( - media_id.web_contents_id.render_process_id, - media_id.web_contents_id.main_render_frame_id)); - - if (media_id.type == content::DesktopMediaID::Type::TYPE_WEB_CONTENTS) { - const bool restricted = - GetConfidentialRestrictions(web_contents) - .GetRestriction(DlpContentRestriction::kScreenShare) == - DlpRulesManager::Level::kBlock; - if (restricted) - SYSLOG(INFO) << "DLP blocked screen sharing"; - DlpBooleanHistogram(dlp::kScreenShareBlockedUMA, restricted); - return restricted; - } - - DCHECK_EQ(media_id.type, content::DesktopMediaID::Type::TYPE_WINDOW); - aura::Window* window = content::DesktopMediaID::GetNativeWindowById(media_id); - if (!window) { - DlpBooleanHistogram(dlp::kScreenShareBlockedUMA, false); - return false; - } - for (auto& entry : confidential_web_contents_) { - aura::Window* web_contents_window = entry.first->GetNativeView(); - if (entry.second.GetRestriction(DlpContentRestriction::kScreenShare) == - DlpRulesManager::Level::kBlock && - window->Contains(web_contents_window)) { - SYSLOG(INFO) << "DLP blocked screen sharing"; - DlpBooleanHistogram(dlp::kScreenShareBlockedUMA, true); - return true; - } - } - - DlpBooleanHistogram(dlp::kScreenShareBlockedUMA, false); - return false; + DlpBooleanHistogram(dlp::kScreenShareBlockedUMA, is_blocked); + return is_blocked; } void DlpContentManager::OnVideoCaptureStarted(const ScreenshotArea& area) { @@ -197,16 +177,27 @@ } bool DlpContentManager::IsCaptureModeInitRestricted() const { - const bool restricted = GetOnScreenPresentRestrictions().GetRestriction( - DlpContentRestriction::kScreenshot) == - DlpRulesManager::Level::kBlock || - GetOnScreenPresentRestrictions().GetRestriction( - DlpContentRestriction::kVideoCapture) == - DlpRulesManager::Level::kBlock; - if (restricted) + RestrictionLevelAndUrl screenshot_restriction_info = + GetOnScreenPresentRestrictions().GetRestrictionLevelAndUrl( + DlpContentRestriction::kScreenshot); + RestrictionLevelAndUrl videocapture_restriction_info = + GetOnScreenPresentRestrictions().GetRestrictionLevelAndUrl( + DlpContentRestriction::kVideoCapture); + RestrictionLevelAndUrl restriction_info = + screenshot_restriction_info.level >= videocapture_restriction_info.level + ? screenshot_restriction_info + : videocapture_restriction_info; + const bool is_blocked = + restriction_info.level == DlpRulesManager::Level::kBlock; + if (is_blocked || restriction_info.level == DlpRulesManager::Level::kReport) { SYSLOG(INFO) << "DLP blocked taking a screen capture"; - DlpBooleanHistogram(dlp::kCaptureModeInitBlockedUMA, restricted); - return restricted; + if (reporting_manager_) + ReportEvent(restriction_info.url, + DlpRulesManager::Restriction::kScreenshot, + restriction_info.level, reporting_manager_); + } + DlpBooleanHistogram(dlp::kCaptureModeInitBlockedUMA, is_blocked); + return is_blocked; } void DlpContentManager::OnScreenCaptureStarted( @@ -341,7 +332,7 @@ if (level == DlpRulesManager::Level::kNotSet || level == DlpRulesManager::Level::kAllow) continue; - set.SetRestriction(restriction.second, level); + set.SetRestriction(restriction.second, level, url); } return set; @@ -381,21 +372,29 @@ void DlpContentManager::OnScreenRestrictionsChanged( const DlpContentRestrictionSet& added_restrictions, const DlpContentRestrictionSet& removed_restrictions) const { - DCHECK(!(added_restrictions.GetRestriction( + DCHECK(!(added_restrictions.GetRestrictionLevel( DlpContentRestriction::kPrivacyScreen) == DlpRulesManager::Level::kBlock && - removed_restrictions.GetRestriction( + removed_restrictions.GetRestrictionLevel( DlpContentRestriction::kPrivacyScreen) == DlpRulesManager::Level::kBlock)); - if (added_restrictions.GetRestriction( - DlpContentRestriction::kPrivacyScreen) == - DlpRulesManager::Level::kBlock) { + RestrictionLevelAndUrl added_restriction_info = + added_restrictions.GetRestrictionLevelAndUrl( + DlpContentRestriction::kPrivacyScreen); + if (added_restriction_info.level == DlpRulesManager::Level::kBlock) { SYSLOG(INFO) << "DLP enforced privacy screen"; DlpBooleanHistogram(dlp::kPrivacyScreenEnforcedUMA, true); ash::PrivacyScreenDlpHelper::Get()->SetEnforced(true); } + if (added_restriction_info.level == DlpRulesManager::Level::kBlock || + added_restriction_info.level == DlpRulesManager::Level::kReport) { + if (reporting_manager_) + ReportEvent(added_restriction_info.url, + DlpRulesManager::Restriction::kPrivacyScreen, + added_restriction_info.level, reporting_manager_); + } - if (removed_restrictions.GetRestriction( + if (removed_restrictions.GetRestrictionLevel( DlpContentRestriction::kPrivacyScreen) == DlpRulesManager::Level::kBlock) { base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( @@ -407,7 +406,7 @@ } void DlpContentManager::MaybeRemovePrivacyScreenEnforcement() const { - if (GetOnScreenPresentRestrictions().GetRestriction( + if (GetOnScreenPresentRestrictions().GetRestrictionLevel( DlpContentRestriction::kPrivacyScreen) != DlpRulesManager::Level::kBlock) { SYSLOG(INFO) << "DLP removed enforcement of privacy screen"; @@ -416,27 +415,28 @@ } } -bool DlpContentManager::IsAreaRestricted( +RestrictionLevelAndUrl DlpContentManager::GetAreaRestrictionInfo( const ScreenshotArea& area, DlpContentRestriction restriction) const { // Fullscreen - restricted if any confidential data is visible. if (area.type == ScreenshotType::kAllRootWindows) { - return GetOnScreenPresentRestrictions().GetRestriction(restriction) == - DlpRulesManager::Level::kBlock; + return GetOnScreenPresentRestrictions().GetRestrictionLevelAndUrl( + restriction); } // Window - restricted if the window contains confidential data. if (area.type == ScreenshotType::kWindow) { DCHECK(area.window); + RestrictionLevelAndUrl restriction_info; for (auto& entry : confidential_web_contents_) { aura::Window* web_contents_window = entry.first->GetNativeView(); - if (entry.second.GetRestriction(restriction) == - DlpRulesManager::Level::kBlock && - area.window->Contains(web_contents_window)) { - return true; + if (area.window->Contains(web_contents_window) && + entry.second.GetRestrictionLevel(restriction) > + restriction_info.level) { + restriction_info = entry.second.GetRestrictionLevelAndUrl(restriction); } } - return false; + return restriction_info; } DCHECK_EQ(area.type, ScreenshotType::kPartialWindow); @@ -444,10 +444,11 @@ DCHECK(area.window); // Partial - restricted if any visible confidential WebContents intersects // with the area. + RestrictionLevelAndUrl restriction_info; for (auto& entry : confidential_web_contents_) { if (entry.first->GetVisibility() != content::Visibility::VISIBLE || - entry.second.GetRestriction(restriction) != - DlpRulesManager::Level::kBlock) { + entry.second.GetRestrictionLevel(restriction) == + DlpRulesManager::Level::kNotSet) { continue; } aura::Window* web_contents_window = entry.first->GetNativeView(); @@ -466,19 +467,55 @@ intersection.Intersect(web_contents_window->GetBoundsInRootWindow()); if (!intersection.IsEmpty() && !web_contents_window->occluded_region_in_root().contains( - gfx::RectToSkIRect(intersection))) { - return true; + gfx::RectToSkIRect(intersection)) && + entry.second.GetRestrictionLevel(restriction) > + restriction_info.level) { + restriction_info = entry.second.GetRestrictionLevelAndUrl(restriction); } } - return false; + return restriction_info; +} + +RestrictionLevelAndUrl DlpContentManager::GetScreenCaptureRestrictionInfo( + const content::DesktopMediaID& media_id) const { + if (media_id.type == content::DesktopMediaID::Type::TYPE_SCREEN) { + return GetOnScreenPresentRestrictions().GetRestrictionLevelAndUrl( + DlpContentRestriction::kScreenShare); + } + if (media_id.type == content::DesktopMediaID::Type::TYPE_WEB_CONTENTS) { + content::WebContents* web_contents = + content::WebContents::FromRenderFrameHost( + content::RenderFrameHost::FromID( + media_id.web_contents_id.render_process_id, + media_id.web_contents_id.main_render_frame_id)); + + return GetConfidentialRestrictions(web_contents) + .GetRestrictionLevelAndUrl(DlpContentRestriction::kScreenShare); + } + DCHECK_EQ(media_id.type, content::DesktopMediaID::Type::TYPE_WINDOW); + RestrictionLevelAndUrl restriction_info; + aura::Window* window = content::DesktopMediaID::GetNativeWindowById(media_id); + if (window) { + for (auto& entry : confidential_web_contents_) { + aura::Window* web_contents_window = entry.first->GetNativeView(); + if (window->Contains(web_contents_window) && + entry.second.GetRestrictionLevel( + DlpContentRestriction::kScreenShare) > restriction_info.level) { + restriction_info = entry.second.GetRestrictionLevelAndUrl( + DlpContentRestriction::kScreenShare); + } + } + } + return restriction_info; } void DlpContentManager::CheckRunningVideoCapture() { if (!running_video_capture_area_.has_value()) return; - if (IsAreaRestricted(*running_video_capture_area_, - DlpContentRestriction::kVideoCapture)) { + RestrictionLevelAndUrl restriction_info = GetAreaRestrictionInfo( + *running_video_capture_area_, DlpContentRestriction::kVideoCapture); + if (restriction_info.level == DlpRulesManager::Level::kBlock) { if (ash::features::IsCaptureModeEnabled()) { SYSLOG(INFO) << "DLP interrupted screen recording"; DlpBooleanHistogram(dlp::kVideoCaptureInterruptedUMA, true); @@ -486,6 +523,13 @@ } running_video_capture_area_.reset(); } + if (restriction_info.level == DlpRulesManager::Level::kBlock || + restriction_info.level == DlpRulesManager::Level::kReport) { + if (reporting_manager_) + ReportEvent(restriction_info.url, + DlpRulesManager::Restriction::kScreenshot, + restriction_info.level, reporting_manager_); + } } void DlpContentManager::MaybeUpdateScreenCaptureNotification() { @@ -521,10 +565,21 @@ void DlpContentManager::CheckRunningScreenCaptures() { for (auto& capture : running_screen_captures_) { - bool is_allowed = !IsScreenCaptureRestricted(capture.media_id); - if (is_allowed != capture.is_running) { + RestrictionLevelAndUrl restriction_info = + GetScreenCaptureRestrictionInfo(capture.media_id); + const bool is_allowed = + restriction_info.level != DlpRulesManager::Level::kBlock; + const bool is_reported = + restriction_info.level == DlpRulesManager::Level::kBlock || + restriction_info.level == DlpRulesManager::Level::kReport; + if (is_reported && capture.is_running) { SYSLOG(INFO) << "DLP " << (is_allowed ? "resumed" : "paused") << " running screen share"; + ReportEvent(restriction_info.url, + DlpRulesManager::Restriction::kScreenShare, + restriction_info.level, reporting_manager_); + } + if (is_allowed != capture.is_running) { DlpBooleanHistogram(dlp::kScreenSharePausedOrResumedUMA, !is_allowed); capture.state_change_callback.Run( capture.media_id, capture.is_running
diff --git a/chrome/browser/chromeos/policy/dlp/dlp_content_manager.h b/chrome/browser/chromeos/policy/dlp/dlp_content_manager.h index f95bbb31..bc0464c 100644 --- a/chrome/browser/chromeos/policy/dlp/dlp_content_manager.h +++ b/chrome/browser/chromeos/policy/dlp/dlp_content_manager.h
@@ -169,9 +169,16 @@ // Removes PrivacyScreen enforcement after delay if it's still not enforced. void MaybeRemovePrivacyScreenEnforcement() const; - // Returns whether |restriction| is currently enforced for |area|. - bool IsAreaRestricted(const ScreenshotArea& area, - DlpContentRestriction restriction) const; + // Returns which level and url of |restriction| that is currently enforced for + // |area|. + RestrictionLevelAndUrl GetAreaRestrictionInfo( + const ScreenshotArea& area, + DlpContentRestriction restriction) const; + + // Returns which level and url of screen capture restriction that is currently + // enforced for |media_id|. + RestrictionLevelAndUrl GetScreenCaptureRestrictionInfo( + const content::DesktopMediaID& media_id) const; // Checks and stops the running video capture if restricted content appeared // in the corresponding areas.
diff --git a/chrome/browser/chromeos/policy/dlp/dlp_content_manager_browsertest.cc b/chrome/browser/chromeos/policy/dlp/dlp_content_manager_browsertest.cc index 36b7f7b..1a3930aa 100644 --- a/chrome/browser/chromeos/policy/dlp/dlp_content_manager_browsertest.cc +++ b/chrome/browser/chromeos/policy/dlp/dlp_content_manager_browsertest.cc
@@ -42,6 +42,8 @@ #include "ui/aura/window.h" #include "ui/gfx/geometry/rect.h" +using testing::_; + namespace policy { namespace { @@ -380,7 +382,7 @@ DlpContentManager* manager = helper_.GetContentManager(); SetupDlpRulesManager(); - EXPECT_CALL(*mock_rules_manager_, GetSourceUrlPattern) + EXPECT_CALL(*mock_rules_manager_, GetSourceUrlPattern(_, _, _)) .Times(2) .WillRepeatedly(testing::Return(src_pattern)); @@ -399,7 +401,7 @@ // Check that IsPrintingRestricted emitted an event. EXPECT_TRUE(manager->IsPrintingRestricted(web_contents)); - EXPECT_EQ(events.size(), 1); + EXPECT_EQ(events.size(), 1u); EXPECT_THAT(events[0], IsDlpPolicyEvent(CreatePrintingRestrictedDlpEvent(src_pattern))); @@ -411,7 +413,7 @@ /*print_only_selection=*/false); EXPECT_TRUE( display_service_tester.GetNotification(kPrintBlockedNotificationId)); - EXPECT_EQ(events.size(), 2); + EXPECT_EQ(events.size(), 2u); EXPECT_THAT(events[1], IsDlpPolicyEvent(CreatePrintingRestrictedDlpEvent(src_pattern))); } @@ -422,7 +424,7 @@ browser()->tab_strip_model()->GetActiveWebContents(); SetupDlpRulesManager(); - EXPECT_CALL(*mock_rules_manager_, GetSourceUrlPattern).Times(0); + EXPECT_CALL(*mock_rules_manager_, GetSourceUrlPattern(_, _, _)).Times(0); std::vector<DlpPolicyEvent> events; SetReportQueueForReportingManager(helper_.GetReportingManager(), events); @@ -516,7 +518,8 @@ DlpContentRestrictionSet screenshot_and_videocapture(kScreenshotRestricted); screenshot_and_videocapture.SetRestriction( - DlpContentRestriction::kVideoCapture, DlpRulesManager::Level::kBlock); + DlpContentRestriction::kVideoCapture, DlpRulesManager::Level::kBlock, + GURL()); EXPECT_EQ(screenshot_and_videocapture, helper_.GetRestrictionSetForURL(GURL(kUrl1))); EXPECT_EQ(kPrivacyScreenEnforced,
diff --git a/chrome/browser/chromeos/policy/dlp/dlp_content_manager_unittest.cc b/chrome/browser/chromeos/policy/dlp/dlp_content_manager_unittest.cc index d7804314..70be5f3 100644 --- a/chrome/browser/chromeos/policy/dlp/dlp_content_manager_unittest.cc +++ b/chrome/browser/chromeos/policy/dlp/dlp_content_manager_unittest.cc
@@ -322,7 +322,7 @@ SetReportQueueForReportingManager(); SetupDlpRulesManager(); const std::string src_pattern("example.com"); - EXPECT_CALL(*mock_rules_manager_, GetSourceUrlPattern) + EXPECT_CALL(*mock_rules_manager_, GetSourceUrlPattern(_, _, _)) .Times(1) .WillOnce(::testing::Return(src_pattern));
diff --git a/chrome/browser/chromeos/policy/dlp/dlp_content_restriction_set.cc b/chrome/browser/chromeos/policy/dlp/dlp_content_restriction_set.cc index 50ce043a..606c179 100644 --- a/chrome/browser/chromeos/policy/dlp/dlp_content_restriction_set.cc +++ b/chrome/browser/chromeos/policy/dlp/dlp_content_restriction_set.cc
@@ -9,14 +9,14 @@ namespace policy { DlpContentRestrictionSet::DlpContentRestrictionSet() { - restrictions_.fill(DlpRulesManager::Level::kNotSet); + restrictions_.fill(RestrictionLevelAndUrl()); } DlpContentRestrictionSet::DlpContentRestrictionSet( DlpContentRestriction restriction, DlpRulesManager::Level level) { - restrictions_.fill(DlpRulesManager::Level::kNotSet); - restrictions_[restriction] = level; + restrictions_.fill(RestrictionLevelAndUrl()); + restrictions_[restriction].level = level; } DlpContentRestrictionSet::DlpContentRestrictionSet( @@ -38,18 +38,26 @@ } void DlpContentRestrictionSet::SetRestriction(DlpContentRestriction restriction, - DlpRulesManager::Level level) { - restrictions_[restriction] = std::max(restrictions_[restriction], level); + DlpRulesManager::Level level, + const GURL& url) { + if (level > restrictions_[restriction].level) { + restrictions_[restriction] = RestrictionLevelAndUrl(level, url); + } } -DlpRulesManager::Level DlpContentRestrictionSet::GetRestriction( +DlpRulesManager::Level DlpContentRestrictionSet::GetRestrictionLevel( + DlpContentRestriction restriction) const { + return restrictions_[restriction].level; +} + +RestrictionLevelAndUrl DlpContentRestrictionSet::GetRestrictionLevelAndUrl( DlpContentRestriction restriction) const { return restrictions_[restriction]; } bool DlpContentRestrictionSet::IsEmpty() const { for (int i = 0; i < restrictions_.size(); ++i) { - if (restrictions_[i] != DlpRulesManager::Level::kNotSet) + if (restrictions_[i].level != DlpRulesManager::Level::kNotSet) return false; } return true; @@ -58,7 +66,9 @@ void DlpContentRestrictionSet::UnionWith( const DlpContentRestrictionSet& other) { for (int i = 0; i < restrictions_.size(); ++i) { - restrictions_[i] = std::max(restrictions_[i], other.restrictions_[i]); + if (other.restrictions_[i].level > restrictions_[i].level) { + restrictions_[i] = other.restrictions_[i]; + } } } @@ -67,7 +77,7 @@ // Leave only the restrictions that are present in |this|, but not in |other|. DlpContentRestrictionSet result; for (int i = 0; i < restrictions_.size(); ++i) { - if (restrictions_[i] > other.restrictions_[i]) { + if (restrictions_[i].level > other.restrictions_[i].level) { result.restrictions_[i] = restrictions_[i]; } }
diff --git a/chrome/browser/chromeos/policy/dlp/dlp_content_restriction_set.h b/chrome/browser/chromeos/policy/dlp/dlp_content_restriction_set.h index c78b4bc..72c7d55 100644 --- a/chrome/browser/chromeos/policy/dlp/dlp_content_restriction_set.h +++ b/chrome/browser/chromeos/policy/dlp/dlp_content_restriction_set.h
@@ -9,6 +9,8 @@ #include <array> +#include "url/gurl.h" + namespace policy { // Enum representing the possible restrictions applied to on-screen content. @@ -29,6 +31,26 @@ kMaxValue = kScreenShare, }; +// Represents result of evaluating restriction - both the level at which it +// should be enforced and the url that caused it. +struct RestrictionLevelAndUrl { + RestrictionLevelAndUrl() = default; + RestrictionLevelAndUrl(DlpRulesManager::Level level, GURL url) + : level(level), url(url) {} + RestrictionLevelAndUrl(const RestrictionLevelAndUrl&) = default; + RestrictionLevelAndUrl& operator=(const RestrictionLevelAndUrl&) = default; + ~RestrictionLevelAndUrl() = default; + + // Restrictions with the same level, but different URLs are considered the + // same as they don't affect the current restriction enforcement. + bool operator==(const RestrictionLevelAndUrl& other) const { + return level == other.level; + } + + DlpRulesManager::Level level = DlpRulesManager::Level::kNotSet; + GURL url; +}; + // Represents set of levels of all restrictions applied to on-screen content. // Allowed to be copied and assigned. class DlpContentRestrictionSet { @@ -45,12 +67,18 @@ bool operator==(const DlpContentRestrictionSet& other) const; bool operator!=(const DlpContentRestrictionSet& other) const; - // Sets the |restriction| to the |level| if not set to a higher one yet. + // Sets the |restriction| to the |level| if not set to a higher one yet and + // remembers the |url| in this case. void SetRestriction(DlpContentRestriction restriction, - DlpRulesManager::Level level); + DlpRulesManager::Level level, + const GURL& gurl); // Returns the level for the |restriction|. - DlpRulesManager::Level GetRestriction( + DlpRulesManager::Level GetRestrictionLevel( + DlpContentRestriction restriction) const; + + // Returns the level and url for the |restriction|. + RestrictionLevelAndUrl GetRestrictionLevelAndUrl( DlpContentRestriction restriction) const; // Returns whether no restrictions should be applied. @@ -65,8 +93,8 @@ const DlpContentRestrictionSet& other) const; private: - // The current level of each of the restrictions. - std::array<DlpRulesManager::Level, DlpContentRestriction::kMaxValue + 1> + // The current level and url of each of the restrictions. + std::array<RestrictionLevelAndUrl, DlpContentRestriction::kMaxValue + 1> restrictions_; };
diff --git a/chrome/browser/chromeos/policy/dlp/dlp_reporting_manager.cc b/chrome/browser/chromeos/policy/dlp/dlp_reporting_manager.cc index 445bec2e..125477f 100644 --- a/chrome/browser/chromeos/policy/dlp/dlp_reporting_manager.cc +++ b/chrome/browser/chromeos/policy/dlp/dlp_reporting_manager.cc
@@ -92,9 +92,9 @@ report_queue_ = std::move(report_queue); } -void DlpReportingManager::ReportPrintingEvent( - const std::string& src_pattern, - DlpRulesManager::Level level) const { +void DlpReportingManager::ReportEvent(const std::string& src_pattern, + DlpRulesManager::Restriction restriction, + DlpRulesManager::Level level) const { // TODO(1187506, marcgrimme) Refactor to handle gracefully with user // interaction when queue is not ready. if (!report_queue_.get()) { @@ -104,10 +104,8 @@ } reporting::ReportQueue::EnqueueCallback callback = base::BindOnce( &DlpReportingManager::OnEventEnqueued, base::Unretained(this)); - report_queue_->Enqueue( - CreateDlpPolicyEvent(src_pattern, level, - DlpRulesManager::Restriction::kPrinting), - reporting::Priority::IMMEDIATE, std::move(callback)); + report_queue_->Enqueue(CreateDlpPolicyEvent(src_pattern, level, restriction), + reporting::Priority::IMMEDIATE, std::move(callback)); } void DlpReportingManager::OnEventEnqueued(reporting::Status status) const {
diff --git a/chrome/browser/chromeos/policy/dlp/dlp_reporting_manager.h b/chrome/browser/chromeos/policy/dlp/dlp_reporting_manager.h index cc7d065..baacd78 100644 --- a/chrome/browser/chromeos/policy/dlp/dlp_reporting_manager.h +++ b/chrome/browser/chromeos/policy/dlp/dlp_reporting_manager.h
@@ -37,8 +37,9 @@ // The different methods that cause report events from the specific // restrictions. - void ReportPrintingEvent(const std::string& src_pattern, - DlpRulesManager::Level level) const; + void ReportEvent(const std::string& src_pattern, + DlpRulesManager::Restriction restriction, + DlpRulesManager::Level level) const; ReportQueueSetterCallback GetReportQueueSetter();
diff --git a/chrome/browser/chromeos/policy/dlp/dlp_reporting_manager_unittest.cc b/chrome/browser/chromeos/policy/dlp/dlp_reporting_manager_unittest.cc index b9c44bd..10f6a5a 100644 --- a/chrome/browser/chromeos/policy/dlp/dlp_reporting_manager_unittest.cc +++ b/chrome/browser/chromeos/policy/dlp/dlp_reporting_manager_unittest.cc
@@ -50,7 +50,8 @@ TEST_F(DlpReportingManagerTest, IsPrintingRestricted) { std::unique_ptr<content::WebContents> web_contents = CreateWebContents(); auto src_pattern = web_contents->GetLastCommittedURL().spec(); - manager_.ReportPrintingEvent(src_pattern, DlpRulesManager::Level::kBlock); + manager_.ReportEvent(src_pattern, DlpRulesManager::Restriction::kPrinting, + DlpRulesManager::Level::kBlock); EXPECT_EQ(events_.size(), 1); EXPECT_THAT(events_[0],
diff --git a/chrome/browser/chromeos/policy/dlp/dlp_rules_manager.h b/chrome/browser/chromeos/policy/dlp/dlp_rules_manager.h index d9cee50..ff56aff 100644 --- a/chrome/browser/chromeos/policy/dlp/dlp_rules_manager.h +++ b/chrome/browser/chromeos/policy/dlp/dlp_rules_manager.h
@@ -103,6 +103,25 @@ virtual std::string GetSourceUrlPattern(const GURL& source_url, Restriction restriction, Level level) const = 0; + + // Returns the URL pattern that `source_url` is matched against. The returned + // URL pattern should be configured in a policy rule against `destination` + // with the same `restriction` and `level`. + virtual std::string GetSourceUrlPattern(const GURL& source_url, + const Component& destination, + Restriction restriction, + Level level) const = 0; + + // Returns the URL patterns that `source_url` and `destination_url` are + // matched against. The returned URL pattern should be configured in a policy + // rule with the same `restriction` and `level`. + // The first string in the returned pair is the source url pattern, and the + // second is the destination url pattern. + virtual std::pair<std::string, std::string> GetSrcAndDstUrlPatterns( + const GURL& source_url, + const GURL& destination_url, + Restriction restriction, + Level level) const = 0; }; } // namespace policy
diff --git a/chrome/browser/chromeos/policy/dlp/dlp_rules_manager_impl.cc b/chrome/browser/chromeos/policy/dlp/dlp_rules_manager_impl.cc index b7f307f..9c6338ae 100644 --- a/chrome/browser/chromeos/policy/dlp/dlp_rules_manager_impl.cc +++ b/chrome/browser/chromeos/policy/dlp/dlp_rules_manager_impl.cc
@@ -271,6 +271,95 @@ return std::string(); } +std::string DlpRulesManagerImpl::GetSourceUrlPattern( + const GURL& source_url, + const Component& destination, + Restriction restriction, + Level level) const { + const std::set<UrlConditionId> url_conditions_ids = + src_url_matcher_->MatchURL(source_url); + + std::map<RuleId, UrlConditionId> rules_conditions_map; + for (const auto& condition_id : url_conditions_ids) { + rules_conditions_map.insert( + std::make_pair(src_url_rules_mapping_.at(condition_id), condition_id)); + } + + auto it = components_rules_.find(destination); + if (it == components_rules_.end()) + return std::string(); + + const std::set<RuleId>& components_rules_ids = it->second; + + auto restriction_itr = restrictions_map_.find(restriction); + if (restriction_itr == restrictions_map_.end()) + return std::string(); + + const auto rules_levels_map = restriction_itr->second; + for (const auto& rule_level_entry : rules_levels_map) { + auto rule_id = rule_level_entry.first; + auto lvl = rule_level_entry.second; + auto rule_condition_itr = rules_conditions_map.find(rule_id); + auto component_rule_itr = components_rules_ids.find(rule_id); + if (lvl == level && rule_condition_itr != rules_conditions_map.end() && + component_rule_itr != components_rules_ids.end()) { + auto condition_id = rule_condition_itr->second; + auto condition_pattern_itr = src_pattterns_mapping_.find(condition_id); + if (condition_pattern_itr != src_pattterns_mapping_.end()) + return condition_pattern_itr->second; + } + } + return std::string(); +} + +std::pair<std::string, std::string> +DlpRulesManagerImpl::GetSrcAndDstUrlPatterns(const GURL& source_url, + const GURL& destination_url, + Restriction restriction, + Level level) const { + const std::set<UrlConditionId> url_conditions_ids = + src_url_matcher_->MatchURL(source_url); + + std::map<RuleId, UrlConditionId> src_rules_conditions_map; + for (const auto& condition_id : url_conditions_ids) { + src_rules_conditions_map.insert( + std::make_pair(src_url_rules_mapping_.at(condition_id), condition_id)); + } + + std::map<RuleId, UrlConditionId> dst_rules_conditions_map; + for (const auto& condition_id : url_conditions_ids) { + dst_rules_conditions_map.insert( + std::make_pair(dst_url_rules_mapping_.at(condition_id), condition_id)); + } + + auto restriction_itr = restrictions_map_.find(restriction); + if (restriction_itr == restrictions_map_.end()) + return std::make_pair(std::string(), std::string()); + + const auto rules_levels_map = restriction_itr->second; + for (const auto& rule_level_entry : rules_levels_map) { + auto rule_id = rule_level_entry.first; + auto lvl = rule_level_entry.second; + auto src_rule_condition_itr = src_rules_conditions_map.find(rule_id); + auto dst_rule_condition_itr = dst_rules_conditions_map.find(rule_id); + if (lvl == level && + src_rule_condition_itr != src_rules_conditions_map.end() && + dst_rule_condition_itr != dst_rules_conditions_map.end()) { + auto src_condition_id = src_rule_condition_itr->second; + auto src_condition_pattern_itr = + src_pattterns_mapping_.find(src_condition_id); + auto dst_condition_id = dst_rule_condition_itr->second; + auto dst_condition_pattern_itr = + dst_pattterns_mapping_.find(dst_condition_id); + if (src_condition_pattern_itr != src_pattterns_mapping_.end() && + dst_condition_pattern_itr != dst_pattterns_mapping_.end()) + return std::make_pair(src_condition_pattern_itr->second, + dst_condition_pattern_itr->second); + } + } + return std::make_pair(std::string(), std::string()); +} + void DlpRulesManagerImpl::OnPolicyUpdate() { components_rules_.clear(); restrictions_map_.clear();
diff --git a/chrome/browser/chromeos/policy/dlp/dlp_rules_manager_impl.h b/chrome/browser/chromeos/policy/dlp/dlp_rules_manager_impl.h index 6705a1fb9..d26d459 100644 --- a/chrome/browser/chromeos/policy/dlp/dlp_rules_manager_impl.h +++ b/chrome/browser/chromeos/policy/dlp/dlp_rules_manager_impl.h
@@ -45,6 +45,15 @@ std::string GetSourceUrlPattern(const GURL& source_url, Restriction restriction, Level level) const override; + std::string GetSourceUrlPattern(const GURL& source_url, + const Component& destination, + Restriction restriction, + Level level) const override; + std::pair<std::string, std::string> GetSrcAndDstUrlPatterns( + const GURL& source_url, + const GURL& destination_url, + Restriction restriction, + Level level) const override; protected: friend class DlpRulesManagerFactory;
diff --git a/chrome/browser/chromeos/policy/dlp/mock_dlp_rules_manager.h b/chrome/browser/chromeos/policy/dlp/mock_dlp_rules_manager.h index 762490c..a17322c 100644 --- a/chrome/browser/chromeos/policy/dlp/mock_dlp_rules_manager.h +++ b/chrome/browser/chromeos/policy/dlp/mock_dlp_rules_manager.h
@@ -42,6 +42,19 @@ std::string(const GURL& source_url, Restriction restriction, Level level)); + + MOCK_CONST_METHOD4(GetSourceUrlPattern, + std::string(const GURL& source_url, + const Component& destination, + Restriction restriction, + Level level)); + + MOCK_CONST_METHOD4( + GetSrcAndDstUrlPatterns, + std::pair<std::string, std::string>(const GURL& source_url, + const GURL& destination_url, + Restriction restriction, + Level level)); }; } // namespace policy
diff --git a/chrome/browser/chromeos/policy/policy_cert_service_factory.cc b/chrome/browser/chromeos/policy/policy_cert_service_factory.cc index e2411f2..5bb9f35 100644 --- a/chrome/browser/chromeos/policy/policy_cert_service_factory.cc +++ b/chrome/browser/chromeos/policy/policy_cert_service_factory.cc
@@ -87,7 +87,8 @@ NOTREACHED(); return false; } - return list->Find(value) != list->GetList().end(); + // TODO(crbug.com/1187106): Use base::Contains once |list| is not a ListValue. + return std::find(list->begin(), list->end(), value) != list->end(); } // static
diff --git a/chrome/browser/content_settings/content_settings_pref_provider_unittest.cc b/chrome/browser/content_settings/content_settings_pref_provider_unittest.cc index 8a6143a..5490f940 100644 --- a/chrome/browser/content_settings/content_settings_pref_provider_unittest.cc +++ b/chrome/browser/content_settings/content_settings_pref_provider_unittest.cc
@@ -555,7 +555,7 @@ for (const char* pref : nonempty_prefs) { DictionaryPrefUpdate update(&prefs, pref); const base::DictionaryValue* dictionary = update.Get(); - EXPECT_EQ(1u, dictionary->size()); + EXPECT_EQ(1u, dictionary->DictSize()); } provider.ShutdownOnUIThread();
diff --git a/chrome/browser/enterprise/reporting/prefs.cc b/chrome/browser/enterprise/reporting/prefs.cc index 7ce4bf4..f2662e5 100644 --- a/chrome/browser/enterprise/reporting/prefs.cc +++ b/chrome/browser/enterprise/reporting/prefs.cc
@@ -25,6 +25,7 @@ // the migration. registry->RegisterBooleanPref(kCloudReportingEnabled, false); registry->RegisterTimePref(kLastUploadTimestamp, base::Time()); + registry->RegisterTimePref(kLastUploadSucceededTimestamp, base::Time()); registry->RegisterStringPref(kLastUploadVersion, std::string()); }
diff --git a/chrome/browser/enterprise/reporting/profile_report_generator_unittest.cc b/chrome/browser/enterprise/reporting/profile_report_generator_unittest.cc index 7ac9ec0..80c547dc 100644 --- a/chrome/browser/enterprise/reporting/profile_report_generator_unittest.cc +++ b/chrome/browser/enterprise/reporting/profile_report_generator_unittest.cc
@@ -35,7 +35,6 @@ const int kMaxNumberOfExtensionRequest = 1000; constexpr char kProfile[] = "Profile"; -constexpr char16_t kProfile16[] = u"Profile"; constexpr char kIdleProfile[] = "IdleProfile"; constexpr char16_t kIdleProfile16[] = u"IdleProfile"; constexpr char kExtensionId[] = "abcdefghijklmnopabcdefghijklmnop"; @@ -69,7 +68,7 @@ InitPolicyMap(); profile_ = profile_manager_.CreateTestingProfile( - kProfile, {}, kProfile16, 0, {}, + kProfile, {}, base::UTF8ToUTF16(kProfile), 0, {}, IdentityTestEnvironmentProfileAdaptor:: GetIdentityTestEnvironmentFactories(), base::nullopt, std::move(policy_service_));
diff --git a/chrome/browser/extensions/api/bookmarks/bookmark_api_helpers_unittest.cc b/chrome/browser/extensions/api/bookmarks/bookmark_api_helpers_unittest.cc index ae7ac0af..1abbb62 100644 --- a/chrome/browser/extensions/api/bookmarks/bookmark_api_helpers_unittest.cc +++ b/chrome/browser/extensions/api/bookmarks/bookmark_api_helpers_unittest.cc
@@ -175,7 +175,7 @@ TEST_F(ExtensionBookmarksTest, GetMetaInfo) { base::DictionaryValue id_to_meta_info_map; GetMetaInfo(*model_->other_node(), &id_to_meta_info_map); - EXPECT_EQ(8u, id_to_meta_info_map.size()); + EXPECT_EQ(8u, id_to_meta_info_map.DictSize()); // Verify top level node. const base::Value* value = NULL; @@ -184,8 +184,8 @@ ASSERT_TRUE(NULL != value); const base::DictionaryValue* dictionary_value = NULL; EXPECT_TRUE(value->GetAsDictionary(&dictionary_value)); - ASSERT_TRUE(NULL != dictionary_value); - EXPECT_EQ(0u, dictionary_value->size()); + ASSERT_TRUE(nullptr != dictionary_value); + EXPECT_EQ(0u, dictionary_value->DictSize()); // Verify bookmark with two meta info key/value pairs. value = NULL; @@ -194,8 +194,8 @@ ASSERT_TRUE(NULL != value); dictionary_value = NULL; EXPECT_TRUE(value->GetAsDictionary(&dictionary_value)); - ASSERT_TRUE(NULL != dictionary_value); - EXPECT_EQ(2u, dictionary_value->size()); + ASSERT_TRUE(nullptr != dictionary_value); + EXPECT_EQ(2u, dictionary_value->DictSize()); std::string string_value; EXPECT_TRUE(dictionary_value->GetString("some_key1", &string_value)); EXPECT_EQ("some_value1", string_value); @@ -209,8 +209,8 @@ ASSERT_TRUE(NULL != value); dictionary_value = NULL; EXPECT_TRUE(value->GetAsDictionary(&dictionary_value)); - ASSERT_TRUE(NULL != dictionary_value); - EXPECT_EQ(1u, dictionary_value->size()); + ASSERT_TRUE(nullptr != dictionary_value); + EXPECT_EQ(1u, dictionary_value->DictSize()); EXPECT_TRUE(dictionary_value->GetString("some_key1", &string_value)); EXPECT_EQ("some_value1", string_value); @@ -221,8 +221,8 @@ ASSERT_TRUE(NULL != value); dictionary_value = NULL; EXPECT_TRUE(value->GetAsDictionary(&dictionary_value)); - ASSERT_TRUE(NULL != dictionary_value); - EXPECT_EQ(1u, dictionary_value->size()); + ASSERT_TRUE(nullptr != dictionary_value); + EXPECT_EQ(1u, dictionary_value->DictSize()); string_value.clear(); EXPECT_FALSE(dictionary_value->GetString("some_key1", &string_value)); EXPECT_EQ("", string_value);
diff --git a/chrome/browser/extensions/api/declarative_webrequest/webrequest_action_unittest.cc b/chrome/browser/extensions/api/declarative_webrequest/webrequest_action_unittest.cc index 628ff93..bc9451c 100644 --- a/chrome/browser/extensions/api/declarative_webrequest/webrequest_action_unittest.cc +++ b/chrome/browser/extensions/api/declarative_webrequest/webrequest_action_unittest.cc
@@ -55,9 +55,9 @@ CHECK(parsed_value->GetAsList(&parsed_list)); WebRequestActionSet::Values actions; - for (auto it = parsed_list->begin(); it != parsed_list->end(); ++it) { + for (const auto& entry : parsed_list->GetList()) { const base::DictionaryValue* dict; - CHECK(it->GetAsDictionary(&dict)); + CHECK(entry.GetAsDictionary(&dict)); actions.push_back(dict->CreateDeepCopy()); }
diff --git a/chrome/browser/extensions/api/signed_in_devices/id_mapping_helper_unittest.cc b/chrome/browser/extensions/api/signed_in_devices/id_mapping_helper_unittest.cc index 2d06911..ea53b32 100644 --- a/chrome/browser/extensions/api/signed_in_devices/id_mapping_helper_unittest.cc +++ b/chrome/browser/extensions/api/signed_in_devices/id_mapping_helper_unittest.cc
@@ -87,6 +87,6 @@ EXPECT_TRUE(VerifyDictionary(public_id2, devices[1]->guid(), dictionary)); EXPECT_TRUE(VerifyDictionary(public_id3, devices[2]->guid(), dictionary)); - EXPECT_EQ(dictionary.size(), 3U); + EXPECT_EQ(dictionary.DictSize(), 3U); } } // namespace extensions
diff --git a/chrome/browser/extensions/api/storage/policy_value_store_unittest.cc b/chrome/browser/extensions/api/storage/policy_value_store_unittest.cc index cfc0e71..690b95d9 100644 --- a/chrome/browser/extensions/api/storage/policy_value_store_unittest.cc +++ b/chrome/browser/extensions/api/storage/policy_value_store_unittest.cc
@@ -164,7 +164,7 @@ ValueStore::ReadResult result = store_->Get(); ASSERT_TRUE(result.status().ok()); - EXPECT_EQ(1u, result.settings().size()); + EXPECT_EQ(1u, result.settings().DictSize()); base::Value* value = NULL; EXPECT_FALSE(result.settings().Get("may", &value)); EXPECT_TRUE(result.settings().Get("must", &value));
diff --git a/chrome/browser/extensions/api/web_request/web_request_event_details_unittest.cc b/chrome/browser/extensions/api/web_request/web_request_event_details_unittest.cc index f95ddd83..7a8dc443 100644 --- a/chrome/browser/extensions/api/web_request/web_request_event_details_unittest.cc +++ b/chrome/browser/extensions/api/web_request/web_request_event_details_unittest.cc
@@ -68,7 +68,7 @@ EXPECT_EQ("http://www.foo.bar/", url); // Extras are filtered out (+1 for url). - EXPECT_EQ(base::size(safe_attributes) + 1, copy->dict_.size()); + EXPECT_EQ(base::size(safe_attributes) + 1, copy->dict_.DictSize()); } TEST(WebRequestEventDetailsTest, SetResponseHeaders) {
diff --git a/chrome/browser/extensions/api/webstore_private/webstore_private_unittest.cc b/chrome/browser/extensions/api/webstore_private/webstore_private_unittest.cc index c8a8903..bd81fca 100644 --- a/chrome/browser/extensions/api/webstore_private/webstore_private_unittest.cc +++ b/chrome/browser/extensions/api/webstore_private/webstore_private_unittest.cc
@@ -97,7 +97,8 @@ Profile* profile) { const base::DictionaryValue* actual_pending_requests = profile->GetPrefs()->GetDictionary(prefs::kCloudExtensionRequestIds); - ASSERT_EQ(expected_pending_requests.size(), actual_pending_requests->size()); + ASSERT_EQ(expected_pending_requests.size(), + actual_pending_requests->DictSize()); for (const auto& expected_request : expected_pending_requests) { EXPECT_EQ(::util::TimeToValue(expected_request.second), *actual_pending_requests->FindKey(expected_request.first)
diff --git a/chrome/browser/extensions/convert_web_app.cc b/chrome/browser/extensions/convert_web_app.cc index b68aae0e..7ffd1dbf 100644 --- a/chrome/browser/extensions/convert_web_app.cc +++ b/chrome/browser/extensions/convert_web_app.cc
@@ -352,7 +352,7 @@ // current shortcut in web_app.shortcuts_menu_item_infos. A shortcut in // the WebAppManifest can have different icons for different sizes. auto shortcut_icons = std::make_unique<base::DictionaryValue>(); - std::string curr_icon = base::NumberToString(shortcuts_icons->size()); + std::string curr_icon = base::NumberToString(shortcuts_icons->DictSize()); for (const auto& icon : shortcut_icon_bitmaps.any) { std::string size = base::NumberToString(icon.first); std::string icon_path =
diff --git a/chrome/browser/extensions/crx_installer_browsertest.cc b/chrome/browser/extensions/crx_installer_browsertest.cc index bcaceda..7d05f18 100644 --- a/chrome/browser/extensions/crx_installer_browsertest.cc +++ b/chrome/browser/extensions/crx_installer_browsertest.cc
@@ -82,9 +82,9 @@ namespace { const char kAppUrl[] = "http://www.google.com"; -const char16_t kAppTitle[] = u"Test title"; -const char16_t kAppDescription[] = u"Test description"; -const char16_t kShortcutItemName[] = u"shortcut"; +const char kAppTitle[] = "Test title"; +const char kAppDescription[] = "Test description"; +const char kShortcutItemName[] = "shortcut"; const char kShortcutUrl[] = "http://www.google.com/shortcut"; const char kShortcutIconUrl[] = "http://www.google.com/shortcut/icon.png"; @@ -140,14 +140,14 @@ return bitmap; } -WebApplicationInfo CreateWebAppInfo(const char16_t* title, - const char16_t* description, +WebApplicationInfo CreateWebAppInfo(const char* title, + const char* description, const char* start_url, int size, bool create_with_shortcuts) { WebApplicationInfo web_app_info; - web_app_info.title = title; - web_app_info.description = description; + web_app_info.title = base::UTF8ToUTF16(title); + web_app_info.description = base::UTF8ToUTF16(description); web_app_info.start_url = GURL(start_url); web_app_info.scope = GURL(start_url); web_app_info.icon_bitmaps.any[size] = CreateSquareBitmap(size); @@ -155,7 +155,7 @@ WebApplicationShortcutsMenuItemInfo shortcut_item; WebApplicationShortcutsMenuItemInfo::Icon icon; IconBitmaps shortcut_icon_bitmaps; - shortcut_item.name = kShortcutItemName; + shortcut_item.name = base::UTF8ToUTF16(kShortcutItemName); shortcut_item.url = GURL(kShortcutUrl); icon.url = GURL(kShortcutIconUrl); icon.square_size_px = size;
diff --git a/chrome/browser/extensions/extension_assets_manager_chromeos.cc b/chrome/browser/extensions/extension_assets_manager_chromeos.cc index 7266a1a4..abd1070d 100644 --- a/chrome/browser/extensions/extension_assets_manager_chromeos.cc +++ b/chrome/browser/extensions/extension_assets_manager_chromeos.cc
@@ -216,7 +216,7 @@ DictionaryPrefUpdate shared_extensions(local_state, kSharedExtensions); std::vector<std::string> extensions; - extensions.reserve(shared_extensions->size()); + extensions.reserve(shared_extensions->DictSize()); for (base::DictionaryValue::Iterator it(*shared_extensions); !it.IsAtEnd(); it.Advance()) { extensions.push_back(it.key()); @@ -440,7 +440,7 @@ } std::vector<std::string> versions; - versions.reserve(extension_info->size()); + versions.reserve(extension_info->DictSize()); for (base::DictionaryValue::Iterator it(*extension_info); !it.IsAtEnd(); it.Advance()) { @@ -501,7 +501,7 @@ } std::vector<std::string> versions; - versions.reserve(extension_info->size()); + versions.reserve(extension_info->DictSize()); for (base::DictionaryValue::Iterator it(*extension_info); !it.IsAtEnd(); it.Advance()) { versions.push_back(it.key());
diff --git a/chrome/browser/extensions/extension_service_test_base.cc b/chrome/browser/extensions/extension_service_test_base.cc index 23da14f6..0707f65 100644 --- a/chrome/browser/extensions/extension_service_test_base.cc +++ b/chrome/browser/extensions/extension_service_test_base.cc
@@ -248,7 +248,7 @@ ADD_FAILURE(); return 0; } - return dict->size(); + return dict->DictSize(); } void ExtensionServiceTestBase::ValidatePrefKeyCount(size_t count) {
diff --git a/chrome/browser/extensions/external_pref_loader.cc b/chrome/browser/extensions/external_pref_loader.cc index 2a95e01..ca77bb9e 100644 --- a/chrome/browser/extensions/external_pref_loader.cc +++ b/chrome/browser/extensions/external_pref_loader.cc
@@ -340,7 +340,7 @@ } if (base_path_id_ == chrome::DIR_EXTERNAL_EXTENSIONS) - UMA_HISTOGRAM_COUNTS_100("Extensions.ExternalJsonCount", prefs->size()); + UMA_HISTOGRAM_COUNTS_100("Extensions.ExternalJsonCount", prefs->DictSize()); // If we have any records to process, then we must have // read at least one .json file. If so, then we should have
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index cd752e2..0a1d4f03 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -1653,10 +1653,6 @@ "Recompute hover state at BeginFrame for layout and scroll based mouse " "moves, rather than old timing-based mechanism."; -const char kUseMultiloginEndpointName[] = "Use Multilogin endpoint."; -const char kUseMultiloginEndpointDescription[] = - "Use Gaia OAuth multilogin for identity consistency."; - const char kOmniboxAdaptiveSuggestionsCountName[] = "Adaptive Omnibox Suggestions count"; const char kOmniboxAdaptiveSuggestionsCountDescription[] =
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index a146c850..194cc60 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -968,9 +968,6 @@ extern const char kNotificationsSystemFlagName[]; extern const char kNotificationsSystemFlagDescription[]; -extern const char kUseMultiloginEndpointName[]; -extern const char kUseMultiloginEndpointDescription[]; - extern const char kOmniboxAdaptiveSuggestionsCountName[]; extern const char kOmniboxAdaptiveSuggestionsCountDescription[];
diff --git a/chrome/browser/interstitials/security_interstitial_idn_test.cc b/chrome/browser/interstitials/security_interstitial_idn_test.cc index 7009e4c..37147f69 100644 --- a/chrome/browser/interstitials/security_interstitial_idn_test.cc +++ b/chrome/browser/interstitials/security_interstitial_idn_test.cc
@@ -20,7 +20,7 @@ testing::AssertionResult SecurityInterstitialIDNTest::VerifyIDNDecoded() const { const char kHostname[] = "xn--d1abbgf6aiiy.xn--p1ai"; - const char16_t kHostnameUnicode[] = u"президент.рф"; + const char kHostnameUnicode[] = "президент.рф"; std::string request_url_spec = base::StringPrintf("https://%s/", kHostname); GURL request_url(request_url_spec); @@ -35,9 +35,9 @@ net::ERR_BLOCKED_BY_CLIENT); observer.Wait(); delete blocking_page; - if (ui_test_utils::FindInPage(contents, kHostnameUnicode, true /*forward*/, - true /*case_sensitive*/, nullptr, - nullptr) == 1) { + if (ui_test_utils::FindInPage(contents, base::UTF8ToUTF16(kHostnameUnicode), + true /*forward*/, true /*case_sensitive*/, + nullptr, nullptr) == 1) { return testing::AssertionSuccess(); } return testing::AssertionFailure() << "Interstitial not displaying text";
diff --git a/chrome/browser/media/webrtc/webrtc_getmediadevices_browsertest.cc b/chrome/browser/media/webrtc/webrtc_getmediadevices_browsertest.cc index 85232dea..70f4d62 100644 --- a/chrome/browser/media/webrtc/webrtc_getmediadevices_browsertest.cc +++ b/chrome/browser/media/webrtc/webrtc_getmediadevices_browsertest.cc
@@ -88,10 +88,10 @@ bool found_audio_input = false; bool found_video_input = false; - for (auto it = values->begin(); it != values->end(); ++it) { + for (const auto& entry : values->GetList()) { const base::DictionaryValue* dict; MediaDeviceInfo device; - ASSERT_TRUE(it->GetAsDictionary(&dict)); + ASSERT_TRUE(entry.GetAsDictionary(&dict)); ASSERT_TRUE(dict->GetString("deviceId", &device.device_id)); ASSERT_TRUE(dict->GetString("kind", &device.kind)); ASSERT_TRUE(dict->GetString("label", &device.label));
diff --git a/chrome/browser/media/webrtc/webrtc_video_display_perf_browsertest.cc b/chrome/browser/media/webrtc/webrtc_video_display_perf_browsertest.cc index 48246c0..c2e863b2 100644 --- a/chrome/browser/media/webrtc/webrtc_video_display_perf_browsertest.cc +++ b/chrome/browser/media/webrtc/webrtc_video_display_perf_browsertest.cc
@@ -133,7 +133,7 @@ ignore_result(parsed_json.release()); // |dictionary| should have exactly two entries, one per ssrc. - if (!dictionary || dictionary->size() != 2u) + if (!dictionary || dictionary->DictSize() != 2u) return goog_decode_ms; // Only a given |dictionary| entry will have a "stats" entry that has a key
diff --git a/chrome/browser/notifications/scheduler/internal/notification_scheduler_unittest.cc b/chrome/browser/notifications/scheduler/internal/notification_scheduler_unittest.cc index 96fc8c94..0e821bb 100644 --- a/chrome/browser/notifications/scheduler/internal/notification_scheduler_unittest.cc +++ b/chrome/browser/notifications/scheduler/internal/notification_scheduler_unittest.cc
@@ -38,7 +38,7 @@ namespace { const char kGuid[] = "guid"; -const char16_t kTitle[] = u"title"; +const char kTitle[] = "title"; class NotificationSchedulerTest : public testing::Test { public: @@ -293,8 +293,8 @@ OnStartTask(); } -MATCHER_P(NotificationDataEq, title, "Verify notification data.") { - EXPECT_EQ(arg->title, title); +MATCHER_P(NotifcationDataEq, title, "Verify notification data.") { + EXPECT_EQ(arg->title, base::UTF8ToUTF16(title)); return true; } @@ -313,7 +313,7 @@ std::make_unique<NotificationEntry>(SchedulerClientType::kTest1, kGuid); EXPECT_CALL( *display_agent(), - ShowNotification(NotificationDataEq(kTitle), + ShowNotification(NotifcationDataEq(kTitle), SystemDataEq(SchedulerClientType::kTest1, kGuid))); DisplayDecider::Results result({kGuid}); EXPECT_CALL(*display_decider(), FindNotificationsToShow(_, _, _)) @@ -333,7 +333,7 @@ [&](std::unique_ptr<NotificationData> notification_data, NotificationSchedulerClient::NotificationDataCallback callback) { // The client updates the notification data here. - notification_data->title = kTitle; + notification_data->title = base::UTF8ToUTF16(kTitle); std::move(callback).Run(std::move(notification_data)); }));
diff --git a/chrome/browser/notifications/scheduler/internal/scheduled_notification_manager_unittest.cc b/chrome/browser/notifications/scheduler/internal/scheduled_notification_manager_unittest.cc index a1de226..921c364 100644 --- a/chrome/browser/notifications/scheduler/internal/scheduled_notification_manager_unittest.cc +++ b/chrome/browser/notifications/scheduler/internal/scheduled_notification_manager_unittest.cc
@@ -30,7 +30,7 @@ const char kGuid[] = "test_guid_1234"; const char kNonExistentGuid[] = "guid_non_existent"; -const char16_t kTitle[] = u"test_title"; +const char kTitle[] = "test_title"; const char kSmallIconUuid[] = "test_small_icon_uuid"; const char kLargeIconUuid[] = "test_large_icon_uuid"; @@ -298,7 +298,7 @@ TEST_F(ScheduledNotificationManagerTest, ScheduleNotification) { InitWithData(std::vector<NotificationEntry>()); NotificationData notification_data; - notification_data.title = kTitle; + notification_data.title = base::UTF8ToUTF16(kTitle); ScheduleParams schedule_params; schedule_params.priority = ScheduleParams::Priority::kLow; auto params = std::make_unique<NotificationParams>( @@ -333,7 +333,7 @@ EXPECT_NE(entry->create_time, base::Time()); // TODO(xingliu): change these to compare with operator==. - EXPECT_EQ(entry->notification_data.title, kTitle); + EXPECT_EQ(base::UTF16ToUTF8(entry->notification_data.title), kTitle); EXPECT_EQ(entry->schedule_params.priority, ScheduleParams::Priority::kLow); // Verify that |enable_ihnr_buttons| will add the helpful/unhelpful buttons. @@ -349,7 +349,7 @@ TEST_F(ScheduledNotificationManagerTest, ScheduleInvalidNotification) { InitWithData(std::vector<NotificationEntry>()); NotificationData notification_data; - notification_data.title = kTitle; + notification_data.title = base::UTF8ToUTF16(kTitle); ScheduleParams schedule_params; // Client type kTest3 is not registered. auto params = std::make_unique<NotificationParams>( @@ -367,7 +367,7 @@ InitWithData(std::vector<NotificationEntry>({entry})); NotificationData notification_data; - notification_data.title = kTitle; + notification_data.title = base::UTF8ToUTF16(kTitle); ScheduleParams schedule_params; auto params = std::make_unique<NotificationParams>( SchedulerClientType::kTest1, notification_data, schedule_params);
diff --git a/chrome/browser/notifications/win/notification_template_builder_unittest.cc b/chrome/browser/notifications/win/notification_template_builder_unittest.cc index 991acaa..35c129c 100644 --- a/chrome/browser/notifications/win/notification_template_builder_unittest.cc +++ b/chrome/browser/notifications/win/notification_template_builder_unittest.cc
@@ -29,8 +29,8 @@ const char kContextMenuLabel[] = "settings"; const char kEncodedId[] = "0|0|Default|0|https://example.com/|notification_id"; const char kNotificationId[] = "notification_id"; -const char16_t kNotificationTitle[] = u"My Title"; -const char16_t kNotificationMessage[] = u"My Message"; +const char kNotificationTitle[] = "My Title"; +const char kNotificationMessage[] = "My Message"; const char kNotificationOrigin[] = "https://example.com"; base::Time FixedTime() { @@ -67,7 +67,8 @@ GURL origin_url(kNotificationOrigin); message_center::Notification notification( message_center::NOTIFICATION_TYPE_SIMPLE, kNotificationId, - kNotificationTitle, kNotificationMessage, gfx::Image() /* icon */, + base::UTF8ToUTF16(kNotificationTitle), + base::UTF8ToUTF16(kNotificationMessage), gfx::Image() /* icon */, std::u16string() /* display_source */, origin_url, NotifierId(origin_url), RichNotificationData(), nullptr /* delegate */); // Set a fixed timestamp, to avoid having to test against current timestamp.
diff --git a/chrome/browser/password_manager/android/BUILD.gn b/chrome/browser/password_manager/android/BUILD.gn index 176293b..2ad5c6d 100644 --- a/chrome/browser/password_manager/android/BUILD.gn +++ b/chrome/browser/password_manager/android/BUILD.gn
@@ -11,6 +11,7 @@ "//chrome/browser/settings:java", "//components/browser_ui/settings/android:java", "//components/password_manager/core/browser:password_manager_java_enums", + "//content/public/android:content_java", "//third_party/androidx:androidx_annotation_annotation_java", "//third_party/androidx:androidx_appcompat_appcompat_java", "//third_party/androidx:androidx_core_core_java",
diff --git a/chrome/browser/password_manager/android/DEPS b/chrome/browser/password_manager/android/DEPS new file mode 100644 index 0000000..ca4acba --- /dev/null +++ b/chrome/browser/password_manager/android/DEPS
@@ -0,0 +1,4 @@ +include_rules = [ + "-content/public/android/java", + "+content/public/android/java/src/org/chromium/content_public", +] \ No newline at end of file
diff --git a/chrome/browser/password_manager/android/java/src/org/chromium/chrome/browser/password_manager/BiometricAuthenticatorBridge.java b/chrome/browser/password_manager/android/java/src/org/chromium/chrome/browser/password_manager/BiometricAuthenticatorBridge.java index 962b15f..538d80a 100644 --- a/chrome/browser/password_manager/android/java/src/org/chromium/chrome/browser/password_manager/BiometricAuthenticatorBridge.java +++ b/chrome/browser/password_manager/android/java/src/org/chromium/chrome/browser/password_manager/BiometricAuthenticatorBridge.java
@@ -9,80 +9,123 @@ import static android.hardware.biometrics.BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE; import static android.hardware.biometrics.BiometricManager.BIOMETRIC_SUCCESS; +import android.app.KeyguardManager; import android.content.Context; import android.hardware.biometrics.BiometricManager; +import android.hardware.biometrics.BiometricPrompt; import android.os.Build; +import android.os.CancellationSignal; +import android.support.annotation.NonNull; -import androidx.core.hardware.fingerprint.FingerprintManagerCompat; +import androidx.annotation.RequiresApi; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.NativeMethods; -import org.chromium.base.compat.ApiHelperForQ; +import org.chromium.base.task.PostTask; +import org.chromium.content_public.browser.UiThreadTaskTraits; import org.chromium.ui.base.WindowAndroid; +import java.util.concurrent.Executor; + class BiometricAuthenticatorBridge { + private CancellationSignal mCancellationSignal; private final Context mContext; private long mNativeBiometricAuthenticator; + private BiometricPrompt mBiometricPrompt; - private BiometricAuthenticatorBridge( - long nativeBiometricAuthenticator, WindowAndroid windowAndroid) { - mContext = windowAndroid.getApplicationContext(); + private BiometricAuthenticatorBridge(long nativeBiometricAuthenticator, Context context) { mNativeBiometricAuthenticator = nativeBiometricAuthenticator; + mContext = context; + mNativeBiometricAuthenticator = nativeBiometricAuthenticator; + if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) { + BiometricPrompt.Builder promptBuilder = new BiometricPrompt.Builder(mContext).setTitle( + mContext.getResources().getString( + R.string.password_filling_reauth_prompt_title)); + promptBuilder.setDeviceCredentialAllowed(true); + mBiometricPrompt = promptBuilder.build(); + } } @CalledByNative private static BiometricAuthenticatorBridge create( long nativeBiometricAuthenticator, WindowAndroid windowAndroid) { - return new BiometricAuthenticatorBridge(nativeBiometricAuthenticator, windowAndroid); + return new BiometricAuthenticatorBridge( + nativeBiometricAuthenticator, windowAndroid.getApplicationContext()); } @CalledByNative - public @BiometricsAvailability int canAuthenticate() { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { - BiometricManager biometricManager = - ApiHelperForQ.getBiometricManagerSystemService(mContext); - switch (ApiHelperForQ.canAuthenticate(biometricManager)) { - case BIOMETRIC_SUCCESS: - return BiometricsAvailability.AVAILABLE; - case BIOMETRIC_ERROR_NO_HARDWARE: - case BIOMETRIC_ERROR_HW_UNAVAILABLE: - return BiometricsAvailability.NO_HARDWARE; - case BIOMETRIC_ERROR_NONE_ENROLLED: - return BiometricsAvailability.NOT_ENROLLED; - default: - return BiometricsAvailability.NO_HARDWARE; - } - } else { - FingerprintManagerCompat fingerprintManager = FingerprintManagerCompat.from(mContext); - if (!fingerprintManager.isHardwareDetected()) { - return BiometricsAvailability.NO_HARDWARE; - } else if (!fingerprintManager.hasEnrolledFingerprints()) { + @BiometricsAvailability + int canAuthenticate() { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { + return BiometricsAvailability.ANDROID_VERSION_NOT_SUPPORTED; + } + BiometricManager biometricManager = mContext.getSystemService(BiometricManager.class); + switch (biometricManager.canAuthenticate()) { + case BIOMETRIC_SUCCESS: + return hasScreenLockSetUp() ? BiometricsAvailability.AVAILABLE + : BiometricsAvailability.AVAILABLE_NO_FALLBACK; + case BIOMETRIC_ERROR_NONE_ENROLLED: return BiometricsAvailability.NOT_ENROLLED; - } else { - return BiometricsAvailability.AVAILABLE; - } + case BIOMETRIC_ERROR_NO_HARDWARE: + case BIOMETRIC_ERROR_HW_UNAVAILABLE: + default: + return BiometricsAvailability.NO_HARDWARE; } } @CalledByNative + @RequiresApi(Build.VERSION_CODES.P) void authenticate() { - // TODO(crbug.com/1031483): Trigger a biometric prompt. - onAuthenticationCompleted(true); - } + if (mBiometricPrompt == null) { + return; + } + mCancellationSignal = new CancellationSignal(); + Executor callbackExecutor = (r) -> PostTask.postTask(UiThreadTaskTraits.DEFAULT, r); - @CalledByNative - void cancel() { - mNativeBiometricAuthenticator = 0; - // TODO(crbug.com/1031483): Cancel the reauth if one is in progress. + mBiometricPrompt.authenticate(mCancellationSignal, callbackExecutor, + new BiometricPrompt.AuthenticationCallback() { + @Override + public void onAuthenticationError( + int errorCode, @NonNull CharSequence errString) { + super.onAuthenticationError(errorCode, errString); + onAuthenticationCompleted(false); + } + + @Override + public void onAuthenticationSucceeded( + @NonNull BiometricPrompt.AuthenticationResult result) { + super.onAuthenticationSucceeded(result); + onAuthenticationCompleted(true); + } + }); } void onAuthenticationCompleted(boolean success) { + mCancellationSignal = null; if (mNativeBiometricAuthenticator != 0) { BiometricAuthenticatorBridgeJni.get().onAuthenticationCompleted( mNativeBiometricAuthenticator, success); } } + @CalledByNative + void destroy() { + mNativeBiometricAuthenticator = 0; + cancel(); + } + + @CalledByNative + void cancel() { + if (mCancellationSignal != null) { + mCancellationSignal.cancel(); + } + } + + private boolean hasScreenLockSetUp() { + return ((KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE)) + .isKeyguardSecure(); + } + @NativeMethods interface Natives { void onAuthenticationCompleted(long nativeBiometricAuthenticatorAndroid, boolean success);
diff --git a/chrome/browser/password_manager/biometric_authenticator_android.cc b/chrome/browser/password_manager/biometric_authenticator_android.cc index 85afc6a..fb3a749 100644 --- a/chrome/browser/password_manager/biometric_authenticator_android.cc +++ b/chrome/browser/password_manager/biometric_authenticator_android.cc
@@ -53,7 +53,10 @@ window_android->GetJavaObject()); } -BiometricAuthenticatorAndroid::~BiometricAuthenticatorAndroid() = default; +BiometricAuthenticatorAndroid::~BiometricAuthenticatorAndroid() { + Java_BiometricAuthenticatorBridge_destroy(AttachCurrentThread(), + java_object_); +} BiometricsAvailability BiometricAuthenticatorAndroid::CanAuthenticate() { return static_cast<BiometricsAvailability>(
diff --git a/chrome/browser/password_manager/password_manager_signin_intercept_test_helper.cc b/chrome/browser/password_manager/password_manager_signin_intercept_test_helper.cc index 27186a3..53fa1b63 100644 --- a/chrome/browser/password_manager/password_manager_signin_intercept_test_helper.cc +++ b/chrome/browser/password_manager/password_manager_signin_intercept_test_helper.cc
@@ -37,7 +37,6 @@ constexpr char kGaiaUsername[] = "username"; constexpr char16_t kGaiaUsername16[] = u"username"; constexpr char kGaiaEmail[] = "username@gmail.com"; -constexpr char16_t kGaiaEmail16[] = u"username@gmail.com"; constexpr char kGaiaId[] = "test_gaia_id"; } // namespace @@ -103,7 +102,7 @@ params.profile_path = profile_path; params.profile_name = u"TestProfileName"; params.gaia_id = kGaiaId; - params.user_name = kGaiaEmail16; + params.user_name = base::UTF8ToUTF16(kGaiaEmail); profile_storage->AddProfile(std::move(params)); // Check that the signin qualifies for interception.
diff --git a/chrome/browser/payments/BUILD.gn b/chrome/browser/payments/BUILD.gn index 13ff731..60a5379 100644 --- a/chrome/browser/payments/BUILD.gn +++ b/chrome/browser/payments/BUILD.gn
@@ -18,7 +18,6 @@ "ignore_payment_method_browsertest.cc", "journey_logger_browsertest.cc", "load_and_remove_iframe_with_many_payment_requests_browsertest.cc", - "payment_handler_capabilities_browsertest.cc", "payment_handler_change_shipping_address_option_browsertest.cc", "payment_handler_enable_delegations_browsertest.cc", "payment_handler_enforce_full_delegation_browsertest.cc",
diff --git a/chrome/browser/payments/manifest_verifier_browsertest.cc b/chrome/browser/payments/manifest_verifier_browsertest.cc index 73fb3ad..21b17511 100644 --- a/chrome/browser/payments/manifest_verifier_browsertest.cc +++ b/chrome/browser/payments/manifest_verifier_browsertest.cc
@@ -194,110 +194,6 @@ } } -// A payment handler with "basic-card" payment method name is valid. -IN_PROC_BROWSER_TEST_F(ManifestVerifierBrowserTest, KnownPaymentMethodName) { - { - content::InstalledPaymentAppsFinder::PaymentApps apps; - apps[0] = std::make_unique<content::StoredPaymentApp>(); - apps[0]->scope = GURL("https://bobpay.com/webpay"); - apps[0]->enabled_methods.push_back("basic-card"); - - Verify(std::move(apps)); - - EXPECT_EQ(1U, verified_apps().size()); - ExpectApp(0, "https://bobpay.com/webpay", {"basic-card"}, false); - EXPECT_TRUE(error_message().empty()) << error_message(); - } - - // Repeat verifications should have identical results. - { - content::InstalledPaymentAppsFinder::PaymentApps apps; - apps[0] = std::make_unique<content::StoredPaymentApp>(); - apps[0]->scope = GURL("https://bobpay.com/webpay"); - apps[0]->enabled_methods.push_back("basic-card"); - - Verify(std::move(apps)); - - EXPECT_EQ(1U, verified_apps().size()); - ExpectApp(0, "https://bobpay.com/webpay", {"basic-card"}, false); - EXPECT_TRUE(error_message().empty()) << error_message(); - } -} - -// A payment handler with both "basic-card" and "interledger" payment method -// names is valid. -IN_PROC_BROWSER_TEST_F(ManifestVerifierBrowserTest, - TwoKnownPaymentMethodNames) { - { - content::InstalledPaymentAppsFinder::PaymentApps apps; - apps[0] = std::make_unique<content::StoredPaymentApp>(); - apps[0]->scope = GURL("https://bobpay.com/webpay"); - apps[0]->enabled_methods.push_back("basic-card"); - apps[0]->enabled_methods.push_back("interledger"); - - Verify(std::move(apps)); - - EXPECT_EQ(1U, verified_apps().size()); - ExpectApp(0, "https://bobpay.com/webpay", {"basic-card", "interledger"}, - false); - EXPECT_TRUE(error_message().empty()) << error_message(); - } - - // Repeat verifications should have identical results. - { - content::InstalledPaymentAppsFinder::PaymentApps apps; - apps[0] = std::make_unique<content::StoredPaymentApp>(); - apps[0]->scope = GURL("https://bobpay.com/webpay"); - apps[0]->enabled_methods.push_back("basic-card"); - apps[0]->enabled_methods.push_back("interledger"); - - Verify(std::move(apps)); - - EXPECT_EQ(1U, verified_apps().size()); - ExpectApp(0, "https://bobpay.com/webpay", {"basic-card", "interledger"}, - false); - EXPECT_TRUE(error_message().empty()) << error_message(); - } -} - -// Two payment handlers with "basic-card" payment method names are both valid. -IN_PROC_BROWSER_TEST_F(ManifestVerifierBrowserTest, - TwoAppsWithKnownPaymentMethodNames) { - { - content::InstalledPaymentAppsFinder::PaymentApps apps; - apps[0] = std::make_unique<content::StoredPaymentApp>(); - apps[0]->scope = GURL("https://bobpay.com/webpay"); - apps[0]->enabled_methods.push_back("basic-card"); - apps[1] = std::make_unique<content::StoredPaymentApp>(); - apps[1]->scope = GURL("https://alicepay.com/webpay"); - apps[1]->enabled_methods.push_back("basic-card"); - - Verify(std::move(apps)); - - EXPECT_EQ(2U, verified_apps().size()); - ExpectApp(0, "https://bobpay.com/webpay", {"basic-card"}, false); - ExpectApp(1, "https://alicepay.com/webpay", {"basic-card"}, false); - EXPECT_TRUE(error_message().empty()) << error_message(); - } - - // Repeat verifications should have identical results. - { - content::InstalledPaymentAppsFinder::PaymentApps apps; - apps[0] = std::make_unique<content::StoredPaymentApp>(); - apps[0]->scope = GURL("https://bobpay.com/webpay"); - apps[0]->enabled_methods.push_back("basic-card"); - apps[1] = std::make_unique<content::StoredPaymentApp>(); - apps[1]->scope = GURL("https://alicepay.com/webpay"); - apps[1]->enabled_methods.push_back("basic-card"); - Verify(std::move(apps)); - - EXPECT_EQ(2U, verified_apps().size()); - ExpectApp(0, "https://bobpay.com/webpay", {"basic-card"}, false); - ExpectApp(1, "https://alicepay.com/webpay", {"basic-card"}, false); - EXPECT_TRUE(error_message().empty()) << error_message(); - } -} - // Verify that a payment handler from https://bobpay.com/webpay can not use the // payment method name https://frankpay.com/webpay, because // https://frankpay.com/payment-manifest.json does not explicitly authorize @@ -481,9 +377,9 @@ } } -// Verify that a payment handler from https://alicepay.com/webpay can use all -// three of non-URL payment method name, same-origin URL payment method name, -// and different-origin URL payment method name. +// Verify that a payment handler from https://alicepay.com/webpay can use both +// same-origin URL payment method name and different-origin URL payment method +// name. IN_PROC_BROWSER_TEST_F(ManifestVerifierBrowserTest, ThreeTypesOfMethods) { { content::InstalledPaymentAppsFinder::PaymentApps apps; @@ -497,8 +393,7 @@ EXPECT_EQ(1U, verified_apps().size()); ExpectApp(0, "https://alicepay.com/webpay", - {"basic-card", "https://alicepay.com/webpay2", - "https://ikepay.com/webpay"}, + {"https://alicepay.com/webpay2", "https://ikepay.com/webpay"}, true); EXPECT_TRUE(error_message().empty()) << error_message(); } @@ -516,8 +411,7 @@ EXPECT_EQ(1U, verified_apps().size()); ExpectApp(0, "https://alicepay.com/webpay", - {"basic-card", "https://alicepay.com/webpay2", - "https://ikepay.com/webpay"}, + {"https://alicepay.com/webpay2", "https://ikepay.com/webpay"}, true); EXPECT_TRUE(error_message().empty()) << error_message(); } @@ -602,9 +496,9 @@ } } -// All known payment method names are valid. +// Non-URL payment method names are not valid. IN_PROC_BROWSER_TEST_F(ManifestVerifierBrowserTest, - AllKnownPaymentMethodNames) { + NonUrlPaymentMethodNamesAreNotValid) { { content::InstalledPaymentAppsFinder::PaymentApps apps; apps[0] = std::make_unique<content::StoredPaymentApp>(); @@ -618,11 +512,7 @@ Verify(std::move(apps)); - EXPECT_EQ(1U, verified_apps().size()); - ExpectApp(0, "https://bobpay.com/webpay", - {"basic-card", "interledger", "payee-credit-transfer", - "payer-credit-transfer", "tokenized-card"}, - false); + EXPECT_TRUE(verified_apps().empty()); EXPECT_TRUE(error_message().empty()) << error_message(); } @@ -640,11 +530,7 @@ Verify(std::move(apps)); - EXPECT_EQ(1U, verified_apps().size()); - ExpectApp(0, "https://bobpay.com/webpay", - {"basic-card", "interledger", "payee-credit-transfer", - "payer-credit-transfer", "tokenized-card"}, - false); + EXPECT_TRUE(verified_apps().empty()); EXPECT_TRUE(error_message().empty()) << error_message(); } }
diff --git a/chrome/browser/payments/payment_handler_capabilities_browsertest.cc b/chrome/browser/payments/payment_handler_capabilities_browsertest.cc deleted file mode 100644 index 0351d72c..0000000 --- a/chrome/browser/payments/payment_handler_capabilities_browsertest.cc +++ /dev/null
@@ -1,224 +0,0 @@ -// Copyright 2020 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 <map> -#include <string> - -#include "base/test/scoped_feature_list.h" -#include "build/build_config.h" -#include "chrome/test/payments/payment_request_platform_browsertest_base.h" -#include "chrome/test/payments/payment_request_test_controller.h" -#include "chrome/test/payments/test_event_waiter.h" -#include "content/public/test/browser_test.h" -#include "content/public/test/browser_test_utils.h" -#include "testing/gtest/include/gtest/gtest.h" - -#if defined(OS_ANDROID) -#include "components/payments/content/android/payment_feature_list.h" -#endif // OS_ANDROID - -namespace payments { -namespace { - -constexpr char kOriginalPrice[] = "5.00"; -constexpr char kDiscountPrice[] = "4.00"; - -class PaymentHandlerCapabilitiesTest - : public PaymentRequestPlatformBrowserTestBase { - public: - - void ExpectAppTotals() { - EXPECT_EQ(expected_app_totals_.size(), - test_controller()->app_descriptions().size()); - for (const auto& app : test_controller()->app_descriptions()) { - auto iter = expected_app_totals_.find(app.sublabel); - ASSERT_NE(expected_app_totals_.end(), iter) - << "Origin \"" << app.sublabel << "\" was not expected."; - EXPECT_EQ(iter->second, app.total) - << app.sublabel << " should have a total of \"" << iter->second - << "\", but \"" << app.total << "\" was found instead."; - } - } - - void ExpectModifiedPriceForOrigin(const std::string& origin, - const std::string& value) { - // Android payment apps pre-format the modified value. -#if defined(OS_ANDROID) - expected_app_totals_[origin] = "$" + value; -#else - expected_app_totals_[origin] = "USD " + value; -#endif // OS_ANDROID - } - - void ExpectPriceNotModifiedForOrigin(const std::string& origin, - const std::string& value) { - expected_app_totals_[origin] = "USD " + value; - } - - std::map<std::string, std::string> expected_app_totals_; - base::test::ScopedFeatureList features_; -}; - -// Modified price should be displayed for the payment handler with the matching -// capabilities. -IN_PROC_BROWSER_TEST_F(PaymentHandlerCapabilitiesTest, TwoApps) { - NavigateTo("alicepay.com", "/payment_handler_installer.html"); - EXPECT_EQ( - "success", - content::EvalJs(GetActiveWebContents(), - "installWithCapabilities('alicepay.com/app1/app.js', " - "'basic-card', {supportedNetworks: ['visa']})")); - NavigateTo("bobpay.com", "/payment_handler_installer.html"); - EXPECT_EQ( - "success", - content::EvalJs(GetActiveWebContents(), - "installWithCapabilities('bobpay.com/app1/app.js', " - "'basic-card', {supportedNetworks: ['mastercard']})")); - - ResetEventWaiterForSingleEvent(TestEvent::kAppListReady); - NavigateTo("test.com", - "/payment_request_bobpay_and_basic_card_with_modifiers_test.html"); - EXPECT_TRUE( - content::ExecJs(GetActiveWebContents(), "visaSupportedNetwork()")); - WaitForObservedEvent(); - - ExpectModifiedPriceForOrigin("alicepay.com", kDiscountPrice); - ExpectPriceNotModifiedForOrigin("bobpay.com", kOriginalPrice); - - ExpectAppTotals(); -} - -// A "basic-card" modifier without any networks will apply to a payment handler -// that does not declare its capabilities. -IN_PROC_BROWSER_TEST_F(PaymentHandlerCapabilitiesTest, - AllCardsModifierMatchesAppWithoutCapabilities) { - NavigateTo("bobpay.com", "/payment_handler_installer.html"); - EXPECT_EQ("success", - content::EvalJs(GetActiveWebContents(), - "installWithCapabilities('bobpay.com/app1/app.js', " - "'basic-card', {})")); - - ResetEventWaiterForSingleEvent(TestEvent::kAppListReady); - NavigateTo("test.com", - "/payment_request_bobpay_and_basic_card_with_modifier_optional_" - "data_test.html"); - EXPECT_TRUE( - content::ExecJs(GetActiveWebContents(), "buyWithAllCardsModifier()")); - WaitForObservedEvent(); - - ExpectModifiedPriceForOrigin("bobpay.com", kDiscountPrice); - ExpectAppTotals(); -} - -// A "basic-card" modifier without any networks will apply to a payment handler -// with visa capabilities. -IN_PROC_BROWSER_TEST_F(PaymentHandlerCapabilitiesTest, - AllCardsModifierMatchesVisaCapabilities) { - NavigateTo("bobpay.com", "/payment_handler_installer.html"); - EXPECT_EQ("success", - content::EvalJs(GetActiveWebContents(), - "installWithCapabilities('bobpay.com/app1/app.js', " - "'basic-card', {supportedNetworks: ['visa']})")); - - ResetEventWaiterForSingleEvent(TestEvent::kAppListReady); - NavigateTo("test.com", - "/payment_request_bobpay_and_basic_card_with_modifier_optional_" - "data_test.html"); - EXPECT_TRUE( - content::ExecJs(GetActiveWebContents(), "buyWithAllCardsModifier()")); - WaitForObservedEvent(); - - ExpectModifiedPriceForOrigin("bobpay.com", kDiscountPrice); - ExpectAppTotals(); -} - -// A "basic-card" modifier with visa network will not apply to a payment handler -// that does not declare its capabilities. -IN_PROC_BROWSER_TEST_F(PaymentHandlerCapabilitiesTest, - VisaCardsModifierDoesNotMatchAppWithoutCapabilities) { - NavigateTo("bobpay.com", "/payment_handler_installer.html"); - EXPECT_EQ("success", - content::EvalJs(GetActiveWebContents(), - "installWithCapabilities('bobpay.com/app1/app.js', " - "'basic-card', {})")); - - ResetEventWaiterForSingleEvent(TestEvent::kAppListReady); - NavigateTo("test.com", - "/payment_request_bobpay_and_basic_card_with_modifier_optional_" - "data_test.html"); - EXPECT_TRUE(content::ExecJs(GetActiveWebContents(), "buyWithVisaModifier()")); - WaitForObservedEvent(); - - ExpectPriceNotModifiedForOrigin("bobpay.com", kOriginalPrice); - ExpectAppTotals(); -} - -// A "basic-card" modifier with visa network will apply to a payment handler -// with visa capabilities. -IN_PROC_BROWSER_TEST_F(PaymentHandlerCapabilitiesTest, - VisaCardsModifierMatchesVisaCapabilities) { - NavigateTo("bobpay.com", "/payment_handler_installer.html"); - EXPECT_EQ("success", - content::EvalJs(GetActiveWebContents(), - "installWithCapabilities('bobpay.com/app1/app.js', " - "'basic-card', {supportedNetworks: ['visa']})")); - - ResetEventWaiterForSingleEvent(TestEvent::kAppListReady); - NavigateTo("test.com", - "/payment_request_bobpay_and_basic_card_with_modifier_optional_" - "data_test.html"); - EXPECT_TRUE(content::ExecJs(GetActiveWebContents(), "buyWithVisaModifier()")); - WaitForObservedEvent(); - - ExpectModifiedPriceForOrigin("bobpay.com", kDiscountPrice); - ExpectAppTotals(); -} - -// A "basic-card" modifier without any networks will apply to a payment handler -// with mastercard capabilities. -IN_PROC_BROWSER_TEST_F(PaymentHandlerCapabilitiesTest, - AllCardsModifierMatchesMastercardCapabilities) { - NavigateTo("bobpay.com", "/payment_handler_installer.html"); - EXPECT_EQ( - "success", - content::EvalJs(GetActiveWebContents(), - "installWithCapabilities('bobpay.com/app1/app.js', " - "'basic-card', {supportedNetworks: ['mastercard']})")); - - ResetEventWaiterForSingleEvent(TestEvent::kAppListReady); - NavigateTo("test.com", - "/payment_request_bobpay_and_basic_card_with_modifier_optional_" - "data_test.html"); - EXPECT_TRUE( - content::ExecJs(GetActiveWebContents(), "buyWithAllCardsModifier()")); - WaitForObservedEvent(); - - ExpectModifiedPriceForOrigin("bobpay.com", kDiscountPrice); - ExpectAppTotals(); -} - -// A "basic-card" modifier with visa network will not apply to a payment handler -// with mastercard capabilities. -IN_PROC_BROWSER_TEST_F(PaymentHandlerCapabilitiesTest, - VisaCardsModifierDoesNotMatchMastercardCapabilities) { - NavigateTo("bobpay.com", "/payment_handler_installer.html"); - EXPECT_EQ( - "success", - content::EvalJs(GetActiveWebContents(), - "installWithCapabilities('bobpay.com/app1/app.js', " - "'basic-card', {supportedNetworks: ['mastercard']})")); - - ResetEventWaiterForSingleEvent(TestEvent::kAppListReady); - NavigateTo("test.com", - "/payment_request_bobpay_and_basic_card_with_modifier_optional_" - "data_test.html"); - EXPECT_TRUE(content::ExecJs(GetActiveWebContents(), "buyWithVisaModifier()")); - WaitForObservedEvent(); - - ExpectPriceNotModifiedForOrigin("bobpay.com", kOriginalPrice); - ExpectAppTotals(); -} - -} // namespace -} // namespace payments
diff --git a/chrome/browser/payments/payment_handler_uninstall_browsertest.cc b/chrome/browser/payments/payment_handler_uninstall_browsertest.cc index e66c316..06f03ef 100644 --- a/chrome/browser/payments/payment_handler_uninstall_browsertest.cc +++ b/chrome/browser/payments/payment_handler_uninstall_browsertest.cc
@@ -38,30 +38,6 @@ WaitForObservedEvent(); } -IN_PROC_BROWSER_TEST_F(PaymentHandlerUninstallTest, BasicCard) { - EXPECT_EQ("success", - content::EvalJs(GetActiveWebContents(), "install('basic-card')")); - - // Launch the payment request and validate that one app is available. - ResetEventWaiterForSingleEvent(TestEvent::kAppListReady); - EXPECT_EQ("success", content::EvalJs(GetActiveWebContents(), - "launchWithoutWaitForResponse()")); - WaitForObservedEvent(); - EXPECT_EQ(1u, test_controller()->app_descriptions().size()); - - EXPECT_EQ("success", content::EvalJs(GetActiveWebContents(), "abort()")); - - // Uninstall the payment app and verify that there is no payment app - // available. A new request.show() will not get rejected though since the user - // will still have the option to add a credit card. - EXPECT_EQ("success", content::EvalJs(GetActiveWebContents(), "uninstall()")); - ResetEventWaiterForSingleEvent(TestEvent::kAppListReady); - EXPECT_EQ("success", content::EvalJs(GetActiveWebContents(), - "launchWithoutWaitForResponse()")); - WaitForObservedEvent(); - EXPECT_EQ(0u, test_controller()->app_descriptions().size()); -} - } // namespace } // namespace payments
diff --git a/chrome/browser/payments/service_worker_payment_app_finder_browsertest.cc b/chrome/browser/payments/service_worker_payment_app_finder_browsertest.cc index bf026ec..3994d9e0 100644 --- a/chrome/browser/payments/service_worker_payment_app_finder_browsertest.cc +++ b/chrome/browser/payments/service_worker_payment_app_finder_browsertest.cc
@@ -410,32 +410,6 @@ } } -// A payment app can use "basic-card" payment method. -IN_PROC_BROWSER_TEST_F(ServiceWorkerPaymentAppFinderBrowserTest, BasicCard) { - InstallPaymentAppForMethod("basic-card"); - - { - GetAllPaymentAppsForMethods({"basic-card", "https://alicepay.com/webpay", - "https://bobpay.com/webpay"}); - - EXPECT_TRUE(installable_apps().empty()); - ASSERT_EQ(1U, apps().size()); - ExpectPaymentAppWithMethod("basic-card"); - EXPECT_TRUE(error_message().empty()) << error_message(); - } - - // Repeat lookups should have identical results. - { - GetAllPaymentAppsForMethods({"basic-card", "https://alicepay.com/webpay", - "https://bobpay.com/webpay"}); - - EXPECT_TRUE(installable_apps().empty()); - ASSERT_EQ(1U, apps().size()); - ExpectPaymentAppWithMethod("basic-card"); - EXPECT_TRUE(error_message().empty()) << error_message(); - } -} - // A payment app can use any payment method name from its own origin. IN_PROC_BROWSER_TEST_F(ServiceWorkerPaymentAppFinderBrowserTest, OwnOrigin) { InstallPaymentAppForMethod("https://alicepay.com/webpay");
diff --git a/chrome/browser/profiles/profile_manager.cc b/chrome/browser/profiles/profile_manager.cc index 4e06d60..8ba6989 100644 --- a/chrome/browser/profiles/profile_manager.cc +++ b/chrome/browser/profiles/profile_manager.cc
@@ -569,10 +569,9 @@ // Make a copy because the list might change in the calls to GetProfile. std::unique_ptr<base::ListValue> profile_list( local_state->GetList(prefs::kProfilesLastActive)->DeepCopy()); - base::ListValue::const_iterator it; - for (it = profile_list->begin(); it != profile_list->end(); ++it) { + for (const auto& entry : profile_list->GetList()) { std::string profile_base_name; - if (!it->GetAsString(&profile_base_name) || profile_base_name.empty() || + if (!entry.GetAsString(&profile_base_name) || profile_base_name.empty() || profile_base_name == base::FilePath(chrome::kSystemProfileDir).AsUTF8Unsafe()) { LOG(WARNING) << "Invalid entry in " << prefs::kProfilesLastActive; @@ -1107,7 +1106,7 @@ local_state->GetList(prefs::kProfilesDeleted); DCHECK(deleted_profiles); - for (const base::Value& value : *deleted_profiles) { + for (const base::Value& value : deleted_profiles->GetList()) { base::Optional<base::FilePath> profile_path = util::ValueToFilePath(value); // Although it should never happen, make sure this is a valid path in the // user_data_dir, so we don't accidentally delete something else.
diff --git a/chrome/browser/renderer_context_menu/accessibility_labels_menu_observer_browsertest.cc b/chrome/browser/renderer_context_menu/accessibility_labels_menu_observer_browsertest.cc index 4740cc2..1c14440 100644 --- a/chrome/browser/renderer_context_menu/accessibility_labels_menu_observer_browsertest.cc +++ b/chrome/browser/renderer_context_menu/accessibility_labels_menu_observer_browsertest.cc
@@ -95,7 +95,7 @@ ash::AccessibilityManager::Get()->EnableSpokenFeedback(true); #else // Spoof a screen reader. - content::BrowserAccessibilityState::GetInstance()->AddAccessibilityModeFlags( + content::testing::ScopedContentAXModeSetter scoped_accessibility_mode( ui::AXMode::kScreenReader); #endif // BUILDFLAG(IS_CHROMEOS_ASH) menu()->GetPrefs()->SetBoolean(prefs::kAccessibilityImageLabelsEnabled,
diff --git a/chrome/browser/renderer_context_menu/render_view_context_menu_browsertest.cc b/chrome/browser/renderer_context_menu/render_view_context_menu_browsertest.cc index d3ddfb74..76379733 100644 --- a/chrome/browser/renderer_context_menu/render_view_context_menu_browsertest.cc +++ b/chrome/browser/renderer_context_menu/render_view_context_menu_browsertest.cc
@@ -215,8 +215,9 @@ auto web_app_info = std::make_unique<WebApplicationInfo>(); web_app_info->start_url = start_url; web_app_info->scope = start_url; - web_app_info->title = u"Test app 🐐"; - web_app_info->description = u"Test description 🐐"; + web_app_info->title = base::UTF8ToUTF16("Test app \xF0\x9F\x90\x90"); + web_app_info->description = + base::UTF8ToUTF16("Test description \xF0\x9F\x90\x90"); web_app_info->open_as_window = open_as_window; return web_app::test::InstallWebApp(browser()->profile(),
diff --git a/chrome/browser/resources/settings/basic_page/basic_page.html b/chrome/browser/resources/settings/basic_page/basic_page.html index f36c113b..5fce87a 100644 --- a/chrome/browser/resources/settings/basic_page/basic_page.html +++ b/chrome/browser/resources/settings/basic_page/basic_page.html
@@ -54,6 +54,10 @@ iron-icon { margin-inline-start: 16px; } + + :host-context([enable-landing-page-redesign]):host(:not([in-search-mode])) settings-section:not([active]) { + display: none; + } </style> <template is="dom-if" if="[[showBasicPage_( currentRoute_, inSearchMode, hasExpandedSection_)]]">
diff --git a/chrome/browser/resources/settings/basic_page/basic_page.js b/chrome/browser/resources/settings/basic_page/basic_page.js index 2ca28b8..68bd70b4 100644 --- a/chrome/browser/resources/settings/basic_page/basic_page.js +++ b/chrome/browser/resources/settings/basic_page/basic_page.js
@@ -348,7 +348,8 @@ * @private */ showAdvancedToggle_(inSearchMode, hasExpandedSection) { - return !inSearchMode && !hasExpandedSection; + return !inSearchMode && !hasExpandedSection && + !loadTimeData.getBoolean('enableLandingPageRedesign'); }, /**
diff --git a/chrome/browser/resources/settings/settings.html b/chrome/browser/resources/settings/settings.html index 51e035b0..af261fd 100644 --- a/chrome/browser/resources/settings/settings.html +++ b/chrome/browser/resources/settings/settings.html
@@ -1,5 +1,6 @@ <!doctype html> -<html dir="$i18n{textdirection}" lang="$i18n{language}" class="loading"> +<html dir="$i18n{textdirection}" lang="$i18n{language}" class="loading" + $i18n{enableLandingPageRedesignAttribute}> <head> <meta charset="utf-8"> <meta name="color-scheme" content="light dark">
diff --git a/chrome/browser/resources/settings/settings_page/BUILD.gn b/chrome/browser/resources/settings/settings_page/BUILD.gn index f1bffe2..ab04e02 100644 --- a/chrome/browser/resources/settings/settings_page/BUILD.gn +++ b/chrome/browser/resources/settings/settings_page/BUILD.gn
@@ -20,6 +20,7 @@ js_library("main_page_behavior") { deps = [ ":settings_section", + "..:route", "..:router", "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", "//ui/webui/resources/js:assert.m",
diff --git a/chrome/browser/resources/settings/settings_page/main_page_behavior.js b/chrome/browser/resources/settings/settings_page/main_page_behavior.js index 3daaaab..609d5c7 100644 --- a/chrome/browser/resources/settings/settings_page/main_page_behavior.js +++ b/chrome/browser/resources/settings/settings_page/main_page_behavior.js
@@ -5,8 +5,11 @@ // clang-format off import {assert} from 'chrome://resources/js/assert.m.js'; import {beforeNextRender} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; + import {ensureLazyLoaded} from '../ensure_lazy_loaded.js'; -import {Route, Router, MinimumRoutes} from '../router.js'; +import {loadTimeData} from '../i18n_setup.js'; +import {routes} from '../route.js'; +import {MinimumRoutes, Route, Router} from '../router.js'; // clang-format on /** @@ -28,6 +31,9 @@ TOP_LEVEL: 'top-level', }; + /** @type {!Route} */ + const TOP_LEVEL_EQUIVALENT_ROUTE = routes.PEOPLE; + /** * @param {?Route} route * @return {!RouteState} @@ -67,6 +73,7 @@ type: Boolean, value: false, observer: 'inSearchModeChanged_', + reflectToAttribute: true, }, }, @@ -247,6 +254,24 @@ }, /** + * Shows the section corresponding to |newRoute| and hides the previously + * |active| section (if any). + * @param {!Route} newRoute + */ + switchToSection_(newRoute) { + this.ensureSectionForRoute_(newRoute).then(section => { + // Clear any previously |active| section. + const oldSection = this.$$(`settings-section[active]`); + if (oldSection) { + oldSection.toggleAttribute('active', false); + } + + section.toggleAttribute('active', true); + this.fire('show-container'); + }); + }, + + /** * Detects which state transition is appropriate for the given new/old * routes. * @param {!Route} newRoute @@ -297,6 +322,20 @@ const newState = transition[1]; assert(this.validTransitions_.get(oldState).has(newState)); + loadTimeData.getBoolean('enableLandingPageRedesign') ? + this.processTransitionRedesign_( + oldRoute, newRoute, oldState, newState) : + this.processTransition_(oldRoute, newRoute, oldState, newState); + }, + + /** + * @param {Route} oldRoute + * @param {!Route} newRoute + * @param {!RouteState} oldState + * @param {!RouteState} newState + * @private + */ + processTransition_(oldRoute, newRoute, oldState, newState) { if (oldState === RouteState.TOP_LEVEL) { if (newState === RouteState.SECTION) { this.scrollToSection_(newRoute); @@ -323,7 +362,7 @@ if (oldState === RouteState.SUBPAGE) { if (newState === RouteState.SECTION) { - this.enterMainPage_(oldRoute); + this.enterMainPage_(/** @type {!Route} */ (oldRoute)); // Scroll to the corresponding section, only if the user explicitly // navigated to a section (via the menu). @@ -350,7 +389,7 @@ // position is automatically restored, because we focus the // sub-subpage entry point. } else if (newState === RouteState.TOP_LEVEL) { - this.enterMainPage_(oldRoute); + this.enterMainPage_(/** @type {!Route} */ (oldRoute)); } return; } @@ -369,6 +408,86 @@ }, /** + * @param {Route} oldRoute + * @param {!Route} newRoute + * @param {!RouteState} oldState + * @param {!RouteState} newState + * @private + */ + processTransitionRedesign_(oldRoute, newRoute, oldState, newState) { + if (oldState === RouteState.TOP_LEVEL) { + if (newState === RouteState.SECTION) { + this.switchToSection_(newRoute); + } else if (newState === RouteState.SUBPAGE) { + this.enterSubpage_(newRoute); + } else if (newState === RouteState.TOP_LEVEL) { + // Case when navigating from '/?search=foo' to '/' (clearing search + // results). + this.switchToSection_(TOP_LEVEL_EQUIVALENT_ROUTE); + } + // Nothing to do here for the case of RouteState.DIALOG. + return; + } + + if (oldState === RouteState.SECTION) { + if (newState === RouteState.SECTION) { + this.switchToSection_(newRoute); + } else if (newState === RouteState.SUBPAGE) { + this.switchToSection_(newRoute); + this.enterSubpage_(newRoute); + } else if (newState === RouteState.TOP_LEVEL) { + this.switchToSection_(TOP_LEVEL_EQUIVALENT_ROUTE); + this.scroller.scrollTop = 0; + } + // Nothing to do here for the case of RouteState.DIALOG. + return; + } + + if (oldState === RouteState.SUBPAGE) { + if (newState === RouteState.SECTION) { + this.enterMainPage_(/** @type {!Route} */ (oldRoute)); + this.switchToSection_(newRoute); + } else if (newState === RouteState.SUBPAGE) { + // Handle case where the two subpages belong to + // different sections, but are linked to each other. For example + // /storage and /accounts (in ChromeOS). + if (!oldRoute.contains(newRoute) && !newRoute.contains(oldRoute)) { + this.enterMainPage_(oldRoute).then(() => { + this.enterSubpage_(newRoute); + }); + return; + } + + // Handle case of subpage to sub-subpage navigation. + if (oldRoute.contains(newRoute)) { + this.scroller.scrollTop = 0; + return; + } + // When going from a sub-subpage to its parent subpage, scroll + // position is automatically restored, because we focus the + // sub-subpage entry point. + } else if (newState === RouteState.TOP_LEVEL) { + this.enterMainPage_(/** @type {!Route} */ (oldRoute)); + } + return; + } + + if (oldState === RouteState.INITIAL) { + if ([RouteState.SECTION, RouteState.DIALOG].includes(newState)) { + this.switchToSection_(newRoute); + } else if (newState === RouteState.SUBPAGE) { + this.switchToSection_(newRoute); + this.enterSubpage_(newRoute); + } else if (newState === RouteState.TOP_LEVEL) { + this.switchToSection_(TOP_LEVEL_EQUIVALENT_ROUTE); + } + return; + } + + // Nothing to do for when oldState === RouteState.DIALOG. + }, + + /** * TODO(dpapad): Rename this to |querySection| to distinguish it from * ensureSectionForRoute_() which force-renders the section as needed. * Helper function to get a section from the local DOM.
diff --git a/chrome/browser/search_engines/template_url_fetcher_unittest.cc b/chrome/browser/search_engines/template_url_fetcher_unittest.cc index f48bc5e6..134c466 100644 --- a/chrome/browser/search_engines/template_url_fetcher_unittest.cc +++ b/chrome/browser/search_engines/template_url_fetcher_unittest.cc
@@ -31,6 +31,8 @@ namespace { +using base::ASCIIToUTF16; + constexpr int32_t kRequestID = 10; bool GetTestFilePath(const std::string& file_name, base::FilePath* path) { @@ -297,7 +299,8 @@ WaitForDownloadToFinish(); const TemplateURL* t_url = test_util()->model()->GetTemplateURLForKeyword(keyword); - EXPECT_EQ(u"тест", t_url->short_name()); + EXPECT_EQ(base::UTF8ToUTF16("\xd1\x82\xd0\xb5\xd1\x81\xd1\x82"), + t_url->short_name()); } } // namespace
diff --git a/chrome/browser/search_engines/template_url_service_sync_unittest.cc b/chrome/browser/search_engines/template_url_service_sync_unittest.cc index 9442e9a0..fff3861 100644 --- a/chrome/browser/search_engines/template_url_service_sync_unittest.cc +++ b/chrome/browser/search_engines/template_url_service_sync_unittest.cc
@@ -34,8 +34,10 @@ #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" +using base::ASCIIToUTF16; using base::Time; using base::TimeDelta; +using base::UTF8ToUTF16; using testing::NotNull; namespace { @@ -969,8 +971,9 @@ GURL google_url(model()->search_terms_data().GoogleBaseURLValue()); TemplateURL* guid2 = model()->GetTemplateURLForHost(google_url.host()); ASSERT_THAT(guid2, NotNull()); - std::string google_keyword(url_formatter::StripWWW(google_url.host())); - EXPECT_EQ(base::ASCIIToUTF16(google_keyword), guid2->keyword()); + std::u16string google_keyword( + base::ASCIIToUTF16(url_formatter::StripWWW(google_url.host()))); + EXPECT_EQ(google_keyword, guid2->keyword()); // We should also have gotten some corresponding UPDATEs pushed upstream. EXPECT_GE(processor()->change_list_size(), 2U); @@ -981,19 +984,18 @@ ASSERT_TRUE(processor()->contains_guid("guid2")); syncer::SyncChange guid2_change = processor()->change_for_guid("guid2"); EXPECT_EQ(syncer::SyncChange::ACTION_UPDATE, guid2_change.change_type()); - EXPECT_EQ(google_keyword, GetKeyword(guid2_change.sync_data())); + EXPECT_EQ(google_keyword, UTF8ToUTF16(GetKeyword(guid2_change.sync_data()))); } TEST_F(TemplateURLServiceSyncTest, AutogeneratedKeywordConflicts) { // Sync brings in some autogenerated keywords, but the generated keywords we // try to create conflict with ones in the model. - std::string google_keyword(url_formatter::StripWWW( - GURL(model()->search_terms_data().GoogleBaseURLValue()).host())); - std::u16string google_keyword16(base::ASCIIToUTF16(google_keyword)); + std::u16string google_keyword(base::ASCIIToUTF16(url_formatter::StripWWW( + GURL(model()->search_terms_data().GoogleBaseURLValue()).host()))); const std::string local_google_url = "{google:baseURL}1/search?q={searchTerms}"; TemplateURL* google = - model()->Add(CreateTestTemplateURL(google_keyword16, local_google_url)); + model()->Add(CreateTestTemplateURL(google_keyword, local_google_url)); TemplateURL* other = model()->Add(CreateTestTemplateURL(u"other.com", "http://other.com/foo")); syncer::SyncDataList initial_data; @@ -1022,8 +1024,7 @@ // the sync TemplateURLs (GUIDs transferred over). EXPECT_FALSE(model()->GetTemplateURLForGUID(local_google_guid)); ASSERT_TRUE(model()->GetTemplateURLForGUID("sync1")); - EXPECT_EQ(google_keyword16, - model()->GetTemplateURLForGUID("sync1")->keyword()); + EXPECT_EQ(google_keyword, model()->GetTemplateURLForGUID("sync1")->keyword()); EXPECT_FALSE(model()->GetTemplateURLForGUID(local_other_guid)); ASSERT_TRUE(model()->GetTemplateURLForGUID("sync2")); EXPECT_EQ(u"other.com", model()->GetTemplateURLForGUID("sync2")->keyword()); @@ -1034,7 +1035,7 @@ ASSERT_TRUE(processor()->contains_guid("sync1")); syncer::SyncChange sync1_change = processor()->change_for_guid("sync1"); EXPECT_EQ(syncer::SyncChange::ACTION_UPDATE, sync1_change.change_type()); - EXPECT_EQ(google_keyword, GetKeyword(sync1_change.sync_data())); + EXPECT_EQ(google_keyword, UTF8ToUTF16(GetKeyword(sync1_change.sync_data()))); EXPECT_EQ(local_google_url, GetURL(sync1_change.sync_data())); ASSERT_TRUE(processor()->contains_guid("sync2")); syncer::SyncChange sync2_change = processor()->change_for_guid("sync2"); @@ -1764,8 +1765,7 @@ } TEST_F(TemplateURLServiceSyncTest, PreSyncUpdates) { - const char kNewKeyword[] = "somethingnew"; - const char16_t kNewKeyword16[] = u"somethingnew"; + const char* kNewKeyword = "somethingnew"; // Fetch the prepopulate search engines so we know what they are. std::vector<std::unique_ptr<TemplateURLData>> prepop_turls = TemplateURLPrepopulateData::GetPrepopulatedEngines( @@ -1780,7 +1780,7 @@ TemplateURLData data_copy(*prepop_turls[0]); data_copy.last_modified = Time::FromTimeT(10); std::u16string original_keyword = data_copy.keyword(); - data_copy.SetKeyword(kNewKeyword16); + data_copy.SetKeyword(ASCIIToUTF16(kNewKeyword)); // Set safe_for_autoreplace to false so our keyword survives. data_copy.safe_for_autoreplace = false; model()->Add(std::make_unique<TemplateURL>(data_copy)); @@ -1792,7 +1792,8 @@ // The newly added search engine should have been safely merged, with an // updated time. - TemplateURL* added_turl = model()->GetTemplateURLForKeyword(kNewKeyword16); + TemplateURL* added_turl = model()->GetTemplateURLForKeyword( + ASCIIToUTF16(kNewKeyword)); ASSERT_TRUE(added_turl); base::Time new_timestamp = added_turl->last_modified(); EXPECT_GE(new_timestamp, pre_merge_time); @@ -1817,7 +1818,8 @@ EXPECT_EQ(prepop_turls.size(), model()->GetAllSyncData(syncer::SEARCH_ENGINES).size()); - ASSERT_EQ(added_turl, model()->GetTemplateURLForKeyword(kNewKeyword16)); + ASSERT_EQ(added_turl, model()->GetTemplateURLForKeyword( + ASCIIToUTF16(kNewKeyword))); EXPECT_EQ(new_timestamp, added_turl->last_modified()); syncer::SyncChange change = processor()->change_for_guid(sync_guid); EXPECT_EQ(syncer::SyncChange::ACTION_UPDATE, change.change_type()); @@ -2546,6 +2548,7 @@ } TEST_F(TemplateURLServiceSyncTest, NonAsciiKeywordDoesNotCrash) { - model()->Add(CreateTestTemplateURL(u"\U0002f98d", "http://key1.com")); + model()->Add(CreateTestTemplateURL(UTF8ToUTF16("\xf0\xaf\xa6\x8d"), + "http://key1.com")); MergeAndExpectNotify(CreateInitialSyncData(), 1); }
diff --git a/chrome/browser/sharing/shared_clipboard/shared_clipboard_ui_controller_unittest.cc b/chrome/browser/sharing/shared_clipboard/shared_clipboard_ui_controller_unittest.cc index ecc05b5..4cea4de 100644 --- a/chrome/browser/sharing/shared_clipboard/shared_clipboard_ui_controller_unittest.cc +++ b/chrome/browser/sharing/shared_clipboard/shared_clipboard_ui_controller_unittest.cc
@@ -33,7 +33,7 @@ namespace { -const char16_t kText[] = u"Text to be copied"; +const char kText[] = "Text to be copied"; const char kExpectedText[] = "Text to be copied"; const char kReceiverGuid[] = "test_receiver_guid"; const char kReceiverName[] = "test_receiver_name"; @@ -54,7 +54,7 @@ CreateFakeDeviceInfo(kReceiverGuid, kReceiverName); controller_ = SharedClipboardUiController::GetOrCreateFromWebContents( web_contents_.get()); - controller_->OnDeviceSelected(kText, *device_info.get()); + controller_->OnDeviceSelected(base::UTF8ToUTF16(kText), *device_info.get()); } protected:
diff --git a/chrome/browser/signin/dice_signed_in_profile_creator_unittest.cc b/chrome/browser/signin/dice_signed_in_profile_creator_unittest.cc index 35974468..af43e3c 100644 --- a/chrome/browser/signin/dice_signed_in_profile_creator_unittest.cc +++ b/chrome/browser/signin/dice_signed_in_profile_creator_unittest.cc
@@ -29,7 +29,7 @@ namespace { -const char16_t kProfileTestName[] = u"profile_test_name"; +const char kProfileTestName[] = "profile_test_name"; std::unique_ptr<TestingProfile> BuildTestingProfile(const base::FilePath& path, Profile::Delegate* delegate, @@ -165,11 +165,12 @@ AccountInfo account_info = identity_test_env()->MakeAccountAvailable("bob@example.com"); size_t kTestIcon = profiles::GetModernAvatarIconStartIndex(); + std::u16string kProfileTestName16 = base::UTF8ToUTF16(kProfileTestName); base::RunLoop loop; std::unique_ptr<DiceSignedInProfileCreator> creator = std::make_unique<DiceSignedInProfileCreator>( - profile(), account_info.account_id, kProfileTestName, kTestIcon, + profile(), account_info.account_id, kProfileTestName16, kTestIcon, use_guest_profile(), base::BindOnce(&DiceSignedInProfileCreatorTest::OnProfileCreated, base::Unretained(this), loop.QuitClosure())); @@ -200,7 +201,7 @@ ASSERT_TRUE(entry); ASSERT_EQ(entry->IsGuest(), use_guest_profile()); if (!use_guest_profile()) { - EXPECT_EQ(kProfileTestName, entry->GetLocalProfileName()); + EXPECT_EQ(kProfileTestName16, entry->GetLocalProfileName()); EXPECT_EQ(kTestIcon, entry->GetAvatarIconIndex()); } }
diff --git a/chrome/browser/signin/signin_global_error_unittest.cc b/chrome/browser/signin/signin_global_error_unittest.cc index ff400754..36746f5 100644 --- a/chrome/browser/signin/signin_global_error_unittest.cc +++ b/chrome/browser/signin/signin_global_error_unittest.cc
@@ -35,7 +35,6 @@ #include "testing/gtest/include/gtest/gtest.h" static const char kTestEmail[] = "testuser@test.com"; -static const char16_t kTestEmail16[] = u"testuser@test.com"; class SigninGlobalErrorTest : public testing::Test { public: @@ -65,7 +64,7 @@ ->GetProfileAttributesWithPath(profile()->GetPath()); ASSERT_NE(entry, nullptr); - entry->SetAuthInfo(account_info.gaia, kTestEmail16, + entry->SetAuthInfo(account_info.gaia, base::UTF8ToUTF16(kTestEmail), /*is_consented_primary_account=*/true); global_error_ = SigninGlobalErrorFactory::GetForProfile(profile());
diff --git a/chrome/browser/signin/ui/android/BUILD.gn b/chrome/browser/signin/ui/android/BUILD.gn index c7fa875..9cefcf7 100644 --- a/chrome/browser/signin/ui/android/BUILD.gn +++ b/chrome/browser/signin/ui/android/BUILD.gn
@@ -162,7 +162,6 @@ "java/src/org/chromium/chrome/browser/signin/ui/ConfirmManagedSyncDataDialogIntegrationTest.java", "java/src/org/chromium/chrome/browser/signin/ui/ConfirmSyncDataIntegrationTest.java", "java/src/org/chromium/chrome/browser/signin/ui/SignOutDialogRenderTest.java", - "java/src/org/chromium/chrome/browser/signin/ui/SigninCheckerTest.java", "java/src/org/chromium/chrome/browser/signin/ui/account_picker/AccountPickerBottomSheetRenderTest.java", "java/src/org/chromium/chrome/browser/signin/ui/account_picker/AccountPickerBottomSheetTest.java", "java/src/org/chromium/chrome/browser/signin/ui/account_picker/AccountPickerDialogTest.java", @@ -181,6 +180,7 @@ "//chrome/browser/ui/android/night_mode:night_mode_java_test_support", "//chrome/test/android:chrome_java_test_support", "//components/browser_ui/bottomsheet/android:java", + "//components/externalauth/android:java", "//components/signin/core/browser:signin_enums_java", "//components/signin/public/android:java", "//components/signin/public/android:signin_java_test_support",
diff --git a/chrome/browser/signin/ui/android/DEPS b/chrome/browser/signin/ui/android/DEPS index 935b8d3..d0bd062d 100644 --- a/chrome/browser/signin/ui/android/DEPS +++ b/chrome/browser/signin/ui/android/DEPS
@@ -7,4 +7,7 @@ : [ "+content/public/android/java/src/org/chromium/content_public/browser/LoadUrlParams.java" ], + "SigninCheckerTest.java": [ + "+components/externalauth/android/java/src/org/chromium/components/externalauth/ExternalAuthUtils.java" + ], }
diff --git a/chrome/browser/signin/ui/android/java/src/org/chromium/chrome/browser/signin/ui/SigninCheckerTest.java b/chrome/browser/signin/ui/android/java/src/org/chromium/chrome/browser/signin/ui/SigninCheckerTest.java deleted file mode 100644 index 2a51a9a..0000000 --- a/chrome/browser/signin/ui/android/java/src/org/chromium/chrome/browser/signin/ui/SigninCheckerTest.java +++ /dev/null
@@ -1,121 +0,0 @@ -// Copyright 2021 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. - -package org.chromium.chrome.browser.signin.ui; - -import static org.mockito.Mockito.when; - -import android.os.Build.VERSION_CODES; - -import androidx.test.filters.MediumTest; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.mockito.quality.Strictness; - -import org.chromium.base.test.util.CommandLineFlags; -import org.chromium.base.test.util.CriteriaHelper; -import org.chromium.base.test.util.DisableIf; -import org.chromium.chrome.browser.flags.ChromeFeatureList; -import org.chromium.chrome.browser.flags.ChromeSwitches; -import org.chromium.chrome.browser.profiles.Profile; -import org.chromium.chrome.browser.signin.services.IdentityServicesProvider; -import org.chromium.chrome.test.ChromeJUnit4ClassRunner; -import org.chromium.chrome.test.ChromeTabbedActivityTestRule; -import org.chromium.chrome.test.util.browser.Features; -import org.chromium.chrome.test.util.browser.signin.AccountManagerTestRule; -import org.chromium.components.signin.AccountRenameChecker; -import org.chromium.components.signin.base.CoreAccountInfo; - -/** - * This class tests the sign-in checks done at Chrome start-up or when accounts - * change on device. - */ -@RunWith(ChromeJUnit4ClassRunner.class) -@CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE}) -@Features.DisableFeatures({ChromeFeatureList.DEPRECATE_MENAGERIE_API}) -@DisableIf.Build(sdk_is_less_than = VERSION_CODES.LOLLIPOP_MR1) -public class SigninCheckerTest { - @Rule - public final MockitoRule mMockitoRule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS); - - @Rule - public final AccountManagerTestRule mAccountManagerTestRule = new AccountManagerTestRule(); - - @Rule - public final ChromeTabbedActivityTestRule mActivityTestRule = - new ChromeTabbedActivityTestRule(); - - @Mock - private AccountRenameChecker.Delegate mAccountRenameCheckerDelegateMock; - - @Before - public void setUp() { - AccountRenameChecker.overrideDelegateForTests(mAccountRenameCheckerDelegateMock); - mActivityTestRule.startMainActivityOnBlankPage(); - } - - @Test - @MediumTest - public void signinWhenPrimaryAccountIsRenamedToAKnownAccount() { - mAccountManagerTestRule.addAccountAndWaitForSeeding("the.second.account@gmail.com"); - final CoreAccountInfo oldAccount = - mAccountManagerTestRule.addTestAccountThenSigninAndEnableSync(); - final String newAccountEmail = "test.new.account@gmail.com"; - when(mAccountRenameCheckerDelegateMock.getNewNameOfRenamedAccount(oldAccount.getEmail())) - .thenReturn(newAccountEmail); - final CoreAccountInfo expectedPrimaryAccount = - mAccountManagerTestRule.addAccount(newAccountEmail); - - mAccountManagerTestRule.removeAccount(oldAccount.getEmail()); - - CriteriaHelper.pollUiThread(() -> { - return expectedPrimaryAccount.equals( - mAccountManagerTestRule.getCurrentSignedInAccount()); - }); - } - - @Test - @MediumTest - public void signoutWhenPrimaryAccountIsRenamedToAnUnknownAccount() { - mAccountManagerTestRule.addAccountAndWaitForSeeding("the.second.account@gmail.com"); - final CoreAccountInfo oldAccount = - mAccountManagerTestRule.addTestAccountThenSigninAndEnableSync(); - final String newAccountEmail = "test.new.account@gmail.com"; - when(mAccountRenameCheckerDelegateMock.getNewNameOfRenamedAccount(oldAccount.getEmail())) - .thenReturn(newAccountEmail); - - mAccountManagerTestRule.removeAccount(oldAccount.getEmail()); - - CriteriaHelper.pollUiThread(() -> { - return !IdentityServicesProvider.get() - .getIdentityManager(Profile.getLastUsedRegularProfile()) - .hasPrimaryAccount(); - }); - Assert.assertNull(mAccountManagerTestRule.getCurrentSignedInAccount()); - } - - @Test - @MediumTest - public void signoutWhenPrimaryAccountIsRemoved() { - mAccountManagerTestRule.addAccountAndWaitForSeeding("the.second.account@gmail.com"); - final CoreAccountInfo oldAccount = - mAccountManagerTestRule.addTestAccountThenSigninAndEnableSync(); - - mAccountManagerTestRule.removeAccount(oldAccount.getEmail()); - - CriteriaHelper.pollUiThread(() -> { - return !IdentityServicesProvider.get() - .getIdentityManager(Profile.getLastUsedRegularProfile()) - .hasPrimaryAccount(); - }); - Assert.assertNull(mAccountManagerTestRule.getCurrentSignedInAccount()); - } -}
diff --git a/chrome/browser/ssl/security_state_tab_helper_browsertest.cc b/chrome/browser/ssl/security_state_tab_helper_browsertest.cc index 2867ba5c..7f3c78a1 100644 --- a/chrome/browser/ssl/security_state_tab_helper_browsertest.cc +++ b/chrome/browser/ssl/security_state_tab_helper_browsertest.cc
@@ -139,7 +139,6 @@ enum CertificateStatus { VALID_CERTIFICATE, INVALID_CERTIFICATE }; const char kTestCertificateIssuerName[] = "Test Root CA"; -const char16_t kTestCertificateIssuerName16[] = u"Test Root CA"; bool IsShowingInterstitial(content::WebContents* tab) { security_interstitials::SecurityInterstitialTabHelper* helper = @@ -295,9 +294,10 @@ expected_cert->issuer().GetDisplayName()); EXPECT_EQ(l10n_util::GetStringUTF8(IDS_VALID_SERVER_CERTIFICATE), explanation.summary); - EXPECT_EQ(l10n_util::GetStringFUTF8(IDS_VALID_SERVER_CERTIFICATE_DESCRIPTION, - kTestCertificateIssuerName16), - explanation.description); + EXPECT_EQ( + l10n_util::GetStringFUTF8(IDS_VALID_SERVER_CERTIFICATE_DESCRIPTION, + base::UTF8ToUTF16(kTestCertificateIssuerName)), + explanation.description); net::X509Certificate* cert = browser->tab_strip_model() ->GetActiveWebContents() ->GetController()
diff --git a/chrome/browser/ssl/ssl_browsertest.cc b/chrome/browser/ssl/ssl_browsertest.cc index 847bc32..7a0c71b 100644 --- a/chrome/browser/ssl/ssl_browsertest.cc +++ b/chrome/browser/ssl/ssl_browsertest.cc
@@ -7278,7 +7278,6 @@ namespace { char kTestMITMSoftwareName[] = "Misconfigured Firewall"; -char16_t kTestMITMSoftwareName16[] = u"Misconfigured Firewall"; class SSLUIMITMSoftwareTest : public CertVerifierBrowserTest { public: @@ -7672,12 +7671,12 @@ SetUpMITMSoftwareCertList(kLargeVersionId); TestMITMSoftwareInterstitial(); - const std::string expected_primary_paragraph = - l10n_util::GetStringFUTF8(IDS_MITM_SOFTWARE_PRIMARY_PARAGRAPH_ENTERPRISE, - net::EscapeForHTML(kTestMITMSoftwareName16)); + const std::string expected_primary_paragraph = l10n_util::GetStringFUTF8( + IDS_MITM_SOFTWARE_PRIMARY_PARAGRAPH_ENTERPRISE, + net::EscapeForHTML(base::UTF8ToUTF16(kTestMITMSoftwareName))); const std::string expected_explanation = l10n_util::GetStringFUTF8( IDS_MITM_SOFTWARE_EXPLANATION_ENTERPRISE, - net::EscapeForHTML(kTestMITMSoftwareName16), + net::EscapeForHTML(base::UTF8ToUTF16(kTestMITMSoftwareName)), l10n_util::GetStringUTF16(IDS_MITM_SOFTWARE_EXPLANATION)); WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); @@ -7700,7 +7699,7 @@ // has escaped HTML characters which throw an error. const std::string expected_explanation = l10n_util::GetStringFUTF8( IDS_MITM_SOFTWARE_EXPLANATION_NONENTERPRISE, - net::EscapeForHTML(kTestMITMSoftwareName16), + net::EscapeForHTML(base::UTF8ToUTF16(kTestMITMSoftwareName)), l10n_util::GetStringUTF16(IDS_MITM_SOFTWARE_EXPLANATION)); WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
diff --git a/chrome/browser/sync/test/integration/wallet_helper.cc b/chrome/browser/sync/test/integration/wallet_helper.cc index a95b7602..a22613a 100644 --- a/chrome/browser/sync/test/integration/wallet_helper.cc +++ b/chrome/browser/sync/test/integration/wallet_helper.cc
@@ -40,9 +40,7 @@ const int kDefaultCardExpMonth = 8; const int kDefaultCardExpYear = 2087; const char kDefaultCardLastFour[] = "1234"; -const char16_t kDefaultCardLastFour16[] = u"1234"; const char kDefaultCardName[] = "Patrick Valenzuela"; -const char16_t kDefaultCardName16[] = u"Patrick Valenzuela"; const sync_pb::WalletMaskedCreditCard_WalletCardType kDefaultCardType = sync_pb::WalletMaskedCreditCard::AMEX; @@ -407,11 +405,17 @@ } CreditCard GetDefaultCreditCard() { - CreditCard card(CreditCard::MASKED_SERVER_CARD, kDefaultCardID); + return GetCreditCard(kDefaultCardID, kDefaultCardLastFour); +} + +autofill::CreditCard GetCreditCard(const std::string& name, + const std::string& last_four) { + CreditCard card(CreditCard::MASKED_SERVER_CARD, name); card.SetExpirationMonth(kDefaultCardExpMonth); card.SetExpirationYear(kDefaultCardExpYear); - card.SetNumber(kDefaultCardLastFour16); - card.SetRawInfo(autofill::CREDIT_CARD_NAME_FULL, kDefaultCardName16); + card.SetNumber(base::UTF8ToUTF16(last_four)); + card.SetRawInfo(autofill::CREDIT_CARD_NAME_FULL, + base::UTF8ToUTF16(kDefaultCardName)); card.SetServerStatus(CreditCard::OK); card.SetNetworkForMaskedCard(autofill::kAmericanExpressCard); card.set_billing_address_id(kDefaultBillingAddressID); @@ -485,11 +489,11 @@ void ExpectDefaultCreditCardValues(const CreditCard& card) { EXPECT_EQ(CreditCard::MASKED_SERVER_CARD, card.record_type()); EXPECT_EQ(kDefaultCardID, card.server_id()); - EXPECT_EQ(kDefaultCardLastFour16, card.LastFourDigits()); + EXPECT_EQ(base::UTF8ToUTF16(kDefaultCardLastFour), card.LastFourDigits()); EXPECT_EQ(autofill::kAmericanExpressCard, card.network()); EXPECT_EQ(kDefaultCardExpMonth, card.expiration_month()); EXPECT_EQ(kDefaultCardExpYear, card.expiration_year()); - EXPECT_EQ(kDefaultCardName16, + EXPECT_EQ(base::UTF8ToUTF16(kDefaultCardName), card.GetRawInfo(autofill::ServerFieldType::CREDIT_CARD_NAME_FULL)); EXPECT_EQ(kDefaultBillingAddressID, card.billing_address_id()); }
diff --git a/chrome/browser/translate/language_detection_service_browsertest.cc b/chrome/browser/translate/language_detection_service_browsertest.cc index 83204345..a85aac7 100644 --- a/chrome/browser/translate/language_detection_service_browsertest.cc +++ b/chrome/browser/translate/language_detection_service_browsertest.cc
@@ -18,10 +18,10 @@ DetermineLanguageReliable) { mojo::Remote<language_detection::mojom::LanguageDetectionService> service = language_detection::LaunchLanguageDetectionService(); - std::u16string text = - u"El niño atrapó un dorado muy grande con cebo vivo. Fileteó el " - u"pescado y lo asó a la parrilla. Sabía excelente. Espera pescar otro " - u"buen pescado mañana."; + std::u16string text = base::UTF8ToUTF16( + "El niño atrapó un dorado muy grande con cebo vivo. Fileteó el " + "pescado y lo asó a la parrilla. Sabía excelente. Espera pescar otro " + "buen pescado mañana."); base::RunLoop run_loop; service->DetermineLanguage(
diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index 8696db9..c0ae2ba 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn
@@ -4000,6 +4000,8 @@ "views/page_info/page_info_main_view.h", "views/page_info/page_info_new_bubble_view.cc", "views/page_info/page_info_new_bubble_view.h", + "views/page_info/page_info_security_content_view.cc", + "views/page_info/page_info_security_content_view.h", "views/page_info/page_switcher_view.cc", "views/page_info/page_switcher_view.h", "views/page_info/permission_icon.cc",
diff --git a/chrome/browser/ui/android/strings/android_chrome_strings.grd b/chrome/browser/ui/android/strings/android_chrome_strings.grd index 9540784..f2a9ebd 100644 --- a/chrome/browser/ui/android/strings/android_chrome_strings.grd +++ b/chrome/browser/ui/android/strings/android_chrome_strings.grd
@@ -2120,6 +2120,9 @@ <message name="IDS_PASSWORD_GENERATION_DIALOG_USE_PASSWORD_BUTTON" desc="Text for a button belonging to the modal dialog that displayes a generated password. Can be used by the user to accept the generated password."> Use password </message> + <message name="IDS_PASSWORD_FILLING_REAUTH_PROMPT_TITLE" desc="The title of the authentication dialog displayed before the password manager fills a saved password into a website."> + Verify it’s you + </message> <!-- Runtime permission strings --> <message name="IDS_MISSING_STORAGE_PERMISSION_DOWNLOAD_EDUCATION_TEXT" desc="Text shown educating the user that Chrome is missing the Android storage permission, which is required to download files.">
diff --git a/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_PASSWORD_FILLING_REAUTH_PROMPT_TITLE.png.sha1 b/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_PASSWORD_FILLING_REAUTH_PROMPT_TITLE.png.sha1 new file mode 100644 index 0000000..5102f78 --- /dev/null +++ b/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_PASSWORD_FILLING_REAUTH_PROMPT_TITLE.png.sha1
@@ -0,0 +1 @@ +a9238e0c600ff7aa979fd96381d9f35aa2ccc3e4 \ No newline at end of file
diff --git a/chrome/browser/ui/autofill/autofill_popup_controller_unittest.cc b/chrome/browser/ui/autofill/autofill_popup_controller_unittest.cc index cd7576a..0d8d3b5 100644 --- a/chrome/browser/ui/autofill/autofill_popup_controller_unittest.cc +++ b/chrome/browser/ui/autofill/autofill_popup_controller_unittest.cc
@@ -292,21 +292,10 @@ class AutofillPopupControllerAccessibilityUnitTest : public AutofillPopupControllerUnitTest { public: - AutofillPopupControllerAccessibilityUnitTest() = default; + AutofillPopupControllerAccessibilityUnitTest() + : accessibility_mode_setter_(ui::AXMode::kScreenReader) {} ~AutofillPopupControllerAccessibilityUnitTest() override = default; - void SetUp() override { - AutofillPopupControllerUnitTest::SetUp(); - content::BrowserAccessibilityState::GetInstance() - ->AddAccessibilityModeFlags(ui::AXMode::kScreenReader); - } - - void TearDown() override { - content::BrowserAccessibilityState::GetInstance() - ->RemoveAccessibilityModeFlags(ui::AXMode::kScreenReader); - AutofillPopupControllerUnitTest::TearDown(); - } - std::unique_ptr<NiceMock<MockAutofillExternalDelegate>> CreateExternalDelegate() override { autofill_driver_ = std::make_unique<NiceMock<MockAutofillDriver>>( @@ -320,6 +309,7 @@ protected: std::unique_ptr<MockBrowserAutofillManager> autofill_manager_; std::unique_ptr<NiceMock<MockAutofillDriver>> autofill_driver_; + content::testing::ScopedContentAXModeSetter accessibility_mode_setter_; private: DISALLOW_COPY_AND_ASSIGN(AutofillPopupControllerAccessibilityUnitTest); @@ -805,6 +795,10 @@ autofill_popup_controller_->FireControlsChangedEvent(true); EXPECT_EQ(base::nullopt, ui::GetActivePopupAxUniqueId()); } + // This needs to happen before TearDown() because having the mode set to + // kScreenReader causes mocked functions to get called with + // mock_ax_platform_node_delegate after it has been destroyed. + accessibility_mode_setter_.ResetMode(); } #endif
diff --git a/chrome/browser/ui/autofill/chrome_autofill_client.cc b/chrome/browser/ui/autofill/chrome_autofill_client.cc index a87a789..13776175 100644 --- a/chrome/browser/ui/autofill/chrome_autofill_client.cc +++ b/chrome/browser/ui/autofill/chrome_autofill_client.cc
@@ -465,7 +465,7 @@ GetPersonalDataManager()->GetSyncSigninState() == autofill::AutofillSyncSigninState::kSignedInAndWalletSyncTransportEnabled; - base::Optional<AccountInfo> account_info = base::nullopt; + base::Optional<AccountInfo> account_info; // AccountInfo data should be passed down only if the following conditions are // satisfied: // 1) Sync is off or the @@ -532,11 +532,14 @@ void ChromeAutofillClient::ConfirmSaveAddressProfile( const AutofillProfile& profile, const AutofillProfile* original_profile, + SaveAddressProfilePromptOptions options, AddressProfileSavePromptCallback callback) { #if defined(OS_ANDROID) + // TODO(crbug.com/1167061): Respect SaveAddressProfilePromptOptions. save_address_profile_flow_manager_.OfferSave( web_contents(), profile, original_profile, std::move(callback)); #else + // TODO(crbug.com/1167060): Respect SaveAddressProfilePromptOptions. SaveUpdateAddressProfileBubbleControllerImpl::CreateForWebContents( web_contents()); SaveUpdateAddressProfileBubbleControllerImpl* controller =
diff --git a/chrome/browser/ui/autofill/chrome_autofill_client.h b/chrome/browser/ui/autofill/chrome_autofill_client.h index f0da781e..9c7ea436 100644 --- a/chrome/browser/ui/autofill/chrome_autofill_client.h +++ b/chrome/browser/ui/autofill/chrome_autofill_client.h
@@ -132,6 +132,7 @@ void ConfirmSaveAddressProfile( const AutofillProfile& profile, const AutofillProfile* original_profile, + SaveAddressProfilePromptOptions options, AddressProfileSavePromptCallback callback) override; bool HasCreditCardScanFeature() override; void ScanCreditCard(CreditCardScanCallback callback) override;
diff --git a/chrome/browser/ui/autofill/save_address_profile_bubble_controller_impl_browsertest.cc b/chrome/browser/ui/autofill/save_address_profile_bubble_controller_impl_browsertest.cc index 9524daf..afe53453 100644 --- a/chrome/browser/ui/autofill/save_address_profile_bubble_controller_impl_browsertest.cc +++ b/chrome/browser/ui/autofill/save_address_profile_bubble_controller_impl_browsertest.cc
@@ -8,6 +8,7 @@ #include "chrome/browser/ui/autofill/chrome_autofill_client.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/test/test_browser_dialog.h" +#include "components/autofill/core/browser/autofill_client.h" #include "components/autofill/core/browser/autofill_test_utils.h" #include "components/autofill/core/common/autofill_features.h" #include "content/public/test/browser_test.h" @@ -33,9 +34,11 @@ browser()->tab_strip_model()->GetActiveWebContents(); autofill::ChromeAutofillClient* autofill_client = autofill::ChromeAutofillClient::FromWebContents(web_contents); - autofill_client->ConfirmSaveAddressProfile(test::GetFullProfile(), - /*original_profile=*/nullptr, - base::DoNothing()); + autofill_client->ConfirmSaveAddressProfile( + test::GetFullProfile(), + /*original_profile=*/nullptr, + AutofillClient::SaveAddressProfilePromptOptions{.show_prompt = true}, + base::DoNothing()); controller_ = SaveUpdateAddressProfileBubbleControllerImpl::FromWebContents( web_contents); DCHECK(controller_);
diff --git a/chrome/browser/ui/omnibox/omnibox_view_browsertest.cc b/chrome/browser/ui/omnibox/omnibox_view_browsertest.cc index 9cc964d..b14570f 100644 --- a/chrome/browser/ui/omnibox/omnibox_view_browsertest.cc +++ b/chrome/browser/ui/omnibox/omnibox_view_browsertest.cc
@@ -1220,7 +1220,7 @@ // Insert text: ダ. This is two, 3-byte UTF-8 characters: // U+FF80 "HALFWIDTH KATAKANA LETTER TA" and // U+FF9E "HALFWIDTH KATAKANA VOICED SOUND MARK". - omnibox_view->SetUserText(u"\uFF80\uFF9E"); + omnibox_view->SetUserText(base::UTF8ToUTF16("\357\276\200\357\276\236")); EXPECT_FALSE(omnibox_view->GetText().empty()); // Move the cursor to the end. @@ -1236,7 +1236,7 @@ EXPECT_TRUE(omnibox_view->GetText().empty()); #else // Toolkit-views text fields delete just the sound mark. - EXPECT_EQ(u"\uFF80", omnibox_view->GetText()); + EXPECT_EQ(base::UTF8ToUTF16("\357\276\200"), omnibox_view->GetText()); #endif }
diff --git a/chrome/browser/ui/startup/startup_browser_creator_browsertest.cc b/chrome/browser/ui/startup/startup_browser_creator_browsertest.cc index c29d1a2..c2bdaf1 100644 --- a/chrome/browser/ui/startup/startup_browser_creator_browsertest.cc +++ b/chrome/browser/ui/startup/startup_browser_creator_browsertest.cc
@@ -149,7 +149,7 @@ #if !BUILDFLAG(IS_CHROMEOS_ASH) const char kAppId[] = "dofnemchnjfeendjmdhaldenaiabpiad"; -const char16_t kAppName[] = u"Test App"; +const char kAppName[] = "Test App"; const char kStartUrl[] = "https://test.com"; // Check that there are two browsers. Find the one that is not |browser|. @@ -1341,7 +1341,7 @@ base::RunLoop run_loop; WebApplicationInfo info; info.start_url = GURL(kStartUrl); - info.title = kAppName; + info.title = base::UTF8ToUTF16(kAppName); info.open_as_window = true; web_app_finalizer.FinalizeInstall( info, options, @@ -1445,7 +1445,7 @@ std::unique_ptr<WebApplicationInfo> info = std::make_unique<WebApplicationInfo>(); info->start_url = GURL(kStartUrl); - info->title = kAppName; + info->title = base::UTF8ToUTF16(kAppName); info->open_as_window = true; info->url_handlers = url_handlers; web_app::AppId app_id = @@ -1586,7 +1586,7 @@ std::unique_ptr<WebApplicationInfo> info = std::make_unique<WebApplicationInfo>(); info->start_url = GURL(kStartUrl); - info->title = kAppName; + info->title = base::UTF8ToUTF16(kAppName); info->open_as_window = true; info->protocol_handlers = protocol_handlers; web_app::AppId app_id =
diff --git a/chrome/browser/ui/views/accessibility/browser_accessibility_uitest_auralinux.cc b/chrome/browser/ui/views/accessibility/browser_accessibility_uitest_auralinux.cc index 911f0c31..e5c47569 100644 --- a/chrome/browser/ui/views/accessibility/browser_accessibility_uitest_auralinux.cc +++ b/chrome/browser/ui/views/accessibility/browser_accessibility_uitest_auralinux.cc
@@ -20,18 +20,15 @@ #include "ui/views/accessibility/view_accessibility.h" class AuraLinuxAccessibilityInProcessBrowserTest : public InProcessBrowserTest { - public: - void SetUp() override { - ui::AXPlatformNode::NotifyAddAXModeFlags(ui::kAXModeComplete); - InProcessBrowserTest::SetUp(); - } - protected: - AuraLinuxAccessibilityInProcessBrowserTest() = default; + AuraLinuxAccessibilityInProcessBrowserTest() + : ax_mode_setter_(ui::kAXModeComplete) {} void VerifyEmbedRelationships(); private: + ui::testing::ScopedAxModeSetter ax_mode_setter_; + DISALLOW_COPY_AND_ASSIGN(AuraLinuxAccessibilityInProcessBrowserTest); };
diff --git a/chrome/browser/ui/views/bubble_anchor_util_views.cc b/chrome/browser/ui/views/bubble_anchor_util_views.cc index 0545ce2..111e67b3 100644 --- a/chrome/browser/ui/views/bubble_anchor_util_views.cc +++ b/chrome/browser/ui/views/bubble_anchor_util_views.cc
@@ -50,8 +50,7 @@ AnchorConfiguration GetPermissionPromptBubbleAnchorConfiguration( Browser* browser) { BrowserView* browser_view = BrowserView::GetBrowserViewForBrowser(browser); - if (base::FeatureList::IsEnabled(permissions::features::kPermissionChip) && - browser_view->GetLocationBarView()->IsDrawn()) { + if (browser_view->GetLocationBarView()->chip()) { return {browser_view->GetLocationBarView(), browser_view->GetLocationBarView()->chip()->button(), views::BubbleBorder::TOP_LEFT};
diff --git a/chrome/browser/ui/views/extensions/extensions_side_panel_controller.cc b/chrome/browser/ui/views/extensions/extensions_side_panel_controller.cc index e11895ed..60eb2245 100644 --- a/chrome/browser/ui/views/extensions/extensions_side_panel_controller.cc +++ b/chrome/browser/ui/views/extensions/extensions_side_panel_controller.cc
@@ -14,6 +14,7 @@ #include "chrome/browser/ui/views/side_panel.h" #include "chrome/browser/ui/views/toolbar/toolbar_button.h" #include "chrome/browser/ui/views/toolbar/toolbar_view.h" +#include "chrome/grit/generated_resources.h" #include "content/public/browser/navigation_details.h" #include "content/public/browser/navigation_entry.h" #include "extensions/browser/extension_registry.h" @@ -29,10 +30,10 @@ // TODO(tluk): Figure out what our default width should be. constexpr int kDefaultWidth = 450; +const char kSidePanelResourceName[] = "side_panel.html"; const char kPanelActiveKey[] = "active"; const char kPanelActivatableKey[] = "activatable"; const char kPanelWidth[] = "width"; - const char kPanelTrueValue[] = "true"; } // namespace @@ -46,24 +47,18 @@ web_view_(side_panel_->AddChildView( std::make_unique<views::WebView>(browser_view_->GetProfile()))) { DCHECK(base::FeatureList::IsEnabled(features::kExtensionsSidePanel)); + extensions::ExtensionRegistry* registry = + extensions::ExtensionRegistry::Get(browser_view->GetProfile()); + registry_observation_.Observe(registry); side_panel_->SetVisible(false); side_panel_->SetPanelWidth(kDefaultWidth); - Observe(web_view_->GetWebContents()); - // Enable the hosted WebContents to leverage extensions APIs. - extensions::ChromeExtensionWebContentsObserver::CreateForWebContents( - web_view_->GetWebContents()); - - // Set the side panel as type kExtensionPopup given this most closely - // represents how we intend to use the extension for the side panel. - // TODO(tluk): Consider creating a new type specifically for the extension - // side panel. - extensions::SetViewType(web_view_->GetWebContents(), - extensions::mojom::ViewType::kExtensionPopup); - - if (const extensions::Extension* extension = GetExtension()) - web_view_->LoadInitialURL(extension->GetResourceURL("side_panel.html")); + if (const extensions::Extension* extension = GetExtension()) { + SetNewWebContents(); + web_view_->LoadInitialURL( + extension->GetResourceURL(kSidePanelResourceName)); + } } ExtensionsSidePanelController::~ExtensionsSidePanelController() = default; @@ -71,14 +66,83 @@ std::unique_ptr<ToolbarButton> ExtensionsSidePanelController::CreateToolbarButton() { auto toolbar_button = std::make_unique<ToolbarButton>(); + toolbar_button->SetAccessibleName( + l10n_util::GetStringUTF16(IDS_ACCNAME_LEFT_ALIGNED_SIDE_PANEL_BUTTON)); + toolbar_button->SetTooltipText( + l10n_util::GetStringUTF16(IDS_TOOLTIP_LEFT_ALIGNED_SIDE_PANEL_BUTTON)); // TODO(tluk): Update this to use the icon from the extension. toolbar_button->SetVectorIcon(kWebIcon); toolbar_button->SetCallback(base::BindRepeating( &ExtensionsSidePanelController::SidePanelButtonPressed, base::Unretained(this))); + toolbar_button->SetVisible(!!GetExtension()); + toolbar_button->SetEnabled(false); return toolbar_button; } +void ExtensionsSidePanelController::ResetWebContents() { + if (!web_view_->web_contents() && !web_contents_) + return; + + DCHECK_EQ(web_view_->web_contents(), web_contents_.get()); + Observe(nullptr); + web_view_->SetWebContents(nullptr); + web_contents_.reset(); +} + +void ExtensionsSidePanelController::SetNewWebContents() { + if (web_view_->web_contents()) + ResetWebContents(); + + DCHECK(!web_view_->web_contents()); + DCHECK(!web_contents_); + web_contents_ = content::WebContents::Create( + content::WebContents::CreateParams(browser_view_->GetProfile())); + + // Enable the hosted WebContents to leverage extensions APIs. + extensions::ChromeExtensionWebContentsObserver::CreateForWebContents( + web_contents_.get()); + + // Set the side panel as type kExtensionPopup given this most closely + // represents how we intend to use the extension for the side panel. + // TODO(tluk): Consider creating a new type specifically for the extension + // side panel. + extensions::SetViewType(web_contents_.get(), + extensions::mojom::ViewType::kExtensionPopup); + + Observe(web_contents_.get()); + web_contents_->SetDelegate(this); + web_view_->SetWebContents(web_contents_.get()); +} + +content::WebContents* ExtensionsSidePanelController::OpenURLFromTab( + content::WebContents* source, + const content::OpenURLParams& params) { + return browser_view_->browser()->OpenURL(params); +} + +void ExtensionsSidePanelController::OnExtensionLoaded( + content::BrowserContext* browser_context, + const extensions::Extension* extension) { + if (extension->id() == extension_id_) { + SetNewWebContents(); + web_view_->LoadInitialURL( + extension->GetResourceURL(kSidePanelResourceName)); + browser_view_->toolbar()->left_side_panel_button()->SetVisible(true); + } +} + +void ExtensionsSidePanelController::OnExtensionUnloaded( + content::BrowserContext* browser_context, + const extensions::Extension* extension, + extensions::UnloadedExtensionReason reason) { + if (extension->id() == extension_id_) { + ResetWebContents(); + browser_view_->toolbar()->left_side_panel_button()->SetVisible(false); + side_panel_->SetVisible(false); + } +} + // The extension host uses URL params to control various properties of the side // panel such as visibility and width. Check for these params and adjust the // side panel accordingly.
diff --git a/chrome/browser/ui/views/extensions/extensions_side_panel_controller.h b/chrome/browser/ui/views/extensions/extensions_side_panel_controller.h index 3341517..34fa3199 100644 --- a/chrome/browser/ui/views/extensions/extensions_side_panel_controller.h +++ b/chrome/browser/ui/views/extensions/extensions_side_panel_controller.h
@@ -7,7 +7,11 @@ #include <memory> +#include "base/scoped_observation.h" +#include "content/public/browser/web_contents_delegate.h" #include "content/public/browser/web_contents_observer.h" +#include "extensions/browser/extension_registry.h" +#include "extensions/browser/extension_registry_observer.h" #include "extensions/common/extension_id.h" namespace extensions { @@ -25,7 +29,10 @@ // A class that manages hosting the extension WebContents in the left aligned // side panel of the browser window. // TODO(crbug.com/1197555): Remove this once the experiment has concluded. -class ExtensionsSidePanelController : public content::WebContentsObserver { +class ExtensionsSidePanelController + : public content::WebContentsObserver, + public content::WebContentsDelegate, + public extensions::ExtensionRegistryObserver { public: ExtensionsSidePanelController(SidePanel* side_panel, BrowserView* browser_view); @@ -35,6 +42,22 @@ ~ExtensionsSidePanelController() override; std::unique_ptr<ToolbarButton> CreateToolbarButton(); + void ResetWebContents(); + void SetNewWebContents(); + + // content::WebContentsDelegate: + content::WebContents* OpenURLFromTab( + content::WebContents* source, + const content::OpenURLParams& params) override; + + // extensions::ExtensionRegistryObserver: + void OnExtensionLoaded(content::BrowserContext* browser_context, + const extensions::Extension* extension) override; + void OnExtensionUnloaded(content::BrowserContext* browser_context, + const extensions::Extension* extension, + extensions::UnloadedExtensionReason reason) override; + + views::WebView* get_web_view_for_testing() { return web_view_; } private: // content::WebContentsObserver: @@ -49,6 +72,11 @@ SidePanel* side_panel_; BrowserView* browser_view_; views::WebView* web_view_; + std::unique_ptr<content::WebContents> web_contents_; + + base::ScopedObservation<extensions::ExtensionRegistry, + extensions::ExtensionRegistryObserver> + registry_observation_{this}; }; #endif // CHROME_BROWSER_UI_VIEWS_EXTENSIONS_EXTENSIONS_SIDE_PANEL_CONTROLLER_H_
diff --git a/chrome/browser/ui/views/extensions/extensions_side_panel_controller_browsertest.cc b/chrome/browser/ui/views/extensions/extensions_side_panel_controller_browsertest.cc new file mode 100644 index 0000000..39e9d773 --- /dev/null +++ b/chrome/browser/ui/views/extensions/extensions_side_panel_controller_browsertest.cc
@@ -0,0 +1,161 @@ +// Copyright 2021 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 <memory> + +#include "base/strings/strcat.h" +#include "base/strings/string_number_conversions.h" +#include "chrome/browser/extensions/extension_service.h" +#include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/browser_window.h" +#include "chrome/browser/ui/ui_features.h" +#include "chrome/browser/ui/views/extensions/extensions_side_panel_controller.h" +#include "chrome/browser/ui/views/frame/browser_view.h" +#include "chrome/browser/ui/views/side_panel.h" +#include "chrome/browser/ui/views/toolbar/toolbar_view.h" +#include "chrome/test/base/in_process_browser_test.h" +#include "content/public/test/browser_test.h" +#include "content/public/test/browser_test_utils.h" +#include "extensions/browser/extension_system.h" +#include "extensions/common/extension.h" +#include "extensions/common/extension_builder.h" + +namespace { + +const char kTargetedId[] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; +const char kSidePanelResourceName[] = "side_panel.html"; +const char kPanelActiveKey[] = "active"; +const char kPanelActivatableKey[] = "activatable"; +const char kPanelWidth[] = "width"; +const char kTrue[] = "true"; +const char kFalse[] = "false"; + +std::string GetResourceString(const std::string& key, + const std::string& value) { + return base::StrCat({kSidePanelResourceName, "?", key, "=", value}); +} + +} // namespace + +class ExtensionsSidePanelControllerBrowserTest : public InProcessBrowserTest { + public: + ExtensionsSidePanelControllerBrowserTest() { + scoped_feature_list_.InitAndEnableFeatureWithParameters( + {features::kExtensionsSidePanel}, + {{"ExtensionsSidePanelId", kTargetedId}}); + } + + void SetUpOnMainThread() override { + InProcessBrowserTest::SetUpOnMainThread(); + extension_ = extensions::ExtensionBuilder("foo").SetID(kTargetedId).Build(); + GetExtensionService()->AddExtension(extension_.get()); + + // The following should exist when the `kExtensionsSidePanel` feature flag + // is enabled and the extension with id specified by `ExtensionsSidePanelId` + // is present. + ASSERT_NE(nullptr, side_panel()); + ASSERT_NE(nullptr, side_panel_button()); + ASSERT_NE(nullptr, controller()); + } + + extensions::ExtensionService* GetExtensionService() { + return extensions::ExtensionSystem::Get(browser()->profile()) + ->extension_service(); + } + + BrowserView* browser_view() { + return static_cast<BrowserView*>(browser()->window()); + } + + SidePanel* side_panel() { + return browser_view()->left_aligned_side_panel_for_testing(); + } + + ToolbarButton* side_panel_button() { + return browser_view()->toolbar()->left_side_panel_button(); + } + + ExtensionsSidePanelController* controller() { + return browser_view()->extensions_side_panel_controller(); + } + + const extensions::Extension* extension() { return extension_.get(); } + + private: + scoped_refptr<const extensions::Extension> extension_; + base::test::ScopedFeatureList scoped_feature_list_; +}; + +IN_PROC_BROWSER_TEST_F(ExtensionsSidePanelControllerBrowserTest, + LeftSidePanelButtonVisibleOnlyWhenExtensionEnabled) { + EXPECT_TRUE(side_panel_button()->GetVisible()); + + // Remove the extension. + GetExtensionService()->UnloadExtension( + kTargetedId, extensions::UnloadedExtensionReason::UNINSTALL); + EXPECT_FALSE(side_panel_button()->GetVisible()); + + // Reenable the extension. + GetExtensionService()->AddExtension(extension()); + EXPECT_TRUE(side_panel_button()->GetVisible()); +} + +IN_PROC_BROWSER_TEST_F(ExtensionsSidePanelControllerBrowserTest, + ToggleSidePanelViaURLParams) { + EXPECT_FALSE(side_panel()->GetVisible()); + + // Toggle the side panel into the visible state. + controller()->get_web_view_for_testing()->LoadInitialURL( + extension()->GetResourceURL(GetResourceString(kPanelActiveKey, kTrue))); + content::WaitForLoadStop( + controller()->get_web_view_for_testing()->GetWebContents()); + EXPECT_TRUE(side_panel()->GetVisible()); + + // Hide the side panel. + controller()->get_web_view_for_testing()->LoadInitialURL( + extension()->GetResourceURL(GetResourceString(kPanelActiveKey, kFalse))); + content::WaitForLoadStop( + controller()->get_web_view_for_testing()->GetWebContents()); + EXPECT_FALSE(side_panel()->GetVisible()); +} + +IN_PROC_BROWSER_TEST_F(ExtensionsSidePanelControllerBrowserTest, + SetSidePanelWidthViaURLParams) { + constexpr int kWidth1 = 300; + controller()->get_web_view_for_testing()->LoadInitialURL( + extension()->GetResourceURL( + GetResourceString(kPanelWidth, base::NumberToString(kWidth1)))); + content::WaitForLoadStop( + controller()->get_web_view_for_testing()->GetWebContents()); + EXPECT_EQ(side_panel()->GetPreferredSize().width(), kWidth1); + + constexpr int kWidth2 = 200; + controller()->get_web_view_for_testing()->LoadInitialURL( + extension()->GetResourceURL( + GetResourceString(kPanelWidth, base::NumberToString(kWidth2)))); + content::WaitForLoadStop( + controller()->get_web_view_for_testing()->GetWebContents()); + EXPECT_EQ(side_panel()->GetPreferredSize().width(), kWidth2); +} + +IN_PROC_BROWSER_TEST_F(ExtensionsSidePanelControllerBrowserTest, + SetSidePanelActivatableViaURLParams) { + EXPECT_FALSE(side_panel_button()->GetEnabled()); + + // Set the side panel to be activatable, enabling the side panel button. + controller()->get_web_view_for_testing()->LoadInitialURL( + extension()->GetResourceURL( + GetResourceString(kPanelActivatableKey, kTrue))); + content::WaitForLoadStop( + controller()->get_web_view_for_testing()->GetWebContents()); + EXPECT_TRUE(side_panel_button()->GetEnabled()); + + // Set activatable to false, disabling the side panel button. + controller()->get_web_view_for_testing()->LoadInitialURL( + extension()->GetResourceURL( + GetResourceString(kPanelActivatableKey, kFalse))); + content::WaitForLoadStop( + controller()->get_web_view_for_testing()->GetWebContents()); + EXPECT_FALSE(side_panel_button()->GetEnabled()); +}
diff --git a/chrome/browser/ui/views/frame/browser_view.cc b/chrome/browser/ui/views/frame/browser_view.cc index 5641dfa..93bb5dd 100644 --- a/chrome/browser/ui/views/frame/browser_view.cc +++ b/chrome/browser/ui/views/frame/browser_view.cc
@@ -2349,7 +2349,7 @@ // Tab has a pending permission request. if (toolbar_ && toolbar_->location_bar() && - toolbar_->location_bar()->chip()->GetVisible()) { + toolbar_->location_bar()->chip()) { return l10n_util::GetStringFUTF16( IDS_TAB_AX_LABEL_PERMISSION_REQUESTED_FORMAT, title); } @@ -2777,7 +2777,8 @@ #endif // When permission is requested, permission chip must be first pane in the // pane traversal order to be easily accessible for keyboard users. - if (toolbar_ && toolbar_->location_bar()) { + if (toolbar_ && toolbar_->location_bar() && + toolbar_->location_bar()->chip()) { panes->push_back(toolbar_->location_bar()->chip()); } panes->push_back(toolbar_button_provider_->GetAsAccessiblePaneView());
diff --git a/chrome/browser/ui/views/frame/browser_view.h b/chrome/browser/ui/views/frame/browser_view.h index 2175c25..d2a00a0 100644 --- a/chrome/browser/ui/views/frame/browser_view.h +++ b/chrome/browser/ui/views/frame/browser_view.h
@@ -178,6 +178,10 @@ SidePanel* right_aligned_side_panel() { return right_aligned_side_panel_; } + SidePanel* left_aligned_side_panel_for_testing() { + return left_aligned_side_panel_; + } + ExtensionsSidePanelController* extensions_side_panel_controller() { return extensions_side_panel_controller_.get(); }
diff --git a/chrome/browser/ui/views/frame/browser_view_browsertest.cc b/chrome/browser/ui/views/frame/browser_view_browsertest.cc index 3eaf8950..53345f8 100644 --- a/chrome/browser/ui/views/frame/browser_view_browsertest.cc +++ b/chrome/browser/ui/views/frame/browser_view_browsertest.cc
@@ -341,7 +341,7 @@ // Open a tab-modal dialog and check that the accessibility tree only contains // the dialog. IN_PROC_BROWSER_TEST_F(BrowserViewTest, GetAccessibleTabModalDialogTree) { - ui::AXPlatformNode::NotifyAddAXModeFlags(ui::kAXModeComplete); + ui::testing::ScopedAxModeSetter ax_mode_setter(ui::kAXModeComplete); ui::AXPlatformNode* ax_node = ui::AXPlatformNode::FromNativeViewAccessible( browser_view()->GetWidget()->GetRootView()->GetNativeViewAccessible()); // We expect this conversion to be safe on Windows, but can't guarantee that it
diff --git a/chrome/browser/ui/views/frame/immersive_mode_controller_chromeos_browsertest.cc b/chrome/browser/ui/views/frame/immersive_mode_controller_chromeos_browsertest.cc index a64dd44a..b4999d7 100644 --- a/chrome/browser/ui/views/frame/immersive_mode_controller_chromeos_browsertest.cc +++ b/chrome/browser/ui/views/frame/immersive_mode_controller_chromeos_browsertest.cc
@@ -369,7 +369,7 @@ // on the chip to trigger showing the prompt. BrowserView* browser_view = BrowserView::GetBrowserViewForBrowser(browser()); PermissionChip* chip = browser_view->toolbar()->location_bar()->chip(); - if (chip->GetVisible()) { + if (chip) { views::test::ButtonTestApi(chip->button()) .NotifyClick(ui::MouseEvent(ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(), ui::EventTimeForNow(),
diff --git a/chrome/browser/ui/views/global_media_controls/media_notification_device_selector_view_unittest.cc b/chrome/browser/ui/views/global_media_controls/media_notification_device_selector_view_unittest.cc index c1691fb..e4934a8 100644 --- a/chrome/browser/ui/views/global_media_controls/media_notification_device_selector_view_unittest.cc +++ b/chrome/browser/ui/views/global_media_controls/media_notification_device_selector_view_unittest.cc
@@ -34,12 +34,11 @@ constexpr char kSinkId[] = "sink_id"; constexpr char kSinkFriendlyName[] = "Nest Hub"; -constexpr char16_t kSinkFriendlyName16[] = u"Nest Hub"; UIMediaSink CreateMediaSink( UIMediaSinkState state = UIMediaSinkState::AVAILABLE) { UIMediaSink sink; - sink.friendly_name = kSinkFriendlyName16; + sink.friendly_name = base::UTF8ToUTF16(kSinkFriendlyName); sink.id = kSinkId; sink.state = state; sink.cast_modes = {media_router::MediaCastMode::PRESENTATION};
diff --git a/chrome/browser/ui/views/location_bar/location_bar_view.cc b/chrome/browser/ui/views/location_bar/location_bar_view.cc index 09ff427..4edca684 100644 --- a/chrome/browser/ui/views/location_bar/location_bar_view.cc +++ b/chrome/browser/ui/views/location_bar/location_bar_view.cc
@@ -192,8 +192,6 @@ const gfx::FontList& font_list = views::style::GetFont( CONTEXT_OMNIBOX_PRIMARY, views::style::STYLE_PRIMARY); - chip_ = AddChildView(std::make_unique<PermissionRequestChip>(browser())); - auto location_icon_view = std::make_unique<LocationIconView>(font_list, this, this); location_icon_view->set_drag_controller(this); @@ -538,7 +536,7 @@ // label/chip. const double kLeadingDecorationMaxFraction = 0.5; - if (chip_->GetVisible() && !ShouldShowKeywordBubble()) { + if (chip_ && !ShouldShowKeywordBubble()) { leading_decorations.AddDecoration(vertical_padding, location_height, false, 0, edge_padding, chip_); } @@ -762,6 +760,22 @@ ->ActivateFirstInactiveBubbleForAccessibility(); } +PermissionChip* LocationBarView::DisplayChip( + permissions::PermissionPrompt::Delegate* delegate) { + DCHECK(!chip_); + DCHECK(delegate); + // `chip_` must come first so it's in the correct place in the focus order. + chip_ = AddChildViewAt( + std::make_unique<PermissionRequestChip>(browser(), delegate), 0); + return chip_; +} + +void LocationBarView::FinalizeChip() { + DCHECK(chip_); + RemoveChildViewT(chip_); + chip_ = nullptr; +} + void LocationBarView::UpdateWithoutTabRestore() { Update(nullptr); } @@ -1179,6 +1193,11 @@ AnimationProgressed(animation); } +void LocationBarView::OnChildViewRemoved(View* observed_view, View* child) { + views::AnimationDelegateViews::OnChildViewRemoved(observed_view, child); + PreferredSizeChanged(); +} + void LocationBarView::OnChanged() { location_icon_view_->Update(/*suppress_animations=*/false); clear_all_button_->SetVisible( @@ -1325,15 +1344,14 @@ } void LocationBarView::UpdateChipVisibility() { - if (!chip()->GetActiveRequest()) { - DCHECK(!chip()->GetVisible()); + if (!chip_) { return; } if (IsEditingOrEmpty()) { - chip()->Hide(); + chip_->Hide(); } else { - chip()->Reshow(); + chip_->Reshow(); } }
diff --git a/chrome/browser/ui/views/location_bar/location_bar_view.h b/chrome/browser/ui/views/location_bar/location_bar_view.h index 6be252e..f460e9b 100644 --- a/chrome/browser/ui/views/location_bar/location_bar_view.h +++ b/chrome/browser/ui/views/location_bar/location_bar_view.h
@@ -177,6 +177,13 @@ PermissionChip* chip() { return chip_; } + // Creates and displays an instance of PermissionRequestChip. + PermissionChip* DisplayChip( + permissions::PermissionPrompt::Delegate* delegate); + + // Removes previously displayed PermissionChip. + void FinalizeChip(); + // LocationBar: void FocusLocation(bool is_user_initiated) override; void Revert() override; @@ -350,6 +357,7 @@ void AnimationProgressed(const gfx::Animation* animation) override; void AnimationEnded(const gfx::Animation* animation) override; void AnimationCanceled(const gfx::Animation* animation) override; + void OnChildViewRemoved(View* observed_view, View* child) override; // ChromeOmniboxEditController: void OnChanged() override;
diff --git a/chrome/browser/ui/views/location_bar/omnibox_chip_button.cc b/chrome/browser/ui/views/location_bar/omnibox_chip_button.cc index 3d347f15..6d59cbf 100644 --- a/chrome/browser/ui/views/location_bar/omnibox_chip_button.cc +++ b/chrome/browser/ui/views/location_bar/omnibox_chip_button.cc
@@ -15,9 +15,16 @@ #include "ui/views/controls/highlight_path_generator.h" OmniboxChipButton::OmniboxChipButton(PressedCallback callback, - int button_context) - : MdTextButton(std::move(callback), std::u16string(), button_context) { + const gfx::VectorIcon& icon, + std::u16string message, + bool is_prominent) + : MdTextButton(std::move(callback), + std::u16string(), + views::style::CONTEXT_BUTTON_MD), + icon_(icon) { views::InstallPillHighlightPathGenerator(this); + SetProminent(is_prominent); + SetText(message); SetCornerRadius(GetIconSize()); SetHorizontalAlignment(gfx::ALIGN_LEFT); SetElideBehavior(gfx::ElideBehavior::FADE_TAIL); @@ -32,6 +39,8 @@ constexpr auto kAnimationDuration = base::TimeDelta::FromMilliseconds(350); animation_ = std::make_unique<gfx::SlideAnimation>(this); animation_->SetSlideDuration(kAnimationDuration); + + UpdateColors(); } OmniboxChipButton::~OmniboxChipButton() = default; @@ -52,11 +61,6 @@ animation_->Reset(value); } -void OmniboxChipButton::SetIcon(const gfx::VectorIcon* icon) { - icon_ = icon; - UpdateColors(); -} - void OmniboxChipButton::SetExpandAnimationEndedCallback( base::RepeatingCallback<void()> callback) { expand_animation_ended_callback_ = callback; @@ -74,7 +78,7 @@ } void OmniboxChipButton::OnThemeChanged() { - View::OnThemeChanged(); + MdTextButton::OnThemeChanged(); UpdateColors(); } @@ -97,22 +101,14 @@ UpdateColors(); } -void OmniboxChipButton::SetProminent(bool is_prominent) { - views::MdTextButton::SetProminent(is_prominent); - UpdateColors(); -} - int OmniboxChipButton::GetIconSize() const { return GetLayoutConstant(LOCATION_BAR_ICON_SIZE); } void OmniboxChipButton::UpdateColors() { - if (!icon_) - return; - SetEnabledTextColors(GetForegroundColor()); SetImageModel(views::Button::STATE_NORMAL, - ui::ImageModel::FromVectorIcon(*icon_, GetForegroundColor(), + ui::ImageModel::FromVectorIcon(icon_, GetForegroundColor(), GetIconSize())); SetBgColorOverride(GetBackgroundColor()); }
diff --git a/chrome/browser/ui/views/location_bar/omnibox_chip_button.h b/chrome/browser/ui/views/location_bar/omnibox_chip_button.h index 3c5a1bb..1b37b8e8 100644 --- a/chrome/browser/ui/views/location_bar/omnibox_chip_button.h +++ b/chrome/browser/ui/views/location_bar/omnibox_chip_button.h
@@ -14,9 +14,10 @@ class OmniboxChipButton : public views::MdTextButton { public: METADATA_HEADER(OmniboxChipButton); - explicit OmniboxChipButton( - PressedCallback callback, - int button_context = views::style::CONTEXT_BUTTON_MD); + explicit OmniboxChipButton(PressedCallback callback, + const gfx::VectorIcon& icon, + std::u16string message, + bool is_prominent); OmniboxChipButton(const OmniboxChipButton& button) = delete; OmniboxChipButton& operator=(const OmniboxChipButton& button) = delete; ~OmniboxChipButton() override; @@ -31,11 +32,8 @@ void AnimateCollapse(); void AnimateExpand(); void ResetAnimation(double value = 0); - - void SetIcon(const gfx::VectorIcon* icon); void SetExpandAnimationEndedCallback( base::RepeatingCallback<void()> callback); - bool is_fully_collapsed() const { return fully_collapsed_; } bool is_animating() const { return animation_->is_animating(); } @@ -49,11 +47,6 @@ // Set the button theme. void SetTheme(Theme theme); - - // Set whether the button uses prominent styling, equivalent to - // MdTextButton::SetProminent. - void SetProminent(bool is_prominent); - void SetForceExpandedForTesting(bool force_expanded_for_testing); private: @@ -87,7 +80,7 @@ // without text. bool fully_collapsed_ = false; - const gfx::VectorIcon* icon_ = nullptr; + const gfx::VectorIcon& icon_; base::RepeatingCallback<void()> expand_animation_ended_callback_;
diff --git a/chrome/browser/ui/views/location_bar/permission_chip.cc b/chrome/browser/ui/views/location_bar/permission_chip.cc index 37550a54..0ebd7a4 100644 --- a/chrome/browser/ui/views/location_bar/permission_chip.cc +++ b/chrome/browser/ui/views/location_bar/permission_chip.cc
@@ -10,7 +10,6 @@ #include "base/time/time.h" #include "chrome/browser/ui/views/permission_bubble/permission_prompt_style.h" #include "chrome/grit/generated_resources.h" -#include "components/permissions/features.h" #include "components/permissions/permission_request.h" #include "components/permissions/request_type.h" #include "components/strings/grit/components_strings.h" @@ -22,13 +21,6 @@ #include "ui/views/controls/button/button_controller.h" #include "ui/views/widget/widget.h" -namespace { -bool IsCameraOrMicPermission(permissions::RequestType type) { - return type == permissions::RequestType::kCameraStream || - type == permissions::RequestType::kMicStream; -} -} // namespace - // ButtonController that NotifyClick from being called when the // BubbleOwnerDelegate's bubble is showing. Otherwise the bubble will show again // immediately after being closed via losing focus. @@ -60,13 +52,19 @@ BubbleOwnerDelegate* bubble_owner_ = nullptr; }; -PermissionChip::PermissionChip() { +PermissionChip::PermissionChip( + permissions::PermissionPrompt::Delegate* delegate, + const gfx::VectorIcon& icon, + std::u16string message, + bool should_start_open) + : delegate_(delegate), should_start_open_(should_start_open) { + DCHECK(delegate); SetUseDefaultFillLayout(true); - SetVisible(false); - chip_button_ = - AddChildView(std::make_unique<OmniboxChipButton>(base::BindRepeating( - &PermissionChip::ChipButtonPressed, base::Unretained(this)))); + chip_button_ = AddChildView(std::make_unique<OmniboxChipButton>( + base::BindRepeating(&PermissionChip::ChipButtonPressed, + base::Unretained(this)), + icon, message, true)); chip_button_->SetButtonController(std::make_unique<BubbleButtonController>( chip_button_, this, @@ -77,48 +75,14 @@ &PermissionChip::ExpandAnimationEnded, base::Unretained(this))); chip_button_->SetTheme(OmniboxChipButton::Theme::kBlue); - chip_button_->SetProminent(true); + + Show(should_start_open_); } PermissionChip::~PermissionChip() { CHECK(!IsInObserverList()); -} - -void PermissionChip::DisplayRequest( - permissions::PermissionPrompt::Delegate* delegate) { - DCHECK(delegate); - delegate_ = delegate; - - const std::vector<permissions::PermissionRequest*>& requests = - delegate_->Requests(); - - // TODO(olesiamarukhno): Add combined camera & microphone permission and - // update delegate to contain only one request at a time. - DCHECK(requests.size() == 1u || requests.size() == 2u); - if (requests.size() == 2) { - DCHECK(IsCameraOrMicPermission(requests[0]->GetRequestType())); - DCHECK(IsCameraOrMicPermission(requests[1]->GetRequestType())); - DCHECK_NE(requests[0]->GetRequestType(), requests[1]->GetRequestType()); - } - - chip_button_->SetText(GetPermissionMessage()); - chip_button_->SetIcon(&GetPermissionIconId()); - - Show(ShouldBubbleStartOpen()); - - if (!ShouldBubbleStartOpen()) { - GetViewAccessibility().AnnounceText(l10n_util::GetStringUTF16( - IDS_PERMISSIONS_REQUESTED_SCREENREADER_ANNOUNCEMENT)); - } -} - -void PermissionChip::FinalizeRequest() { - SetVisible(false); - chip_button_->ResetAnimation(); collapse_timer_.AbandonAndStop(); dismiss_timer_.AbandonAndStop(); - delegate_ = nullptr; - PreferredSizeChanged(); } void PermissionChip::Hide() { @@ -128,62 +92,36 @@ void PermissionChip::Reshow() { if (GetVisible()) return; + SetVisible(true); Show(/*always_open_bubble=*/false); } -bool PermissionChip::GetActiveRequest() const { - return !!delegate_; -} - void PermissionChip::OnMouseEntered(const ui::MouseEvent& event) { if (!chip_button_->is_animating()) RestartTimersOnInteraction(); } -void PermissionChip::OnWidgetDestroying(views::Widget* widget) { +void PermissionChip::AddedToWidget() { + views::AccessiblePaneView::AddedToWidget(); + + if (!should_start_open_) { + GetViewAccessibility().AnnounceText(l10n_util::GetStringUTF16( + IDS_PERMISSIONS_REQUESTED_SCREENREADER_ANNOUNCEMENT)); + } +} + +void PermissionChip::OnWidgetClosing(views::Widget* widget) { widget->RemoveObserver(this); // If permission request is still active after the prompt was closed, // collapse the chip. - if (delegate_) - Collapse(/*allow_restart=*/false); + Collapse(/*allow_restart=*/false); } bool PermissionChip::IsBubbleShowing() const { return false; } -bool PermissionChip::ShouldBubbleStartOpen() const { - if (base::FeatureList::IsEnabled( - permissions::features::kPermissionChipGestureSensitive)) { - auto requests = delegate_->Requests(); - const bool has_gesture = - std::any_of(requests.begin(), requests.end(), [](auto* request) { - return request->GetGestureType() == - permissions::PermissionRequestGestureType::GESTURE; - }); - if (has_gesture) - return true; - } - if (base::FeatureList::IsEnabled( - permissions::features::kPermissionChipRequestTypeSensitive)) { - // Notifications and geolocation are targeted here because they are usually - // not necessary for the website to function correctly, so they can safely - // be given less prominence. - auto requests = delegate_->Requests(); - const bool is_geolocation_or_notifications = - std::any_of(requests.begin(), requests.end(), [](auto* request) { - auto request_type = request->GetRequestType(); - return request_type == permissions::RequestType::kNotifications || - request_type == permissions::RequestType::kGeolocation; - }); - if (!is_geolocation_or_notifications) - return true; - } - return false; -} - void PermissionChip::Show(bool always_open_bubble) { - SetVisible(true); // TODO(olesiamarukhno): Add tests for animation logic. chip_button_->ResetAnimation(); if (!delegate_->WasCurrentRequestAlreadyDisplayed() || always_open_bubble) { @@ -196,7 +134,7 @@ void PermissionChip::ExpandAnimationEnded() { StartCollapseTimer(); - if (ShouldBubbleStartOpen()) + if (should_start_open_) OpenBubble(); } @@ -238,14 +176,13 @@ } void PermissionChip::Dismiss() { - if (delegate_) { - delegate_->Closing(); - } GetViewAccessibility().AnnounceText(l10n_util::GetStringUTF16( IDS_PERMISSIONS_EXPIRED_SCREENREADER_ANNOUNCEMENT)); + + // `delegate_->Closing()` will destroy `this`. It's not safe to run any code + // afterwards. + delegate_->Closing(); } BEGIN_METADATA(PermissionChip, views::View) -ADD_READONLY_PROPERTY_METADATA(bool, ActiveRequest) -ADD_READONLY_PROPERTY_METADATA(std::u16string, PermissionMessage) END_METADATA
diff --git a/chrome/browser/ui/views/location_bar/permission_chip.h b/chrome/browser/ui/views/location_bar/permission_chip.h index bfdb34b..096880a0 100644 --- a/chrome/browser/ui/views/location_bar/permission_chip.h +++ b/chrome/browser/ui/views/location_bar/permission_chip.h
@@ -30,33 +30,29 @@ public BubbleOwnerDelegate { public: METADATA_HEADER(PermissionChip); - PermissionChip(); + PermissionChip(permissions::PermissionPrompt::Delegate* delegate, + const gfx::VectorIcon& icon, + std::u16string message, + bool should_start_open); PermissionChip(const PermissionChip& chip) = delete; PermissionChip& operator=(const PermissionChip& chip) = delete; ~PermissionChip() override; - // Displays a request as a chip. - virtual void DisplayRequest( - permissions::PermissionPrompt::Delegate* delegate); - - // Stops displaying the current request. - virtual void FinalizeRequest(); - // Opens the permission prompt bubble. virtual void OpenBubble() = 0; void Hide(); void Reshow(); - bool GetActiveRequest() const; views::Button* button() { return chip_button_; } bool is_fully_collapsed() const { return chip_button_->is_fully_collapsed(); } // views::View: void OnMouseEntered(const ui::MouseEvent& event) override; + void AddedToWidget() override; // views::WidgetObserver: - void OnWidgetDestroying(views::Widget* widget) override; + void OnWidgetClosing(views::Widget* widget) override; // BubbleOwnerDelegate: bool IsBubbleShowing() const override; @@ -64,20 +60,14 @@ virtual views::BubbleDialogDelegateView* GetPermissionPromptBubbleForTest() = 0; + bool should_start_open_for_testing() { return should_start_open_; } + protected: permissions::PermissionPrompt::Delegate* delegate() const { return delegate_; } private: - // Returns the chip's label. - virtual std::u16string GetPermissionMessage() const = 0; - - // Returns the chip's icon. - virtual const gfx::VectorIcon& GetPermissionIconId() const = 0; - - virtual bool ShouldBubbleStartOpen() const; - void Show(bool always_open_bubble); void ExpandAnimationEnded(); void ChipButtonPressed(); @@ -86,11 +76,10 @@ void Collapse(bool allow_restart); void StartDismissTimer(); void Dismiss(); - void AnimateCollapse(); void AnimateExpand(); - permissions::PermissionPrompt::Delegate* delegate_ = nullptr; + permissions::PermissionPrompt::Delegate* const delegate_; // A timer used to collapse the chip after a delay. base::OneShotTimer collapse_timer_; @@ -101,6 +90,8 @@ // The button that displays the icon and text. OmniboxChipButton* chip_button_ = nullptr; + + bool should_start_open_ = false; }; #endif // CHROME_BROWSER_UI_VIEWS_LOCATION_BAR_PERMISSION_CHIP_H_
diff --git a/chrome/browser/ui/views/location_bar/permission_request_chip.cc b/chrome/browser/ui/views/location_bar/permission_request_chip.cc index f096e814d..8da0740 100644 --- a/chrome/browser/ui/views/location_bar/permission_request_chip.cc +++ b/chrome/browser/ui/views/location_bar/permission_request_chip.cc
@@ -11,6 +11,7 @@ #include "chrome/browser/ui/views/permission_bubble/permission_prompt_bubble_view.h" #include "chrome/browser/ui/views/permission_bubble/permission_prompt_style.h" #include "chrome/grit/generated_resources.h" +#include "components/permissions/features.h" #include "components/permissions/permission_request.h" #include "components/permissions/request_type.h" #include "components/strings/grit/components_strings.h" @@ -27,29 +28,104 @@ bool IsCameraPermission(permissions::RequestType type) { return type == permissions::RequestType::kCameraStream; } + +bool IsCameraOrMicPermission(permissions::RequestType type) { + return type == permissions::RequestType::kCameraStream || + type == permissions::RequestType::kMicStream; +} + +const gfx::VectorIcon& GetPermissionIconId( + permissions::PermissionPrompt::Delegate* delegate) { + DCHECK(delegate); + auto requests = delegate->Requests(); + if (requests.size() == 1) + return permissions::GetIconId(requests[0]->GetRequestType()); + + // When we have two requests, it must be microphone & camera. Then we need to + // use the icon from the camera request. + return IsCameraPermission(requests[0]->GetRequestType()) + ? permissions::GetIconId(requests[0]->GetRequestType()) + : permissions::GetIconId(requests[1]->GetRequestType()); +} + +std::u16string GetPermissionMessage( + permissions::PermissionPrompt::Delegate* delegate) { + DCHECK(delegate); + + auto requests = delegate->Requests(); + + return requests.size() == 1 + ? requests[0]->GetChipText().value() + : l10n_util::GetStringUTF16( + IDS_MEDIA_CAPTURE_VIDEO_AND_AUDIO_PERMISSION_CHIP); +} + +void VerifyCameraAndMicRequest( + permissions::PermissionPrompt::Delegate* delegate) { + DCHECK(delegate); + + const std::vector<permissions::PermissionRequest*>& requests = + delegate->Requests(); + + // TODO(olesiamarukhno): Add combined camera & microphone permission and + // update delegate to contain only one request at a time. + DCHECK(requests.size() == 1u || requests.size() == 2u); + if (requests.size() == 2) { + DCHECK(IsCameraOrMicPermission(requests[0]->GetRequestType())); + DCHECK(IsCameraOrMicPermission(requests[1]->GetRequestType())); + DCHECK_NE(requests[0]->GetRequestType(), requests[1]->GetRequestType()); + } +} + +bool ShouldBubbleStartOpen(permissions::PermissionPrompt::Delegate* delegate) { + if (base::FeatureList::IsEnabled( + permissions::features::kPermissionChipGestureSensitive)) { + auto requests = delegate->Requests(); + const bool has_gesture = + std::any_of(requests.begin(), requests.end(), [](auto* request) { + return request->GetGestureType() == + permissions::PermissionRequestGestureType::GESTURE; + }); + if (has_gesture) + return true; + } + if (base::FeatureList::IsEnabled( + permissions::features::kPermissionChipRequestTypeSensitive)) { + // Notifications and geolocation are targeted here because they are usually + // not necessary for the website to function correctly, so they can safely + // be given less prominence. + auto requests = delegate->Requests(); + const bool is_geolocation_or_notifications = + std::any_of(requests.begin(), requests.end(), [](auto* request) { + auto request_type = request->GetRequestType(); + return request_type == permissions::RequestType::kNotifications || + request_type == permissions::RequestType::kGeolocation; + }); + if (!is_geolocation_or_notifications) + return true; + } + return false; +} + } // namespace -PermissionRequestChip::PermissionRequestChip(Browser* browser) - : browser_(browser) {} +PermissionRequestChip::PermissionRequestChip( + Browser* browser, + permissions::PermissionPrompt::Delegate* delegate) + : PermissionChip(delegate, + GetPermissionIconId(delegate), + GetPermissionMessage(delegate), + ShouldBubbleStartOpen(delegate)), + browser_(browser) { + chip_shown_time_ = base::TimeTicks::Now(); + VerifyCameraAndMicRequest(delegate); +} PermissionRequestChip::~PermissionRequestChip() { if (prompt_bubble_) prompt_bubble_->GetWidget()->Close(); } -void PermissionRequestChip::DisplayRequest( - permissions::PermissionPrompt::Delegate* delegate) { - chip_shown_time_ = base::TimeTicks::Now(); - PermissionChip::DisplayRequest(delegate); -} - -void PermissionRequestChip::FinalizeRequest() { - PermissionChip::FinalizeRequest(); - already_recorded_interaction_ = false; - if (prompt_bubble_) - prompt_bubble_->GetWidget()->Close(); -} - void PermissionRequestChip::OpenBubble() { // The prompt bubble is either not opened yet or already closed on // deactivation. @@ -64,50 +140,24 @@ RecordChipButtonPressed(); } -void PermissionRequestChip::OnWidgetDestroying(views::Widget* widget) { - DCHECK_EQ(widget, prompt_bubble_->GetWidget()); - PermissionChip::OnWidgetDestroying(widget); - prompt_bubble_ = nullptr; -} - views::BubbleDialogDelegateView* PermissionRequestChip::GetPermissionPromptBubbleForTest() { return prompt_bubble_; } +void PermissionRequestChip::OnWidgetClosing(views::Widget* widget) { + DCHECK_EQ(widget, prompt_bubble_->GetWidget()); + PermissionChip::OnWidgetClosing(widget); + prompt_bubble_ = nullptr; +} + bool PermissionRequestChip::IsBubbleShowing() const { return prompt_bubble_; } -const gfx::VectorIcon& PermissionRequestChip::GetPermissionIconId() const { - auto requests = delegate()->Requests(); - if (requests.size() == 1) - return permissions::GetIconId(requests[0]->GetRequestType()); - - // When we have two requests, it must be microphone & camera. Then we need to - // use the icon from the camera request. - return IsCameraPermission(requests[0]->GetRequestType()) - ? permissions::GetIconId(requests[0]->GetRequestType()) - : permissions::GetIconId(requests[1]->GetRequestType()); -} - -std::u16string PermissionRequestChip::GetPermissionMessage() const { - if (!delegate()) - return std::u16string(); - auto requests = delegate()->Requests(); - - return requests.size() == 1 - ? requests[0]->GetChipText().value() - : l10n_util::GetStringUTF16( - IDS_MEDIA_CAPTURE_VIDEO_AND_AUDIO_PERMISSION_CHIP); -} - void PermissionRequestChip::RecordChipButtonPressed() { - if (!already_recorded_interaction_) { base::UmaHistogramLongTimes("Permissions.Chip.TimeToInteraction", base::TimeTicks::Now() - chip_shown_time_); - already_recorded_interaction_ = true; - } } BEGIN_METADATA(PermissionRequestChip, views::View)
diff --git a/chrome/browser/ui/views/location_bar/permission_request_chip.h b/chrome/browser/ui/views/location_bar/permission_request_chip.h index 5280780..bcbce6d 100644 --- a/chrome/browser/ui/views/location_bar/permission_request_chip.h +++ b/chrome/browser/ui/views/location_bar/permission_request_chip.h
@@ -14,42 +14,26 @@ class PermissionRequestChip : public PermissionChip { public: METADATA_HEADER(PermissionRequestChip); - explicit PermissionRequestChip(Browser* browser); + explicit PermissionRequestChip( + Browser* browser, + permissions::PermissionPrompt::Delegate* delegate); PermissionRequestChip(const PermissionRequestChip& chip) = delete; PermissionRequestChip& operator=(const PermissionRequestChip& chip) = delete; ~PermissionRequestChip() override; // PermissionChip: - void DisplayRequest( - permissions::PermissionPrompt::Delegate* delegate) override; - - // PermissionChip: - void FinalizeRequest() override; - - // PermissionChip: void OpenBubble() override; + views::BubbleDialogDelegateView* GetPermissionPromptBubbleForTest() override; // views::WidgetObserver: - void OnWidgetDestroying(views::Widget* widget) override; - - // PermissionChip: - views::BubbleDialogDelegateView* GetPermissionPromptBubbleForTest() override; + void OnWidgetClosing(views::Widget* widget) override; // BubbleOwnerDelegate: bool IsBubbleShowing() const override; private: - // PermissionChip: - const gfx::VectorIcon& GetPermissionIconId() const override; - - // PermissionChip: - std::u16string GetPermissionMessage() const override; - void RecordChipButtonPressed(); - // If uma metric was already recorded on the button click. - bool already_recorded_interaction_ = false; - Browser* browser_ = nullptr; // The time when the chip was displayed.
diff --git a/chrome/browser/ui/views/location_bar/permission_request_chip_browsertest.cc b/chrome/browser/ui/views/location_bar/permission_request_chip_browsertest.cc index 71f783a..263c58d 100644 --- a/chrome/browser/ui/views/location_bar/permission_request_chip_browsertest.cc +++ b/chrome/browser/ui/views/location_bar/permission_request_chip_browsertest.cc
@@ -49,7 +49,7 @@ bool VerifyUi() override { LocationBarView* lbv = GetLocationBarView(); PermissionChip* chip = lbv->chip(); - if (!chip || !chip->GetVisible()) + if (!chip) return false; // TODO(olesiamrukhno): VerifyPixelUi works only for these platforms, revise
diff --git a/chrome/browser/ui/views/menu_interactive_uitest.cc b/chrome/browser/ui/views/menu_interactive_uitest.cc index e94c2fcb..b7db619 100644 --- a/chrome/browser/ui/views/menu_interactive_uitest.cc +++ b/chrome/browser/ui/views/menu_interactive_uitest.cc
@@ -108,7 +108,7 @@ IN_PROC_BROWSER_TEST_F(MenuControllerUITest, TestMouseOverShownMenu) { #if !BUILDFLAG(IS_CHROMEOS_ASH) - ui::AXPlatformNode::NotifyAddAXModeFlags(ui::kAXModeComplete); + ui::testing::ScopedAxModeSetter ax_mode_setter(ui::kAXModeComplete); #endif // Create a parent widget. @@ -203,7 +203,7 @@ // Going into full screen mode prevents pre-test focus and mouse position // state from affecting test, and helps ui_controls function correctly. chrome::ToggleFullscreenMode(browser()); - ui::AXPlatformNode::NotifyAddAXModeFlags(ui::kAXModeComplete); + ui::testing::ScopedAxModeSetter ax_mode_setter(ui::kAXModeComplete); MenuDelegate menu_delegate; MenuItemView* menu_item = new MenuItemView(&menu_delegate); AXEventCounter ax_counter(views::AXEventManager::Get());
diff --git a/chrome/browser/ui/views/page_info/page_info_bubble_view.cc b/chrome/browser/ui/views/page_info/page_info_bubble_view.cc index bd432423..9849c1be 100644 --- a/chrome/browser/ui/views/page_info/page_info_bubble_view.cc +++ b/chrome/browser/ui/views/page_info/page_info_bubble_view.cc
@@ -556,7 +556,7 @@ } // Add the Certificate Section. - const ui::ImageModel icon = PageInfoUI::GetCertificateIcon(); + const ui::ImageModel icon = PageInfoUI::GetValidCertificateIcon(); const std::u16string secondary_text = l10n_util::GetStringUTF16( valid_identity ? IDS_PAGE_INFO_CERTIFICATE_VALID_PARENTHESIZED : IDS_PAGE_INFO_CERTIFICATE_INVALID_PARENTHESIZED);
diff --git a/chrome/browser/ui/views/page_info/page_info_main_view.cc b/chrome/browser/ui/views/page_info/page_info_main_view.cc index 4758fc1..8b7e69f 100644 --- a/chrome/browser/ui/views/page_info/page_info_main_view.cc +++ b/chrome/browser/ui/views/page_info/page_info_main_view.cc
@@ -12,6 +12,7 @@ #include "chrome/browser/ui/views/chrome_layout_provider.h" #include "chrome/browser/ui/views/chrome_typography.h" #include "chrome/browser/ui/views/page_info/chosen_object_view.h" +#include "chrome/browser/ui/views/page_info/page_info_security_content_view.h" #include "chrome/browser/vr/vr_tab_helper.h" #include "chrome/common/url_constants.h" #include "components/page_info/page_info_ui_delegate.h" @@ -270,7 +271,6 @@ GetSecurityDescription(identity_info); title_->SetText(base::UTF8ToUTF16(identity_info.site_identity)); - SetSecurityDescriptionType(security_description->type); security_container_view_->RemoveAllChildViews(true); if (security_description->summary_style == SecuritySummaryColor::GREEN) { @@ -288,9 +288,10 @@ .release()); connection_button_->SetTitleText(security_description->summary); } else { - security_view_ = security_container_view_->AddChildView( - std::make_unique<SecurityInformationView>(GetSideMargin())); - UpdateSecurityView(identity_info); + security_content_view_ = security_container_view_->AddChildView( + std::make_unique<PageInfoSecurityContentView>( + presenter_, /*is_standalone_page=*/false)); + security_content_view_->SetIdentityInfo(identity_info); } details_text_ = security_description->details; @@ -403,9 +404,6 @@ case PageInfoMainView::VIEW_ID_PAGE_INFO_LINK_OR_BUTTON_COOKIE_DIALOG: presenter_->OpenCookiesDialog(); break; - case PageInfoMainView::VIEW_ID_PAGE_INFO_LINK_OR_BUTTON_CERTIFICATE_VIEWER: - presenter_->OpenCertificateDialog(certificate_.get()); - break; default: NOTREACHED(); } @@ -447,28 +445,6 @@ permissions_set->AddPaddingColumn(views::GridLayout::kFixedSize, side_margin); } -void PageInfoMainView::ResetDecisionsClicked() { - presenter_->OnRevokeSSLErrorBypassButtonPressed(); - GetWidget()->Close(); -} - -void PageInfoMainView::SecurityDetailsClicked(const ui::Event& event) { - if (GetSecurityDescriptionType() == SecurityDescriptionType::SAFETY_TIP) - presenter_->OpenSafetyTipHelpCenterPage(); - else - presenter_->OpenConnectionHelpCenterPage(event); -} - -PageInfoUI::SecurityDescriptionType -PageInfoMainView::GetSecurityDescriptionType() const { - return security_description_type_; -} - -void PageInfoMainView::SetSecurityDescriptionType( - const PageInfoUI::SecurityDescriptionType& type) { - security_description_type_ = type; -} - gfx::Size PageInfoMainView::CalculatePreferredSize() const { if (site_settings_view_ == nullptr && permissions_view_ == nullptr) { return views::View::CalculatePreferredSize(); @@ -516,101 +492,3 @@ return header; } - -void PageInfoMainView::UpdateSecurityView(const IdentityInfo& identity_info) { - std::unique_ptr<PageInfoUI::SecurityDescription> security_description = - GetSecurityDescription(identity_info); - - DCHECK(security_view_); - DCHECK_EQ(security_description->summary_style, SecuritySummaryColor::RED); - security_view_->SetIcon(PageInfoUI::GetConnectionNotSecureIcon()); - security_view_->SetSummary(security_description->summary, STYLE_RED); - security_view_->SetDetails( - security_description->details, - base::BindRepeating(&PageInfoMainView::SecurityDetailsClicked, - base::Unretained(this))); - if (identity_info.certificate) { - certificate_ = identity_info.certificate; - - if (identity_info.show_ssl_decision_revoke_button) { - security_view_->AddResetDecisionsLabel(base::BindRepeating( - &PageInfoMainView::ResetDecisionsClicked, base::Unretained(this))); - } - - // Show information about the page's certificate. - // The text of link to the Certificate Viewer varies depending on the - // validity of the Certificate. - const bool valid_identity = - (identity_info.identity_status != PageInfo::SITE_IDENTITY_STATUS_ERROR); - std::u16string tooltip; - if (valid_identity) { - tooltip = l10n_util::GetStringFUTF16( - IDS_PAGE_INFO_CERTIFICATE_VALID_LINK_TOOLTIP, - base::UTF8ToUTF16(certificate_->issuer().GetDisplayName())); - } else { - tooltip = l10n_util::GetStringUTF16( - IDS_PAGE_INFO_CERTIFICATE_INVALID_LINK_TOOLTIP); - } - - // Add the Certificate Section. - const ui::ImageModel icon = PageInfoUI::GetCertificateIcon(); - const std::u16string secondary_text = l10n_util::GetStringUTF16( - valid_identity ? IDS_PAGE_INFO_CERTIFICATE_VALID_PARENTHESIZED - : IDS_PAGE_INFO_CERTIFICATE_INVALID_PARENTHESIZED); - - std::u16string subtitle_text; - if (base::FeatureList::IsEnabled(features::kEvDetailsInPageInfo)) { - // Only show the EV certificate details if there are no errors or mixed - // content. - if (identity_info.identity_status == - PageInfo::SITE_IDENTITY_STATUS_EV_CERT && - identity_info.connection_status == - PageInfo::SITE_CONNECTION_STATUS_ENCRYPTED) { - // An EV cert is required to have an organization name and a country. - if (!certificate_->subject().organization_names.empty() && - !certificate_->subject().country_name.empty()) { - subtitle_text = l10n_util::GetStringFUTF16( - IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_EV_VERIFIED, - base::UTF8ToUTF16(certificate_->subject().organization_names[0]), - base::UTF8ToUTF16(certificate_->subject().country_name)); - } - } - } - - // If the certificate button has been added previously, remove the old one - // before recreating it. Re-adding it bumps it to the bottom of the - // container, but its unlikely that the user will notice, since other - // things are changing too. - if (certificate_button_) { - site_settings_view_->RemoveChildView(certificate_button_); - auto to_delete = std::make_unique<views::View*>(certificate_button_); - } - certificate_button_ = site_settings_view_->AddChildView( - std::make_unique<PageInfoHoverButton>( - base::BindRepeating( - [](PageInfoMainView* view) { - view->HandleMoreInfoRequest(view->certificate_button_); - }, - this), - icon, IDS_PAGE_INFO_CERTIFICATE, secondary_text, - VIEW_ID_PAGE_INFO_LINK_OR_BUTTON_CERTIFICATE_VIEWER, tooltip, - subtitle_text, PageInfoUI::GetLaunchIcon()) - .release()); - } - - if (identity_info.show_change_password_buttons) { - security_view_->AddPasswordReuseButtons( - identity_info.safe_browsing_status, - base::BindRepeating( - [](PageInfoMainView* view) { - view->presenter_->OnChangePasswordButtonPressed(); - }, - this), - base::BindRepeating( - [](PageInfoMainView* view) { - view->GetWidget()->Close(); - view->presenter_->OnAllowlistPasswordReuseButtonPressed(); - }, - this)); - } -}
diff --git a/chrome/browser/ui/views/page_info/page_info_main_view.h b/chrome/browser/ui/views/page_info/page_info_main_view.h index 7c6e0ee0..1f2a8d0 100644 --- a/chrome/browser/ui/views/page_info/page_info_main_view.h +++ b/chrome/browser/ui/views/page_info/page_info_main_view.h
@@ -15,6 +15,8 @@ #include "content/public/browser/web_contents_observer.h" #include "ui/views/view.h" +class PageInfoSecurityContentView; + // The main view of the page info, contains security information, permissions // and site-related settings. This is used in the experimental // PageInfoNewBubbleView (under a flag PageInfoV2Desktop). @@ -84,17 +86,6 @@ // be alive to finish handling the mouse or keyboard click. void HandleMoreInfoRequestAsync(int view_id); - void ResetDecisionsClicked(); - - void SecurityDetailsClicked(const ui::Event& event); - - PageInfoUI::SecurityDescriptionType GetSecurityDescriptionType() const; - - void SetSecurityDescriptionType( - const PageInfoUI::SecurityDescriptionType& type); - - void UpdateSecurityView(const IdentityInfo& identity_info); - PageInfo* presenter_; PageInfoUiDelegate* ui_delegate_; @@ -111,24 +102,21 @@ // The button that opens the "Cookies" dialog. PageInfoHoverButton* cookie_button_ = nullptr; - // The button that opens the "Certificate" dialog. - PageInfoHoverButton* certificate_button_ = nullptr; - // The button that opens up "Site Settings". views::View* site_settings_link_ = nullptr; // The view that contains the "Permissions" table of the bubble. views::View* permissions_view_ = nullptr; + // The view that contains `SecurityInformationView` and a certificate button. + PageInfoSecurityContentView* security_content_view_ = nullptr; + #if defined(OS_WIN) && BUILDFLAG(ENABLE_VR) // The view that contains ui related to features on a page, like a presenting // VR page. views::View* page_feature_info_view_ = nullptr; #endif - // The certificate provided by the site, if one exists. - scoped_refptr<net::X509Certificate> certificate_; - // These rows bundle together all the |View|s involved in a single row of the // permissions section, and keep those views updated when the underlying // |Permission| changes. @@ -136,15 +124,8 @@ views::Label* title_ = nullptr; - SecurityInformationView* security_view_ = nullptr; - views::View* security_container_view_ = nullptr; - // TODO(olesiamarukhno): Was used for tests, will update it after redesigning - // moves forward. - PageInfoUI::SecurityDescriptionType security_description_type_ = - PageInfoUI::SecurityDescriptionType::CONNECTION; - base::WeakPtrFactory<PageInfoMainView> weak_factory_{this}; };
diff --git a/chrome/browser/ui/views/page_info/page_info_security_content_view.cc b/chrome/browser/ui/views/page_info/page_info_security_content_view.cc new file mode 100644 index 0000000..85d546e --- /dev/null +++ b/chrome/browser/ui/views/page_info/page_info_security_content_view.cc
@@ -0,0 +1,171 @@ +// Copyright 2021 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 "chrome/browser/ui/views/page_info/page_info_security_content_view.h" + +#include "chrome/browser/ui/ui_features.h" +#include "chrome/browser/ui/views/chrome_layout_provider.h" +#include "chrome/browser/ui/views/chrome_typography.h" +#include "chrome/browser/ui/views/page_info/page_info_main_view.h" +#include "components/strings/grit/components_strings.h" +#include "ui/base/l10n/l10n_util.h" +#include "ui/views/layout/box_layout.h" + +PageInfoSecurityContentView::PageInfoSecurityContentView( + PageInfo* presenter, + bool is_standalone_page) + : presenter_(presenter) { + SetLayoutManager(std::make_unique<views::BoxLayout>( + views::BoxLayout::Orientation::kVertical)); + + security_view_ = AddChildView(std::make_unique<SecurityInformationView>( + ChromeLayoutProvider::Get() + ->GetInsetsMetric(views::INSETS_DIALOG) + .left())); + + if (is_standalone_page) + presenter_->InitializeUiState(this); +} + +PageInfoSecurityContentView::~PageInfoSecurityContentView() = default; + +void PageInfoSecurityContentView::SetCookieInfo( + const CookieInfoList& cookie_info_list) { + // No cookie UI in this page. +} + +void PageInfoSecurityContentView::SetPageFeatureInfo( + const PageFeatureInfo& info) { + // No page feature info in this page. +} + +void PageInfoSecurityContentView::SetIdentityInfo( + const IdentityInfo& identity_info) { + std::unique_ptr<PageInfoUI::SecurityDescription> security_description = + GetSecurityDescription(identity_info); + security_description_type_ = security_description->type; + + if (security_description->summary_style == SecuritySummaryColor::RED) { + security_view_->SetIcon(PageInfoUI::GetConnectionNotSecureIcon()); + security_view_->SetSummary(security_description->summary, STYLE_RED); + } else { + security_view_->SetIcon(PageInfoUI::GetConnectionSecureIcon()); + security_view_->SetSummary(security_description->summary, + views::style::STYLE_PRIMARY); + } + security_view_->SetDetails( + security_description->details, + base::BindRepeating(&PageInfoSecurityContentView::SecurityDetailsClicked, + base::Unretained(this))); + if (identity_info.certificate) { + certificate_ = identity_info.certificate; + + if (identity_info.show_ssl_decision_revoke_button) { + security_view_->AddResetDecisionsLabel(base::BindRepeating( + &PageInfoSecurityContentView::ResetDecisionsClicked, + base::Unretained(this))); + } + + // Show information about the page's certificate. + // The text of link to the Certificate Viewer varies depending on the + // validity of the Certificate. + const bool valid_identity = + (identity_info.identity_status != PageInfo::SITE_IDENTITY_STATUS_ERROR); + std::u16string tooltip; + if (valid_identity) { + tooltip = l10n_util::GetStringFUTF16( + IDS_PAGE_INFO_CERTIFICATE_VALID_LINK_TOOLTIP, + base::UTF8ToUTF16(certificate_->issuer().GetDisplayName())); + } else { + tooltip = l10n_util::GetStringUTF16( + IDS_PAGE_INFO_CERTIFICATE_INVALID_LINK_TOOLTIP); + } + + // Add the Certificate Section. + const ui::ImageModel icon = valid_identity + ? PageInfoUI::GetValidCertificateIcon() + : PageInfoUI::GetInvalidCertificateIcon(); + const int title_id = valid_identity + ? IDS_PAGE_INFO_CERTIFICATE_IS_VALID + : IDS_PAGE_INFO_CERTIFICATE_IS_NOT_VALID; + + std::u16string subtitle_text; + if (base::FeatureList::IsEnabled(features::kEvDetailsInPageInfo)) { + // Only show the EV certificate details if there are no errors or mixed + // content. + if (identity_info.identity_status == + PageInfo::SITE_IDENTITY_STATUS_EV_CERT && + identity_info.connection_status == + PageInfo::SITE_CONNECTION_STATUS_ENCRYPTED) { + // An EV cert is required to have an organization name and a country. + if (!certificate_->subject().organization_names.empty() && + !certificate_->subject().country_name.empty()) { + subtitle_text = l10n_util::GetStringFUTF16( + IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_EV_VERIFIED, + base::UTF8ToUTF16(certificate_->subject().organization_names[0]), + base::UTF8ToUTF16(certificate_->subject().country_name)); + } + } + } + + // If the certificate button has been added previously, remove the old one + // before recreating it. Re-adding it bumps it to the bottom of the + // container, but its unlikely that the user will notice, since other + // things are changing too. + if (certificate_button_) { + RemoveChildViewT(certificate_button_); + } + // TODO(olesiamarukhno): Add shared enum for views ID, instead of using one + // declared in `PageInfoMainView`. + certificate_button_ = AddChildView( + std::make_unique<PageInfoHoverButton>( + base::BindRepeating( + [](PageInfoSecurityContentView* view) { + view->presenter_->OpenCertificateDialog( + view->certificate_.get()); + }, + this), + icon, title_id, std::u16string(), + PageInfoMainView:: + VIEW_ID_PAGE_INFO_LINK_OR_BUTTON_CERTIFICATE_VIEWER, + tooltip, subtitle_text, PageInfoUI::GetLaunchIcon()) + .release()); + } + + if (identity_info.show_change_password_buttons) { + security_view_->AddPasswordReuseButtons( + identity_info.safe_browsing_status, + base::BindRepeating( + [](PageInfoSecurityContentView* view) { + view->presenter_->OnChangePasswordButtonPressed(); + }, + this), + base::BindRepeating( + [](PageInfoSecurityContentView* view) { + view->GetWidget()->Close(); + view->presenter_->OnAllowlistPasswordReuseButtonPressed(); + }, + this)); + } +} + +void PageInfoSecurityContentView::SetPermissionInfo( + const PermissionInfoList& permission_info_list, + ChosenObjectInfoList chosen_object_info_list) { + // No permission info in this page. +} + +void PageInfoSecurityContentView::ResetDecisionsClicked() { + presenter_->OnRevokeSSLErrorBypassButtonPressed(); + GetWidget()->Close(); +} + +void PageInfoSecurityContentView::SecurityDetailsClicked( + const ui::Event& event) { + if (security_description_type_ == SecurityDescriptionType::SAFETY_TIP) { + presenter_->OpenSafetyTipHelpCenterPage(); + } else { + presenter_->OpenConnectionHelpCenterPage(event); + } +}
diff --git a/chrome/browser/ui/views/page_info/page_info_security_content_view.h b/chrome/browser/ui/views/page_info/page_info_security_content_view.h new file mode 100644 index 0000000..ad4a61a --- /dev/null +++ b/chrome/browser/ui/views/page_info/page_info_security_content_view.h
@@ -0,0 +1,54 @@ +// Copyright 2021 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. + +#ifndef CHROME_BROWSER_UI_VIEWS_PAGE_INFO_PAGE_INFO_SECURITY_CONTENT_VIEW_H_ +#define CHROME_BROWSER_UI_VIEWS_PAGE_INFO_PAGE_INFO_SECURITY_CONTENT_VIEW_H_ + +#include "chrome/browser/ui/views/page_info/page_info_hover_button.h" +#include "chrome/browser/ui/views/page_info/security_information_view.h" +#include "components/page_info/page_info_ui.h" +#include "ui/views/view.h" + +// The view that contains `SecurityInformationView` and a certificate button. +// It is used as a content of the security subpage or is directly integrated in +// the main page if connection isn't secure. +class PageInfoSecurityContentView : public views::View, public PageInfoUI { + public: + // `is_standalone_page` is true, when this view is used as a content view of + // a subpage and this view becomes current UI for `PageInfo` by calling + // `InitializeUiState()`. Otherwise, it is part of another page (part of the + // main page if connection isn't secure). + PageInfoSecurityContentView(PageInfo* presenter, bool is_standalone_page); + ~PageInfoSecurityContentView() override; + + // PageInfoUI implementations. + void SetCookieInfo(const CookieInfoList& cookie_info_list) override; + void SetPermissionInfo(const PermissionInfoList& permission_info_list, + ChosenObjectInfoList chosen_object_info_list) override; + void SetIdentityInfo(const IdentityInfo& identity_info) override; + void SetPageFeatureInfo(const PageFeatureInfo& info) override; + + private: + void ResetDecisionsClicked(); + + void SecurityDetailsClicked(const ui::Event& event); + + PageInfo* presenter_; + + // The button that opens the "Certificate" dialog. + PageInfoHoverButton* certificate_button_ = nullptr; + + // The views that shows the status of the site's identity check. + SecurityInformationView* security_view_ = nullptr; + + // The certificate provided by the site, if one exists. + scoped_refptr<net::X509Certificate> certificate_; + + // TODO(crbug.com/1188101): Add plumbing to check this in tests or rewrite + // tests not use it. + PageInfoUI::SecurityDescriptionType security_description_type_ = + PageInfoUI::SecurityDescriptionType::CONNECTION; +}; + +#endif // CHROME_BROWSER_UI_VIEWS_PAGE_INFO_PAGE_INFO_SECURITY_CONTENT_VIEW_H_
diff --git a/chrome/browser/ui/views/payments/payment_handler_change_payment_method_browsertest.cc b/chrome/browser/ui/views/payments/payment_handler_change_payment_method_browsertest.cc index 39c000f..4be17c3 100644 --- a/chrome/browser/ui/views/payments/payment_handler_change_payment_method_browsertest.cc +++ b/chrome/browser/ui/views/payments/payment_handler_change_payment_method_browsertest.cc
@@ -30,44 +30,24 @@ : may_contain_method_url; } -enum class MethodIdentifier { kUrlBased, kBasicCard }; - struct TestCase { TestCase(const std::string& init_test_code, - const std::string& expected_output, - MethodIdentifier method_identifier = MethodIdentifier::kUrlBased) - : init_test_code(init_test_code), - expected_output(expected_output), - method_identifier(method_identifier) {} + const std::string& expected_output) + : init_test_code(init_test_code), expected_output(expected_output) {} - ~TestCase() {} + ~TestCase() = default; const std::string init_test_code; const std::string expected_output; - const MethodIdentifier method_identifier; }; class PaymentHandlerChangePaymentMethodTest : public PaymentRequestBrowserTestBase, - public testing::WithParamInterface<TestCase> { - protected: - PaymentHandlerChangePaymentMethodTest() {} - ~PaymentHandlerChangePaymentMethodTest() override {} - - private: - DISALLOW_COPY_AND_ASSIGN(PaymentHandlerChangePaymentMethodTest); -}; + public testing::WithParamInterface<TestCase> {}; IN_PROC_BROWSER_TEST_P(PaymentHandlerChangePaymentMethodTest, Test) { - if (GetParam().method_identifier == MethodIdentifier::kBasicCard) - SetSkipUiForForBasicCard(); - NavigateTo("/change_payment_method.html"); - if (GetParam().method_identifier == MethodIdentifier::kBasicCard) { - ASSERT_TRUE(content::ExecuteScript(GetActiveWebContents(), - "basicCardMethodName();")); - } std::string actual_output; ASSERT_TRUE(content::ExecuteScriptAndExtractString( GetActiveWebContents(), "install();", &actual_output)); @@ -87,34 +67,15 @@ } INSTANTIATE_TEST_SUITE_P( - NoMerchantResponse, + All, PaymentHandlerChangePaymentMethodTest, testing::Values( TestCase("initTestNoHandler();", "PaymentRequest.show(): changePaymentMethod() returned: null"), - TestCase("initTestNoHandler();", - "PaymentRequest.show(): changePaymentMethod() returned: null", - MethodIdentifier::kBasicCard))); - -INSTANTIATE_TEST_SUITE_P( - ErrorCases, - PaymentHandlerChangePaymentMethodTest, - testing::Values( TestCase("initTestReject()", "PaymentRequest.show() rejected with: Error for test"), - TestCase("initTestReject()", - "PaymentRequest.show() rejected with: Error for test", - MethodIdentifier::kBasicCard), TestCase("initTestThrow()", "PaymentRequest.show() rejected with: Error: Error for test"), - TestCase("initTestThrow()", - "PaymentRequest.show() rejected with: Error: Error for test", - MethodIdentifier::kBasicCard))); - -INSTANTIATE_TEST_SUITE_P( - MerchantResponse, - PaymentHandlerChangePaymentMethodTest, - testing::Values( TestCase( "initTestDetails()", "PaymentRequest.show(): changePaymentMethod() returned: " @@ -124,18 +85,7 @@ "\"total\":{\"amount\":{\"currency\":\"EUR\",\"value\":\"0.03\"}," "\"label\":\"\",\"pending\":false}}]," "\"paymentMethodErrors\":{\"country\":\"Unsupported country\"}," - "\"total\":{\"currency\":\"GBP\",\"value\":\"0.02\"}}"), - TestCase( - "initTestDetails()", - "PaymentRequest.show(): changePaymentMethod() returned: " - "{\"error\":\"Error for test\"," - "\"modifiers\":[{\"data\":{\"soup\":\"potato\"}," - "\"supportedMethods\":\"basic-card\"," - "\"total\":{\"amount\":{\"currency\":\"EUR\",\"value\":\"0.03\"}," - "\"label\":\"\",\"pending\":false}}]," - "\"paymentMethodErrors\":{\"country\":\"Unsupported country\"}," - "\"total\":{\"currency\":\"GBP\",\"value\":\"0.02\"}}", - MethodIdentifier::kBasicCard))); + "\"total\":{\"currency\":\"GBP\",\"value\":\"0.02\"}}"))); } // namespace } // namespace payments
diff --git a/chrome/browser/ui/views/payments/payment_request_payment_app_browsertest.cc b/chrome/browser/ui/views/payments/payment_request_payment_app_browsertest.cc index 4916af2..f30c316 100644 --- a/chrome/browser/ui/views/payments/payment_request_payment_app_browsertest.cc +++ b/chrome/browser/ui/views/payments/payment_request_payment_app_browsertest.cc
@@ -442,65 +442,6 @@ } } -// Test can pay with 'basic-card' payment method from alicepay. -IN_PROC_BROWSER_TEST_F(PaymentRequestPaymentAppTest, PayWithBasicCard) { - InstallAlicePayForMethod("basic-card"); - - { - NavigateTo( - "/payment_request_bobpay_and_basic_card_with_modifiers_test.html"); - SetDownloaderAndIgnorePortInOriginComparisonForTesting(); - - ResetEventWaiterForSequence( - {DialogEvent::PROCESSING_SPINNER_SHOWN, - DialogEvent::PROCESSING_SPINNER_HIDDEN, DialogEvent::DIALOG_OPENED, - DialogEvent::PROCESSING_SPINNER_SHOWN, DialogEvent::DIALOG_CLOSED}); - ASSERT_TRUE(content::ExecJs(GetActiveWebContents(), "buy()")); - WaitForObservedEvent(); - ExpectBodyContains({"basic-card"}); - } - - // Repeat should have identical results. - { - NavigateTo( - "/payment_request_bobpay_and_basic_card_with_modifiers_test.html"); - SetDownloaderAndIgnorePortInOriginComparisonForTesting(); - - ResetEventWaiterForSequence( - {DialogEvent::PROCESSING_SPINNER_SHOWN, - DialogEvent::PROCESSING_SPINNER_HIDDEN, DialogEvent::DIALOG_OPENED, - DialogEvent::PROCESSING_SPINNER_SHOWN, DialogEvent::DIALOG_CLOSED}); - ASSERT_TRUE(content::ExecJs(GetActiveWebContents(), "buy()")); - WaitForObservedEvent(); - ExpectBodyContains({"basic-card"}); - } -} - -// Test can cancel payment with 'basic-card' payment method from alicepay. -IN_PROC_BROWSER_TEST_F(PaymentRequestPaymentAppTest, PayWithBasicCardCancel) { - // Install both alicepay and bobpay to force showing payment sheet. - InstallAlicePayForMethod("basic-card"); - InstallBobPayForMethod("https://bobpay.com"); - - { - NavigateTo( - "/payment_request_bobpay_and_basic_card_with_modifiers_test.html"); - SetDownloaderAndIgnorePortInOriginComparisonForTesting(); - InvokePaymentRequestUI(); - ClickOnCancel(); - ExpectBodyContains({"User closed the Payment Request UI."}); - } - // Repeat should have identical results. - { - NavigateTo( - "/payment_request_bobpay_and_basic_card_with_modifiers_test.html"); - SetDownloaderAndIgnorePortInOriginComparisonForTesting(); - InvokePaymentRequestUI(); - ClickOnCancel(); - ExpectBodyContains({"User closed the Payment Request UI."}); - } -} - class PaymentRequestPaymentAppTestWithPaymentHandlersAndUiSkip : public PaymentRequestPaymentAppTest { public:
diff --git a/chrome/browser/ui/views/payments/payment_request_show_promise_browsertest.cc b/chrome/browser/ui/views/payments/payment_request_show_promise_browsertest.cc index 44a641e..4e1c762 100644 --- a/chrome/browser/ui/views/payments/payment_request_show_promise_browsertest.cc +++ b/chrome/browser/ui/views/payments/payment_request_show_promise_browsertest.cc
@@ -23,13 +23,14 @@ PaymentRequestShowPromiseTest() {} ~PaymentRequestShowPromiseTest() override {} - // Installs the payment handler for "basic-card" that responds to - // "paymentrequest" events by echoing back the "total" object. - void InstallEchoPaymentHandlerForBasicCard() { + // Installs the payment handler for window.location.href payment method that + // responds to "paymentrequest" events by echoing back the "total" object. + void InstallEchoPaymentHandler() { std::string contents; ASSERT_TRUE(content::ExecuteScriptAndExtractString( GetActiveWebContents(), "install();", &contents)); - ASSERT_EQ(contents, "instruments.set(): Payment handler installed."); + ASSERT_EQ(contents, "instruments.set(): Payment handler installed.") + << contents; } // Shows the browser payment sheet. @@ -39,7 +40,10 @@ DialogEvent::SPEC_DONE_UPDATING, DialogEvent::PROCESSING_SPINNER_HIDDEN, DialogEvent::DIALOG_OPENED}); - ASSERT_TRUE(content::ExecuteScript(GetActiveWebContents(), "buy();")); + // The boolean "true" makes the payment method be the URL of the webpage, + // which is necessary because service workers cannot use "basic-card" + // payment method (the default payment method of the test page). + ASSERT_TRUE(content::ExecuteScript(GetActiveWebContents(), "buy(true);")); WaitForObservedEvent(); EXPECT_TRUE(web_modal::WebContentsModalDialogManager::FromWebContents( GetActiveWebContents()) @@ -117,38 +121,9 @@ DISALLOW_COPY_AND_ASSIGN(PaymentRequestShowPromiseTest); }; -IN_PROC_BROWSER_TEST_F(PaymentRequestShowPromiseTest, DigitalGoods) { - base::HistogramTester histogram_tester; - NavigateTo("/show_promise/digital_goods.html"); - InstallEchoPaymentHandlerForBasicCard(); - ASSERT_TRUE(content::ExecuteScript(GetActiveWebContents(), "create();")); - ShowBrowserPaymentSheet(); - - EXPECT_TRUE(IsPayButtonEnabled()); - - OpenOrderSummaryScreen(); - - ExpectTotal("$1.00"); - - ClickOnBackArrow(); - Pay(); - - ExpectBodyContains({R"({"currency":"USD","value":"1.00"})"}); - - // The initial total in digital_goods.js is 99.99 while the final total - // is 1.00. Verify that transaction amount metrics are recorded only once and - // with final total rather than the initial one. The final total falls into - // micro transaction category. - const uint32_t kMicroTransaction = 1; - histogram_tester.ExpectUniqueSample( - "PaymentRequest.TransactionAmount.Triggered", kMicroTransaction, 1); - histogram_tester.ExpectUniqueSample( - "PaymentRequest.TransactionAmount.Completed", kMicroTransaction, 1); -} - IN_PROC_BROWSER_TEST_F(PaymentRequestShowPromiseTest, SingleOptionShipping) { NavigateTo("/show_promise/single_option_shipping.html"); - InstallEchoPaymentHandlerForBasicCard(); + InstallEchoPaymentHandler(); AddAutofillProfile(autofill::test::GetFullProfile()); AddAutofillProfile(autofill::test::GetFullProfile2()); ShowBrowserPaymentSheet(); @@ -185,7 +160,7 @@ IN_PROC_BROWSER_TEST_F(PaymentRequestShowPromiseTest, SingleOptionShippingWithUpdate) { NavigateTo("/show_promise/single_option_shipping_with_update.html"); - InstallEchoPaymentHandlerForBasicCard(); + InstallEchoPaymentHandler(); AddAutofillProfile(autofill::test::GetFullProfile()); AddAutofillProfile(autofill::test::GetFullProfile2()); ShowBrowserPaymentSheet(); @@ -221,7 +196,7 @@ IN_PROC_BROWSER_TEST_F(PaymentRequestShowPromiseTest, CannotShipError) { NavigateTo("/show_promise/us_only_shipping.html"); - InstallEchoPaymentHandlerForBasicCard(); + InstallEchoPaymentHandler(); AddAutofillProfile(autofill::test::GetFullCanadianProfile()); ShowBrowserPaymentSheet(); @@ -249,9 +224,9 @@ } IN_PROC_BROWSER_TEST_F(PaymentRequestShowPromiseTest, SkipUI) { - SetSkipUiForForBasicCard(); + base::HistogramTester histogram_tester; NavigateTo("/show_promise/digital_goods.html"); - InstallEchoPaymentHandlerForBasicCard(); + InstallEchoPaymentHandler(); ASSERT_TRUE(content::ExecuteScript(GetActiveWebContents(), "create();")); ResetEventWaiterForSequence( {DialogEvent::PROCESSING_SPINNER_SHOWN, @@ -262,10 +237,21 @@ WaitForObservedEvent(); ExpectBodyContains({R"({"currency":"USD","value":"1.00"})"}); + + // The initial total in digital_goods.js is 99.99 while the final total is + // 1.00. Verify that transaction amount metrics are recorded only once and + // with final total rather than the initial one. The final total falls into + // micro transaction category. + constexpr uint32_t kMicroTransaction = 1; + histogram_tester.ExpectUniqueSample( + "PaymentRequest.TransactionAmount.Triggered", kMicroTransaction, 1); + histogram_tester.ExpectUniqueSample( + "PaymentRequest.TransactionAmount.Completed", kMicroTransaction, 1); } IN_PROC_BROWSER_TEST_F(PaymentRequestShowPromiseTest, Reject) { NavigateTo("/show_promise/reject.html"); + InstallEchoPaymentHandler(); ResetEventWaiterForSequence( {DialogEvent::PROCESSING_SPINNER_SHOWN, DialogEvent::DIALOG_CLOSED}); ASSERT_TRUE(content::ExecuteScript(GetActiveWebContents(), "buy();")); @@ -276,6 +262,7 @@ IN_PROC_BROWSER_TEST_F(PaymentRequestShowPromiseTest, Timeout) { NavigateTo("/show_promise/timeout.html"); + InstallEchoPaymentHandler(); ResetEventWaiterForSequence( {DialogEvent::PROCESSING_SPINNER_SHOWN, DialogEvent::DIALOG_CLOSED}); ASSERT_TRUE(content::ExecuteScript(GetActiveWebContents(), "buy();")); @@ -302,6 +289,7 @@ IN_PROC_BROWSER_TEST_F(PaymentRequestShowPromiseTest, InvalidDetails) { NavigateTo("/show_promise/invalid_details.html"); + InstallEchoPaymentHandler(); ResetEventWaiterForSequence( {DialogEvent::PROCESSING_SPINNER_SHOWN, DialogEvent::DIALOG_CLOSED}); ASSERT_TRUE(content::ExecuteScript(GetActiveWebContents(), "buy();")); @@ -313,7 +301,7 @@ IN_PROC_BROWSER_TEST_F(PaymentRequestShowPromiseTest, ResolveWithEmptyDictionary) { NavigateTo("/show_promise/resolve_with_empty_dictionary.html"); - InstallEchoPaymentHandlerForBasicCard(); + InstallEchoPaymentHandler(); AddAutofillProfile(autofill::test::GetFullProfile()); ShowBrowserPaymentSheet(); @@ -340,7 +328,7 @@ IN_PROC_BROWSER_TEST_F(PaymentRequestShowPromiseTest, ResolveWithEmptyListsOfItems) { NavigateTo("/show_promise/resolve_with_empty_lists.html"); - InstallEchoPaymentHandlerForBasicCard(); + InstallEchoPaymentHandler(); AddAutofillProfile(autofill::test::GetFullProfile()); ShowBrowserPaymentSheet();
diff --git a/chrome/browser/ui/views/payments/payment_sheet_view_controller_browsertest.cc b/chrome/browser/ui/views/payments/payment_sheet_view_controller_browsertest.cc index fe096e07..ce45150 100644 --- a/chrome/browser/ui/views/payments/payment_sheet_view_controller_browsertest.cc +++ b/chrome/browser/ui/views/payments/payment_sheet_view_controller_browsertest.cc
@@ -82,354 +82,6 @@ DialogViewID::PAYMENT_SHEET_CONTACT_INFO_SECTION))); } -// Accepts 'visa' cards and requests the full contact details. -class PaymentSheetViewControllerContactDetailsTest - : public PaymentRequestBrowserTestBase { - protected: - PaymentSheetViewControllerContactDetailsTest() - : kylepay_server_(net::EmbeddedTestServer::TYPE_HTTPS) {} - - // Starts the test sever for kylepay. - void SetUpOnMainThread() override { - PaymentRequestBrowserTestBase::SetUpOnMainThread(); - - host_resolver()->AddRule("kylepay.com", "127.0.0.1"); - EXPECT_TRUE(kylepay_server_.InitializeAndListen()); - kylepay_server_.ServeFilesFromSourceDirectory( - "components/test/data/payments/kylepay.com"); - kylepay_server_.StartAcceptingConnections(); - } - - void InstallKylePayForBasicCard() { - ui_test_utils::NavigateToURL(browser(), - kylepay_server_.GetURL("kylepay.com", "/")); - EXPECT_EQ("success", content::EvalJs(GetActiveWebContents(), - "install('basic-card');")); - } - - private: - // https://kylepay.com hosts a payment app which supports delegations. - net::EmbeddedTestServer kylepay_server_; - - DISALLOW_COPY_AND_ASSIGN(PaymentSheetViewControllerContactDetailsTest); -}; - -// With no data present, the pay button should be disabled. -IN_PROC_BROWSER_TEST_F(PaymentSheetViewControllerContactDetailsTest, NoData) { - NavigateTo("/payment_request_contact_details_and_free_shipping_test.html"); - InvokePaymentRequestUI(); - - EXPECT_FALSE(IsPayButtonEnabled()); -} - -// With a supported card (Visa) present, the pay button is still disabled -// because there is no contact details. -IN_PROC_BROWSER_TEST_F(PaymentSheetViewControllerContactDetailsTest, - SupportedCard_NoContactInfo) { - NavigateTo("/payment_request_contact_details_and_free_shipping_test.html"); - AddCreditCard(autofill::test::GetCreditCard()); // Visa card. - - InvokePaymentRequestUI(); - EXPECT_FALSE(IsPayButtonEnabled()); -} - -// With a supported card (Visa) present and a complete address profile, there is -// enough information to enable the pay button. -IN_PROC_BROWSER_TEST_F(PaymentSheetViewControllerContactDetailsTest, - SupportedCard_CompleteContactInfo) { - NavigateTo("/payment_request_contact_details_and_free_shipping_test.html"); - autofill::AutofillProfile profile(autofill::test::GetFullProfile()); - AddAutofillProfile(profile); - autofill::CreditCard card(autofill::test::GetCreditCard()); // Visa card. - card.set_billing_address_id(profile.guid()); - AddCreditCard(card); - - InvokePaymentRequestUI(); - EXPECT_TRUE(IsPayButtonEnabled()); -} - -// With only an unsupported card present and a complete address profile, the pay -// button is disabled. -IN_PROC_BROWSER_TEST_F(PaymentSheetViewControllerContactDetailsTest, - UnsupportedCard_CompleteContactInfo) { - NavigateTo("/payment_request_contact_details_and_free_shipping_test.html"); - AddCreditCard(autofill::test::GetCreditCard2()); // Amex card. - AddAutofillProfile(autofill::test::GetFullProfile()); - - InvokePaymentRequestUI(); - EXPECT_FALSE(IsPayButtonEnabled()); -} - -// With a supported card (Visa) present and a *incomplete* address profile, the -// pay button is disabled. -IN_PROC_BROWSER_TEST_F(PaymentSheetViewControllerContactDetailsTest, - SupportedCard_IncompleteContactInfo) { - NavigateTo("/payment_request_contact_details_and_free_shipping_test.html"); - AddCreditCard(autofill::test::GetCreditCard()); // Visa card. - - autofill::AutofillProfile profile = autofill::test::GetFullProfile(); - // Remove the name from the profile to be stored. - profile.SetRawInfo(autofill::NAME_FIRST, u""); - profile.SetRawInfo(autofill::NAME_MIDDLE, u""); - profile.SetRawInfo(autofill::NAME_LAST, u""); - AddAutofillProfile(profile); - - InvokePaymentRequestUI(); - EXPECT_FALSE(IsPayButtonEnabled()); -} - -// Payment sheet view skips showing shipping section when the selected -// instrument supports shipping delegation, the pay button is enabled with blank -// autofill data. -IN_PROC_BROWSER_TEST_F(PaymentSheetViewControllerContactDetailsTest, - ShippingDelegation) { - // Install a payment handler which supports shipping delegation. - NavigateTo("/payment_handler.html"); - std::string expected = "success"; - EXPECT_EQ(expected, content::EvalJs(GetActiveWebContents(), "install()")); - EXPECT_EQ(expected, - content::EvalJs(GetActiveWebContents(), - "enableDelegations(['shippingAddress'])")); - - // Install KylePay which also supports shipping delegation to force showing - // payment sheet. - InstallKylePayForBasicCard(); - - // Invoke a payment request with basic-card and methodName = - // window.location.origin + '/pay' supportedMethods (see payment_handler.js). - NavigateTo("/payment_handler.html"); - ResetEventWaiterForDialogOpened(); - EXPECT_EQ( - expected, - content::EvalJs(GetActiveWebContents(), - "paymentRequestWithOptions({requestShipping: true})")); - WaitForObservedEvent(); - - // Verify that no autofill profile exists. - EXPECT_TRUE(GetDataManager()->GetProfiles().empty()); - - // Shipping address and shipping option sections are not shown in the payment - // sheet view since handling shipping address is delegated to the selected - // payment handler (payment_handler.js). - EXPECT_EQ(nullptr, - dialog_view()->GetViewByID(static_cast<int>( - DialogViewID::PAYMENT_SHEET_SHIPPING_ADDRESS_SECTION_BUTTON))); - EXPECT_EQ(nullptr, dialog_view()->GetViewByID(static_cast<int>( - DialogViewID::PAYMENT_SHEET_SHIPPING_OPTION_SECTION))); - - // Payment button should be enabled with blank autofill profiles since the - // payment handler supports shipping delegation. - EXPECT_TRUE(IsPayButtonEnabled()); - - // When a 3rd party payment app is selected the primary button should have - // "Continue" label. - EXPECT_EQ(l10n_util::GetStringUTF16(IDS_PAYMENTS_CONTINUE_BUTTON), - GetPrimaryButtonLabel()); -} - -// Payment sheet view skips showing contact section when the selected instrument -// supports contact delegation. -IN_PROC_BROWSER_TEST_F(PaymentSheetViewControllerContactDetailsTest, - ContactDelegation) { - // Install a payment handler which supports contact delegation. - NavigateTo("/payment_handler.html"); - std::string expected = "success"; - EXPECT_EQ(expected, content::EvalJs(GetActiveWebContents(), "install()")); - EXPECT_EQ( - expected, - content::EvalJs( - GetActiveWebContents(), - "enableDelegations(['payerName', 'payerPhone', 'payerEmail'])")); - - // Install KylePay which also supports contact delegation to force showing - // payment sheet. - InstallKylePayForBasicCard(); - - // Invoke a payment request with basic-card and methodName = - // window.location.origin + '/pay' supportedMethods (see payment_handler.js). - NavigateTo("/payment_handler.html"); - ResetEventWaiterForDialogOpened(); - EXPECT_EQ( - expected, - content::EvalJs(GetActiveWebContents(), - "paymentRequestWithOptions({requestPayerName: true, " - "requestPayerPhone: true, requestPayerEmail: true})")); - WaitForObservedEvent(); - - // Verify that no autofill profile exists. - EXPECT_TRUE(GetDataManager()->GetProfiles().empty()); - - // Contact info section is not shown in the payment sheet view since handling - // required contact information is delegated to the selected payment handler - // (payment_handler.js). - EXPECT_EQ(nullptr, - dialog_view()->GetViewByID(static_cast<int>( - DialogViewID::PAYMENT_SHEET_CONTACT_INFO_SECTION_BUTTON))); - - // Payment button should be enabled with blank autofill profiles since the - // payment handler supports contact delegation. - EXPECT_TRUE(IsPayButtonEnabled()); -} - -// Payment sheet view shows shipping section when the selected instrument -// supports contact delegation only. -IN_PROC_BROWSER_TEST_F(PaymentSheetViewControllerContactDetailsTest, - ContactOnlyDelegationShippingRequested) { - // Install a payment handler which supports contact delegation. - NavigateTo("/payment_handler.html"); - std::string expected = "success"; - EXPECT_EQ(expected, content::EvalJs(GetActiveWebContents(), "install()")); - EXPECT_EQ( - expected, - content::EvalJs( - GetActiveWebContents(), - "enableDelegations(['payerName', 'payerPhone', 'payerEmail'])")); - // Invoke a payment request with basic-card and methodName = - // window.location.origin + '/pay' supportedMethods (see payment_handler.js). - ResetEventWaiterForDialogOpened(); - EXPECT_EQ( - expected, - content::EvalJs(GetActiveWebContents(), - "paymentRequestWithOptions({requestShipping: true})")); - WaitForObservedEvent(); - - // Verify that no autofill profile exists. - EXPECT_TRUE(GetDataManager()->GetProfiles().empty()); - - // Shipping section is still shown since the selected payment instrument does - // not support delegation of shipping address. - EXPECT_NE(nullptr, - dialog_view()->GetViewByID(static_cast<int>( - DialogViewID::PAYMENT_SHEET_SHIPPING_ADDRESS_SECTION_BUTTON))); - - // Payment button should be disabled since the browser should collect shipping - // address. - EXPECT_FALSE(IsPayButtonEnabled()); -} - -// Payment sheet view shows contact section when the selected instrument does -// not support delegation of all required contact details. -IN_PROC_BROWSER_TEST_F(PaymentSheetViewControllerContactDetailsTest, - PartialContactDelegation) { - // Install a payment handler which supports delegation of all required contact - // information except payer's email. - NavigateTo("/payment_handler.html"); - std::string expected = "success"; - EXPECT_EQ(expected, content::EvalJs(GetActiveWebContents(), "install()")); - EXPECT_EQ(expected, - content::EvalJs(GetActiveWebContents(), - "enableDelegations(['payerName', 'payerPhone'])")); - // Invoke a payment request with basic-card and methodName = - // window.location.origin + '/pay' supportedMethods (see payment_handler.js). - ResetEventWaiterForDialogOpened(); - EXPECT_EQ( - expected, - content::EvalJs(GetActiveWebContents(), - "paymentRequestWithOptions({requestPayerName: true, " - "requestPayerPhone: true, requestPayerEmail: true})")); - WaitForObservedEvent(); - - // Verify that no autofill profile exists. - EXPECT_TRUE(GetDataManager()->GetProfiles().empty()); - - // Contact info section is still shown since the selected payment instrument - // does not support delegation of all required contact info. - EXPECT_NE(nullptr, - dialog_view()->GetViewByID(static_cast<int>( - DialogViewID::PAYMENT_SHEET_CONTACT_INFO_SECTION_BUTTON))); - - // Payment button should be disabled since the browser should collect payer's - // email. - EXPECT_FALSE(IsPayButtonEnabled()); -} - -// If shipping and contact info are requested, show all the rows. -IN_PROC_BROWSER_TEST_F(PaymentSheetViewControllerContactDetailsTest, - AllRowsPresent) { - NavigateTo("/payment_request_contact_details_and_free_shipping_test.html"); - InvokePaymentRequestUI(); - - EXPECT_NE(nullptr, dialog_view()->GetViewByID(static_cast<int>( - DialogViewID::PAYMENT_SHEET_SUMMARY_SECTION))); - // The buttons to select payment methods and shipping address are present. - EXPECT_NE(nullptr, - dialog_view()->GetViewByID(static_cast<int>( - DialogViewID::PAYMENT_SHEET_PAYMENT_METHOD_SECTION_BUTTON))); - EXPECT_NE(nullptr, - dialog_view()->GetViewByID(static_cast<int>( - DialogViewID::PAYMENT_SHEET_SHIPPING_ADDRESS_SECTION_BUTTON))); - // Shipping option section (or its button) is not yet present. - EXPECT_EQ(nullptr, dialog_view()->GetViewByID(static_cast<int>( - DialogViewID::PAYMENT_SHEET_SHIPPING_OPTION_SECTION))); - EXPECT_EQ(nullptr, - dialog_view()->GetViewByID(static_cast<int>( - DialogViewID::PAYMENT_SHEET_SHIPPING_OPTION_SECTION_BUTTON))); - // Contact details button is present. - EXPECT_NE(nullptr, - dialog_view()->GetViewByID(static_cast<int>( - DialogViewID::PAYMENT_SHEET_CONTACT_INFO_SECTION_BUTTON))); -} - -IN_PROC_BROWSER_TEST_F(PaymentSheetViewControllerContactDetailsTest, - AllClickableRowsPresent) { - NavigateTo("/payment_request_contact_details_and_free_shipping_test.html"); - autofill::AutofillProfile profile(autofill::test::GetFullProfile()); - AddAutofillProfile(profile); - autofill::CreditCard card(autofill::test::GetCreditCard()); // Visa card. - card.set_billing_address_id(profile.guid()); - AddCreditCard(card); - InvokePaymentRequestUI(); - - EXPECT_NE(nullptr, dialog_view()->GetViewByID(static_cast<int>( - DialogViewID::PAYMENT_SHEET_SUMMARY_SECTION))); - EXPECT_NE(nullptr, dialog_view()->GetViewByID(static_cast<int>( - DialogViewID::PAYMENT_SHEET_PAYMENT_METHOD_SECTION))); - EXPECT_NE(nullptr, - dialog_view()->GetViewByID(static_cast<int>( - DialogViewID::PAYMENT_SHEET_SHIPPING_ADDRESS_SECTION))); - EXPECT_NE(nullptr, dialog_view()->GetViewByID(static_cast<int>( - DialogViewID::PAYMENT_SHEET_SHIPPING_OPTION_SECTION))); - EXPECT_NE(nullptr, dialog_view()->GetViewByID(static_cast<int>( - DialogViewID::PAYMENT_SHEET_CONTACT_INFO_SECTION))); -} - -IN_PROC_BROWSER_TEST_F(PaymentSheetViewControllerContactDetailsTest, - RetryWithEmptyError) { - NavigateTo("/payment_request_retry.html"); - - autofill::AutofillProfile address = autofill::test::GetFullProfile(); - AddAutofillProfile(address); - - autofill::CreditCard card = autofill::test::GetCreditCard(); - card.set_billing_address_id(address.guid()); - AddCreditCard(card); - - InvokePaymentRequestUI(); - PayWithCreditCard(u"123"); - RetryPaymentRequest("{}", dialog_view()); - - EXPECT_EQ(u"There was an error processing your order. Please try again.", - GetLabelText(DialogViewID::WARNING_LABEL)); -} - -IN_PROC_BROWSER_TEST_F(PaymentSheetViewControllerContactDetailsTest, - RetryWithError) { - NavigateTo("/payment_request_retry.html"); - - autofill::AutofillProfile address = autofill::test::GetFullProfile(); - AddAutofillProfile(address); - - autofill::CreditCard card = autofill::test::GetCreditCard(); - card.set_billing_address_id(address.guid()); - AddCreditCard(card); - - InvokePaymentRequestUI(); - PayWithCreditCard(u"123"); - RetryPaymentRequest("{ error: 'ERROR MESSAGE' }", dialog_view()); - - EXPECT_EQ(u"ERROR MESSAGE", GetLabelText(DialogViewID::WARNING_LABEL)); -} - typedef PaymentRequestBrowserTestBase PaymentHandlerUITest; IN_PROC_BROWSER_TEST_F(PaymentHandlerUITest, BackReturnsToPaymentSheet) {
diff --git a/chrome/browser/ui/views/permission_bubble/permission_bubble_interactive_uitest.cc b/chrome/browser/ui/views/permission_bubble/permission_bubble_interactive_uitest.cc index e349388c..8bb9c48 100644 --- a/chrome/browser/ui/views/permission_bubble/permission_bubble_interactive_uitest.cc +++ b/chrome/browser/ui/views/permission_bubble/permission_bubble_interactive_uitest.cc
@@ -105,7 +105,7 @@ BrowserView* browser_view = BrowserView::GetBrowserViewForBrowser(browser()); PermissionChip* chip = browser_view->toolbar()->location_bar()->chip(); - if (chip->GetVisible()) { + if (chip) { views::test::ButtonTestApi(chip->button()) .NotifyClick(ui::MouseEvent(ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(), ui::EventTimeForNow(),
diff --git a/chrome/browser/ui/views/permission_bubble/permission_prompt_bubble_view_browsertest.cc b/chrome/browser/ui/views/permission_bubble/permission_prompt_bubble_view_browsertest.cc index 05501f81..dc8aeb9 100644 --- a/chrome/browser/ui/views/permission_bubble/permission_prompt_bubble_view_browsertest.cc +++ b/chrome/browser/ui/views/permission_bubble/permission_prompt_bubble_view_browsertest.cc
@@ -73,7 +73,7 @@ base::RunLoop().RunUntilIdle(); PermissionChip* chip = GetPermissionRequestChipView(); - if (chip->GetVisible()) { + if (chip) { views::test::ButtonTestApi(chip->button()) .NotifyClick(ui::MouseEvent(ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(), ui::EventTimeForNow(), @@ -83,8 +83,7 @@ } bool VerifyUi() override { - const bool should_close_on_deactivate = - GetPermissionRequestChipView()->GetVisible(); + const bool should_close_on_deactivate = GetPermissionRequestChipView(); views::Widget* prompt_widget = test_api_->GetPromptWindow(); views::BubbleDialogDelegate* bubble_dialog = prompt_widget->widget_delegate()->AsBubbleDialogDelegate(); @@ -198,10 +197,11 @@ PermissionChip* chip = GetPermissionRequestChipView(); // If chip UI is used, two notifications will be announced: one that // permission was requested and second when bubble is opened. - if (chip->GetVisible()) + if (chip && !chip->should_start_open_for_testing()) { EXPECT_EQ(2, counter.GetCount(ax::mojom::Event::kAlert)); - else + } else { EXPECT_EQ(1, counter.GetCount(ax::mojom::Event::kAlert)); + } #else EXPECT_EQ(1, counter.GetCount(ax::mojom::Event::kAlert)); #endif
diff --git a/chrome/browser/ui/views/permission_bubble/permission_prompt_impl.cc b/chrome/browser/ui/views/permission_bubble/permission_prompt_impl.cc index b4d9cf7b..3865080 100644 --- a/chrome/browser/ui/views/permission_bubble/permission_prompt_impl.cc +++ b/chrome/browser/ui/views/permission_bubble/permission_prompt_impl.cc
@@ -72,8 +72,7 @@ case PermissionPromptStyle::kChip: DCHECK(!prompt_bubble_); DCHECK(chip_); - chip_->FinalizeRequest(); - chip_ = nullptr; + FinalizeChip(); break; case PermissionPromptStyle::kQuiet: DCHECK(!prompt_bubble_); @@ -125,15 +124,14 @@ break; case PermissionPromptStyle::kChip: DCHECK(!prompt_bubble_); - DCHECK(chip_); - chip_ = lbv->chip(); - if (!chip_->GetActiveRequest()) - chip_->DisplayRequest(delegate_); + + if (!lbv->chip()) { + chip_ = lbv->DisplayChip(delegate_); + } // If there is fresh pending request shown as chip UI and location bar // isn't visible anymore, show bubble UI instead. if (!chip_->is_fully_collapsed() && !is_location_bar_drawn) { - chip_->FinalizeRequest(); - chip_ = nullptr; + FinalizeChip(); ShowBubble(); } break; @@ -151,8 +149,7 @@ LocationBarView* lbv = GetLocationBarView(); DCHECK(lbv); - chip_ = lbv->chip(); - chip_->DisplayRequest(delegate_); + chip_ = lbv->DisplayChip(delegate_); prompt_style_ = PermissionPromptStyle::kChip; } @@ -174,6 +171,11 @@ }); } +void PermissionPromptImpl::FinalizeChip() { + GetLocationBarView()->FinalizeChip(); + chip_ = nullptr; +} + permissions::PermissionPrompt::TabSwitchingBehavior PermissionPromptImpl::GetTabSwitchingBehavior() { return permissions::PermissionPrompt::TabSwitchingBehavior::
diff --git a/chrome/browser/ui/views/permission_bubble/permission_prompt_impl.h b/chrome/browser/ui/views/permission_bubble/permission_prompt_impl.h index eb4ef04..a7e8586 100644 --- a/chrome/browser/ui/views/permission_bubble/permission_prompt_impl.h +++ b/chrome/browser/ui/views/permission_bubble/permission_prompt_impl.h
@@ -50,12 +50,10 @@ private: LocationBarView* GetLocationBarView(); - void ShowBubble(); - void ShowChipUI(); - bool ShouldCurrentRequestUseChipUI(); + void FinalizeChip(); // The popup bubble. Not owned by this class; it will delete itself when a // decision is made.
diff --git a/chrome/browser/ui/views/profiles/profile_picker_view_browsertest.cc b/chrome/browser/ui/views/profiles/profile_picker_view_browsertest.cc index 8ae7a001..55d4261b 100644 --- a/chrome/browser/ui/views/profiles/profile_picker_view_browsertest.cc +++ b/chrome/browser/ui/views/profiles/profile_picker_view_browsertest.cc
@@ -75,8 +75,8 @@ enum class ForceEphemeralProfilesPolicy { kUnset, kEnabled, kDisabled }; const SkColor kProfileColor = SK_ColorRED; -const char16_t kWork[] = u"Work"; -const char16_t kOriginalProfileName[] = u"OriginalProfile"; +const char kWork[] = "Work"; +const char kOriginalProfileName[] = "OriginalProfile"; AccountInfo FillAccountInfo( const CoreAccountInfo& core_info, @@ -654,7 +654,7 @@ ASSERT_NE(entry, nullptr); EXPECT_FALSE(entry->IsEphemeral()); EXPECT_FALSE(entry->IsAuthenticated()); - EXPECT_EQ(entry->GetLocalProfileName(), kWork); + EXPECT_EQ(entry->GetLocalProfileName(), base::UTF8ToUTF16(kWork)); // The color is not applied if the user enters the SAML flow. EXPECT_FALSE(ThemeServiceFactory::GetForProfile(profile_being_created) ->UsingAutogeneratedTheme()); @@ -1444,11 +1444,11 @@ } // Checks if a profile matching `name` exists in the profile manager. - bool ProfileWithNameExists(const std::u16string& name) { + bool ProfileWithNameExists(const std::string& name) { for (const auto* entry : profile_manager() ->GetProfileAttributesStorage() .GetAllProfilesAttributes()) { - if (entry->GetLocalProfileName() == name) + if (entry->GetLocalProfileName() == base::UTF8ToUTF16(name)) return true; } return false; @@ -1491,7 +1491,7 @@ ->GetProfileAttributesStorage() .GetProfileAttributesWithPath(browser()->profile()->GetPath()); ASSERT_NE(entry, nullptr); - entry->SetLocalProfileName(kOriginalProfileName, + entry->SetLocalProfileName(base::UTF8ToUTF16(kOriginalProfileName), entry->IsUsingDefaultName()); } CheckPolicyApplied(browser()->profile()); @@ -1549,14 +1549,14 @@ // If the policy is set, all profiles should have been deleted. EXPECT_EQ(1u, profile_manager()->GetNumberOfProfiles()); // The current profile is not the one that was created in the previous run. - EXPECT_FALSE(ProfileWithNameExists(u"Joe")); + EXPECT_FALSE(ProfileWithNameExists("Joe")); EXPECT_FALSE(OriginalProfileExists()); return; } // If the policy is disabled or unset, the two profiles are still here. EXPECT_EQ(2u, profile_manager()->GetNumberOfProfiles()); - EXPECT_TRUE(ProfileWithNameExists(u"Joe")); + EXPECT_TRUE(ProfileWithNameExists("Joe")); EXPECT_TRUE(OriginalProfileExists()); }
diff --git a/chrome/browser/ui/views/tabs/tab_drag_controller_interactive_uitest.cc b/chrome/browser/ui/views/tabs/tab_drag_controller_interactive_uitest.cc index 98671f0e..81e22381 100644 --- a/chrome/browser/ui/views/tabs/tab_drag_controller_interactive_uitest.cc +++ b/chrome/browser/ui/views/tabs/tab_drag_controller_interactive_uitest.cc
@@ -2539,6 +2539,9 @@ ASSERT_TRUE(PressInput(tab_1_center)); ASSERT_TRUE(DragInputTo(tab_1_center + gfx::Vector2d(TabStyle::GetStandardWidth(), 0))); + BrowserView::GetBrowserViewForBrowser(browser()) + ->GetWidget() + ->LayoutRootViewIfNecessary(); EXPECT_EQ(tab_strip_width + TabStyle::GetStandardWidth(), tab_strip->width()); ASSERT_TRUE(ReleaseInput()); }
diff --git a/chrome/browser/ui/views/webauthn/webauthn_bubble_view.cc b/chrome/browser/ui/views/webauthn/webauthn_bubble_view.cc index 0af0304..b0c00de 100644 --- a/chrome/browser/ui/views/webauthn/webauthn_bubble_view.cc +++ b/chrome/browser/ui/views/webauthn/webauthn_bubble_view.cc
@@ -65,8 +65,8 @@ std::u16string WebAuthnBubbleView::GetWindowTitle() const { // TODO(crbug.com/1179014): go through ux review and i18n this string. - return users_.empty() ? u"Sign in with your security key" - : u"Choose an account to sign in"; + return base::UTF8ToUTF16(users_.empty() ? "Sign in with your security key" + : "Choose an account to sign in"); } void WebAuthnBubbleView::Init() { @@ -75,7 +75,8 @@ if (users_.empty()) { // TODO(crbug.com/1179014): go through ux review and i18n this string. std::u16string label_text = base::ReplaceStringPlaceholders( - u"To sign in to $1 with your security key, insert it and tap it", + base::UTF8ToUTF16( + "To sign in to $1 with your security key, insert it and tap it"), webauthn_ui_helpers::RpIdToElidedHost(relying_party_id_, fixed_width()), /*offset=*/nullptr); auto label = std::make_unique<views::Label>(
diff --git a/chrome/browser/ui/web_applications/web_app_browsertest.cc b/chrome/browser/ui/web_applications/web_app_browsertest.cc index 4bd0581..278a1168 100644 --- a/chrome/browser/ui/web_applications/web_app_browsertest.cc +++ b/chrome/browser/ui/web_applications/web_app_browsertest.cc
@@ -85,7 +85,6 @@ namespace { constexpr const char kExampleURL[] = "http://example.org/"; -constexpr const char16_t kExampleURL16[] = u"http://example.org/"; constexpr const char kExampleManifestURL[] = "http://example.org/manifest"; constexpr char kLaunchWebAppDisplayModeHistogram[] = "Launch.WebAppDisplayMode"; @@ -673,7 +672,7 @@ std::u16string result; clipboard->ReadText(ui::ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr, &result); - EXPECT_EQ(result, kExampleURL16); + EXPECT_EQ(result, base::UTF8ToUTF16(kExampleURL)); } // Tests that the command for popping a tab out to a PWA window is disabled in @@ -986,7 +985,8 @@ EXPECT_TRUE(app_menu_model->GetModelAndIndexForCommandId(IDC_INSTALL_PWA, &model, &index)); EXPECT_EQ(app_menu_model.get(), model); - EXPECT_EQ(model->GetLabelAt(index), u"Install Manifest test app…"); + EXPECT_EQ(model->GetLabelAt(index), + base::UTF8ToUTF16("Install Manifest test app\xE2\x80\xA6")); } // Check that no assertions are hit when showing a permission request bubble.
diff --git a/chrome/browser/ui/webui/flags/flags_ui_unittest.cc b/chrome/browser/ui/webui/flags/flags_ui_unittest.cc index ebdc04d..bc24bf7 100644 --- a/chrome/browser/ui/webui/flags/flags_ui_unittest.cc +++ b/chrome/browser/ui/webui/flags/flags_ui_unittest.cc
@@ -45,6 +45,6 @@ content::TestWebUIDataSource::Create("B"); FlagsUI::AddStrings(flags_strings->GetWebUIDataSource()); FlagsDeprecatedUI::AddStrings(deprecated_strings->GetWebUIDataSource()); - EXPECT_EQ(flags_strings->GetLocalizedStrings()->size(), - deprecated_strings->GetLocalizedStrings()->size()); + EXPECT_EQ(flags_strings->GetLocalizedStrings()->DictSize(), + deprecated_strings->GetLocalizedStrings()->DictSize()); }
diff --git a/chrome/browser/ui/webui/media_router/cast_feedback_ui.cc b/chrome/browser/ui/webui/media_router/cast_feedback_ui.cc index f5d47e1..20bb8cd9 100644 --- a/chrome/browser/ui/webui/media_router/cast_feedback_ui.cc +++ b/chrome/browser/ui/webui/media_router/cast_feedback_ui.cc
@@ -92,12 +92,14 @@ "formDescription", l10n_util::GetStringFUTF8( IDS_MEDIA_ROUTER_FEEDBACK_FORM_DESCRIPTION, - u"https://support.google.com/chromecast?p=troubleshoot_chromecast")); + base::UTF8ToUTF16("https://support.google.com/" + "chromecast?p=troubleshoot_chromecast"))); source->AddString( "setupVisibilityQuestion", l10n_util::GetStringFUTF8( IDS_MEDIA_ROUTER_FEEDBACK_SETUP_VISIBILITY_QUESTION, - u"https://support.google.com/chromecast?p=set_up_chromecast")); + base::UTF8ToUTF16( + "https://support.google.com/chromecast?p=set_up_chromecast"))); // TODO(jrw): Attach real log data. source->AddString("logData", "dummy log data");
diff --git a/chrome/browser/ui/webui/policy/policy_ui.cc b/chrome/browser/ui/webui/policy/policy_ui.cc index 67b58c6..d47584b 100644 --- a/chrome/browser/ui/webui/policy/policy_ui.cc +++ b/chrome/browser/ui/webui/policy/policy_ui.cc
@@ -72,6 +72,8 @@ {"statusUpdater", IDS_POLICY_STATUS_UPDATER}, #endif {"statusUser", IDS_POLICY_STATUS_USER}, + {"labelLastCloudReportSentTimestamp", + IDS_POLICY_LABEL_LAST_CLOUD_REPORT_SENT_TIMESTAMP}, }; source->AddLocalizedStrings(kStrings);
diff --git a/chrome/browser/ui/webui/policy/policy_ui_handler.cc b/chrome/browser/ui/webui/policy/policy_ui_handler.cc index 3b31515d..a9094104 100644 --- a/chrome/browser/ui/webui/policy/policy_ui_handler.cc +++ b/chrome/browser/ui/webui/policy/policy_ui_handler.cc
@@ -15,6 +15,7 @@ #include "base/check.h" #include "base/compiler_specific.h" #include "base/files/file_util.h" +#include "base/i18n/time_formatting.h" #include "base/json/json_writer.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" @@ -43,6 +44,7 @@ #include "chrome/common/channel_info.h" #include "chrome/grit/chromium_strings.h" #include "components/enterprise/browser/controller/browser_dm_token_storage.h" +#include "components/enterprise/browser/reporting/common_pref_names.h" #include "components/policy/core/browser/browser_policy_connector.h" #include "components/policy/core/browser/cloud/message_util.h" #include "components/policy/core/browser/configuration_policy_handler_list.h" @@ -67,6 +69,8 @@ #include "components/policy/core/common/schema_map.h" #include "components/policy/policy_constants.h" #include "components/policy/proto/device_management_backend.pb.h" +#include "components/prefs/pref_change_registrar.h" +#include "components/prefs/pref_service.h" #include "components/strings/grit/components_strings.h" #include "components/version_info/version_info.h" #include "content/public/browser/web_contents.h" @@ -358,7 +362,8 @@ public policy::CloudPolicyStore::Observer { public: explicit MachineLevelUserCloudPolicyStatusProvider( - policy::CloudPolicyCore* core); + policy::CloudPolicyCore* core, + PrefService* pref_service); ~MachineLevelUserCloudPolicyStatusProvider() override; void GetStatus(base::DictionaryValue* dict) override; @@ -369,6 +374,7 @@ private: policy::CloudPolicyCore* core_; + PrefService* pref_service_; DISALLOW_COPY_AND_ASSIGN(MachineLevelUserCloudPolicyStatusProvider); }; @@ -561,8 +567,9 @@ #if !defined(OS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_ASH) MachineLevelUserCloudPolicyStatusProvider:: - MachineLevelUserCloudPolicyStatusProvider(policy::CloudPolicyCore* core) - : core_(core) { + MachineLevelUserCloudPolicyStatusProvider(policy::CloudPolicyCore* core, + PrefService* pref_service) + : core_(core), pref_service_(pref_service) { if (core_->store()) core_->store()->AddObserver(this); } @@ -616,6 +623,16 @@ } } dict->SetString("machine", policy::GetMachineName()); + + if (pref_service_->HasPrefPath( + enterprise_reporting::kLastUploadSucceededTimestamp)) { + auto sent_time = pref_service_->GetTime( + enterprise_reporting::kLastUploadSucceededTimestamp); + dict->SetString("lastCloudReportSentTimestamp", + base::TimeFormatShortDateAndTimeWithTimeZone(sent_time)); + dict->SetString("timeSinceLastCloudReportSent", + GetTimeSinceLastRefreshString(sent_time)); + } } void MachineLevelUserCloudPolicyStatusProvider::OnStoreLoaded( @@ -930,7 +947,7 @@ if (manager) { machine_status_provider_ = std::make_unique<MachineLevelUserCloudPolicyStatusProvider>( - manager->core()); + manager->core(), g_browser_process->local_state()); } #endif // !defined(OS_ANDROID) #endif // BUILDFLAG(IS_CHROMEOS_ASH) @@ -954,6 +971,12 @@ device_status_provider_->SetStatusChangeCallback(update_callback); machine_status_provider_->SetStatusChangeCallback(update_callback); updater_status_provider_->SetStatusChangeCallback(update_callback); + + pref_change_registrar_ = std::make_unique<PrefChangeRegistrar>(); + pref_change_registrar_->Init(g_browser_process->local_state()); + pref_change_registrar_->Add( + enterprise_reporting::kLastUploadSucceededTimestamp, update_callback); + GetPolicyService()->AddObserver(policy::POLICY_DOMAIN_CHROME, this); GetPolicyService()->AddObserver(policy::POLICY_DOMAIN_EXTENSIONS, this);
diff --git a/chrome/browser/ui/webui/policy/policy_ui_handler.h b/chrome/browser/ui/webui/policy/policy_ui_handler.h index d3e2feb0..6acf616 100644 --- a/chrome/browser/ui/webui/policy/policy_ui_handler.h +++ b/chrome/browser/ui/webui/policy/policy_ui_handler.h
@@ -32,6 +32,7 @@ #endif class PolicyStatusProvider; +class PrefChangeRegistrar; struct GoogleUpdatePoliciesAndState; namespace policy { @@ -137,6 +138,8 @@ std::unique_ptr<policy::PolicyMap> updater_policies_; #endif // defined(OS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) + std::unique_ptr<PrefChangeRegistrar> pref_change_registrar_; + base::WeakPtrFactory<PolicyUIHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(PolicyUIHandler);
diff --git a/chrome/browser/ui/webui/print_preview/print_preview_ui.cc b/chrome/browser/ui/webui/print_preview/print_preview_ui.cc index c7981a5..c8307a0e5 100644 --- a/chrome/browser/ui/webui/print_preview/print_preview_ui.cc +++ b/chrome/browser/ui/webui/print_preview/print_preview_ui.cc
@@ -91,9 +91,10 @@ namespace { #if defined(OS_MAC) -const char16_t kBasicPrintShortcut[] = u"\u0028\u21e7\u2318\u0050\u0029"; +// U+0028 U+21E7 U+2318 U+0050 U+0029 in UTF8 +const char kBasicPrintShortcut[] = "\x28\xE2\x8c\xA5\xE2\x8C\x98\x50\x29"; #elif !BUILDFLAG(IS_CHROMEOS_ASH) -const char16_t kBasicPrintShortcut[] = u"(Ctrl+Shift+P)"; +const char kBasicPrintShortcut[] = "(Ctrl+Shift+P)"; #endif constexpr char kInvalidArgsForDidStartPreview[] = @@ -379,7 +380,7 @@ chrome::kCloudPrintCertificateErrorLearnMoreURL); #if !BUILDFLAG(IS_CHROMEOS_ASH) - const std::u16string shortcut_text(kBasicPrintShortcut); + const std::u16string shortcut_text(base::UTF8ToUTF16(kBasicPrintShortcut)); source->AddString("systemDialogOption", l10n_util::GetStringFUTF16( IDS_PRINT_PREVIEW_SYSTEM_DIALOG_OPTION, shortcut_text));
diff --git a/chrome/browser/ui/webui/settings/chromeos/accessibility_handler_browsertest.cc b/chrome/browser/ui/webui/settings/chromeos/accessibility_handler_browsertest.cc index f9fec63..8180941 100644 --- a/chrome/browser/ui/webui/settings/chromeos/accessibility_handler_browsertest.cc +++ b/chrome/browser/ui/webui/settings/chromeos/accessibility_handler_browsertest.cc
@@ -45,7 +45,9 @@ void TearDownOnMainThread() override { handler_.reset(); } - void AssertWebUICalls(int num) { ASSERT_EQ(num, web_ui_.call_data().size()); } + void AssertWebUICalls(unsigned int num) { + ASSERT_EQ(num, web_ui_.call_data().size()); + } bool WasWebUIListenerCalledWithStringArgument( const std::string& expected_listener,
diff --git a/chrome/browser/web_applications/components/web_app_data_retriever_unittest.cc b/chrome/browser/web_applications/components/web_app_data_retriever_unittest.cc index 8235153..5fe8399 100644 --- a/chrome/browser/web_applications/components/web_app_data_retriever_unittest.cc +++ b/chrome/browser/web_applications/components/web_app_data_retriever_unittest.cc
@@ -37,7 +37,7 @@ namespace { -const char16_t kFooTitle[] = u"Foo Title"; +const char kFooTitle[] = "Foo Title"; } // namespace @@ -130,6 +130,23 @@ std::move(quit_closure).Run(); } + std::unique_ptr<WebApplicationInfo> CreateWebApplicationInfo( + const GURL& url, + const std::string name, + const std::string description, + const GURL& scope, + base::Optional<SkColor> theme_color) { + auto web_app_info = std::make_unique<WebApplicationInfo>(); + + web_app_info->start_url = url; + web_app_info->title = base::UTF8ToUTF16(name); + web_app_info->description = base::UTF8ToUTF16(description); + web_app_info->scope = scope; + web_app_info->theme_color = theme_color; + + return web_app_info; + } + protected: content::WebContentsTester* web_contents_tester() { return content::WebContentsTester::For(web_contents()); @@ -211,7 +228,8 @@ web_contents_tester()->NavigateAndCommit(GURL("https://foo.example")); - web_contents_tester()->SetTitle(kFooTitle); + const auto web_contents_title = base::UTF8ToUTF16(kFooTitle); + web_contents_tester()->SetTitle(web_contents_title); WebApplicationInfo original_web_app_info; original_web_app_info.title = u""; @@ -228,7 +246,7 @@ // If the WebApplicationInfo has no title, we fallback to the WebContents // title. - EXPECT_EQ(kFooTitle, web_app_info()->title); + EXPECT_EQ(web_contents_title, web_app_info()->title); } TEST_F(WebAppDataRetrieverTest, @@ -344,7 +362,8 @@ TEST_F(WebAppDataRetrieverTest, GetWebApplicationInfo_FrameNavigated) { SetFakeWebPageMetadataAgent(); - web_contents_tester()->SetTitle(kFooTitle); + const auto web_contents_title = base::UTF8ToUTF16(kFooTitle); + web_contents_tester()->SetTitle(web_contents_title); const GURL kFooUrl("https://foo.example/bar"); web_contents_tester()->NavigateAndCommit(kFooUrl.GetOrigin()); @@ -359,7 +378,7 @@ run_loop.Run(); EXPECT_EQ(kFooUrl.GetOrigin(), web_app_info()->start_url); - EXPECT_EQ(kFooTitle, web_app_info()->title); + EXPECT_EQ(web_contents_title, web_app_info()->title); } TEST_F(WebAppDataRetrieverTest, CheckInstallabilityAndRetrieveManifest) {
diff --git a/chrome/browser/web_applications/components/web_app_install_utils_unittest.cc b/chrome/browser/web_applications/components/web_app_install_utils_unittest.cc index 9f76acb..06cee0c 100644 --- a/chrome/browser/web_applications/components/web_app_install_utils_unittest.cc +++ b/chrome/browser/web_applications/components/web_app_install_utils_unittest.cc
@@ -28,8 +28,8 @@ const char16_t kAppShortName[] = u"Test short name"; const char16_t kAppTitle[] = u"Test title"; -const char16_t kAlternativeAppTitle[] = u"Different test title"; -const char16_t kShortcutItemName[] = u"shortcut item "; +const char kAlternativeAppTitle[] = "Different test title"; +const char kShortcutItemName[] = "shortcut item "; constexpr SquareSizePx kIconSize = 64; @@ -51,7 +51,7 @@ TEST(WebAppInstallUtils, UpdateWebAppInfoFromManifest) { WebApplicationInfo web_app_info; - web_app_info.title = kAlternativeAppTitle; + web_app_info.title = base::UTF8ToUTF16(kAlternativeAppTitle); web_app_info.start_url = GURL("http://www.notchromium.org"); WebApplicationIconInfo info; const GURL kAppIcon1("fav1.png"); @@ -289,7 +289,7 @@ TEST_F(WebAppInstallUtilsWithShortcutsMenu, UpdateWebAppInfoFromManifestWithShortcuts) { WebApplicationInfo web_app_info; - web_app_info.title = kAlternativeAppTitle; + web_app_info.title = base::UTF8ToUTF16(kAlternativeAppTitle); web_app_info.start_url = GURL("http://www.notchromium.org"); WebApplicationIconInfo info; const GURL kAppIcon1("fav1.png"); @@ -300,8 +300,9 @@ for (int i = 0; i < 3; ++i) { WebApplicationShortcutsMenuItemInfo shortcuts_menu_item_info; WebApplicationShortcutsMenuItemInfo::Icon icon; - shortcuts_menu_item_info.name = - kShortcutItemName + base::NumberToString16(i + 1); + std::string shortcut_name = kShortcutItemName; + shortcut_name += base::NumberToString(i + 1); + shortcuts_menu_item_info.name = base::UTF8ToUTF16(shortcut_name); shortcuts_menu_item_info.url = kShortcutItemUrl; icon.url = GURL("http://www.chromium.org/shortcuts/icon1.png"); @@ -385,7 +386,9 @@ // Test that shortcuts in the manifest replace those in |web_app_info|. blink::Manifest::ShortcutItem shortcut_item; - shortcut_item.name = std::u16string(kShortcutItemName) + u"4"; + std::string shortcut_name = kShortcutItemName; + shortcut_name += base::NumberToString(4); + shortcut_item.name = base::UTF8ToUTF16(shortcut_name); shortcut_item.url = kShortcutItemUrl; const GURL kIconUrl2("http://www.chromium.org/shortcuts/icon2.png"); @@ -396,7 +399,9 @@ manifest.shortcuts.push_back(shortcut_item); - shortcut_item.name = std::u16string(kShortcutItemName) + u"5"; + shortcut_name = kShortcutItemName; + shortcut_name += base::NumberToString(5); + shortcut_item.name = base::UTF8ToUTF16(shortcut_name); const GURL kIconUrl3("http://www.chromium.org/shortcuts/icon3.png"); icon.src = kIconUrl3; @@ -475,7 +480,9 @@ blink::Manifest manifest; for (unsigned int i = 0; i < kNumTestIcons; ++i) { blink::Manifest::ShortcutItem shortcut_item; - shortcut_item.name = kShortcutItemName + base::NumberToString16(i); + std::string shortcut_name = kShortcutItemName; + shortcut_name += base::NumberToString(i); + shortcut_item.name = base::UTF8ToUTF16(shortcut_name); shortcut_item.url = GURL("http://www.chromium.org/shortcuts/action"); blink::Manifest::ImageResource icon; @@ -529,7 +536,9 @@ blink::Manifest manifest; for (int i = 1; i <= 20; ++i) { blink::Manifest::ShortcutItem shortcut_item; - shortcut_item.name = kShortcutItemName + base::NumberToString16(i); + std::string shortcut_name = kShortcutItemName; + shortcut_name += base::NumberToString(i); + shortcut_item.name = base::UTF8ToUTF16(shortcut_name); shortcut_item.url = GURL("http://www.chromium.org/shortcuts/action"); blink::Manifest::ImageResource icon; @@ -565,7 +574,9 @@ { WebApplicationShortcutsMenuItemInfo shortcut_item; std::vector<WebApplicationShortcutsMenuItemInfo::Icon> shortcut_icon_infos; - shortcut_item.name = std::u16string(kShortcutItemName) + u"1"; + std::string shortcut_name = kShortcutItemName; + shortcut_name += base::NumberToString(1); + shortcut_item.name = base::UTF8ToUTF16(shortcut_name); shortcut_item.url = GURL("http://www.chromium.org/shortcuts/action"); icon.url = kIconUrl1; icon.square_size_px = kIconSize; @@ -579,7 +590,9 @@ { WebApplicationShortcutsMenuItemInfo shortcut_item; std::vector<WebApplicationShortcutsMenuItemInfo::Icon> shortcut_icon_infos; - shortcut_item.name = std::u16string(kShortcutItemName) + u"2"; + std::string shortcut_name = kShortcutItemName; + shortcut_name += base::NumberToString(2); + shortcut_item.name = base::UTF8ToUTF16(shortcut_name); icon.url = kIconUrl1; icon.square_size_px = kIconSize; shortcut_icon_infos.push_back(icon); @@ -760,7 +773,7 @@ // Construct |shortcuts_menu_item_info| to add to // |web_app_info.shortcuts_menu_item_infos|. WebApplicationShortcutsMenuItemInfo shortcuts_menu_item_info; - shortcuts_menu_item_info.name = kShortcutItemName; + shortcuts_menu_item_info.name = base::UTF8ToUTF16(kShortcutItemName); shortcuts_menu_item_info.url = GURL("http://www.chromium.org/shortcuts/action"); // Construct |icon| to add to |shortcuts_menu_item_info.shortcut_icon_infos|.
diff --git a/chrome/browser/web_applications/components/web_app_run_on_os_login_win_unittest.cc b/chrome/browser/web_applications/components/web_app_run_on_os_login_win_unittest.cc index 49eb540b..4ae49adc 100644 --- a/chrome/browser/web_applications/components/web_app_run_on_os_login_win_unittest.cc +++ b/chrome/browser/web_applications/components/web_app_run_on_os_login_win_unittest.cc
@@ -25,7 +25,7 @@ namespace { -constexpr char16_t kAppTitle[] = u"app"; +constexpr char kAppTitle[] = {"app"}; } // namespace class WebAppRunOnOsLoginWinTest : public WebAppTest { @@ -42,7 +42,7 @@ std::unique_ptr<ShortcutInfo> GetShortcutInfo() { auto shortcut_info = std::make_unique<ShortcutInfo>(); shortcut_info->extension_id = "app-id"; - shortcut_info->title = kAppTitle; + shortcut_info->title = base::UTF8ToUTF16(kAppTitle); shortcut_info->profile_path = profile()->GetPath(); gfx::ImageFamily image_family; @@ -64,7 +64,7 @@ std::vector<base::FilePath> GetShortcuts() { return internals::FindAppShortcutsByProfileAndTitle( - GetStartupFolder(), profile()->GetPath(), kAppTitle); + GetStartupFolder(), profile()->GetPath(), base::UTF8ToUTF16(kAppTitle)); } void VerifyShortcutCreated() { @@ -116,7 +116,8 @@ VerifyShortcutCreated(); internals::UnregisterRunOnOsLogin(shortcut_info->extension_id, - profile()->GetPath(), kAppTitle); + profile()->GetPath(), + base::UTF8ToUTF16(kAppTitle)); VerifyShortcutDeleted(); }
diff --git a/chrome/browser/web_applications/manifest_update_manager_browsertest.cc b/chrome/browser/web_applications/manifest_update_manager_browsertest.cc index ebd1690..590f3a0 100644 --- a/chrome/browser/web_applications/manifest_update_manager_browsertest.cc +++ b/chrome/browser/web_applications/manifest_update_manager_browsertest.cc
@@ -97,7 +97,6 @@ )"; constexpr char kAnotherShortcutsItemName[] = "Timeline"; -constexpr char16_t kAnotherShortcutsItemName16[] = u"Timeline"; constexpr char kAnotherShortcutsItemUrl[] = "/shortcut"; constexpr char kAnotherShortcutsItemShortName[] = "H"; constexpr char kAnotherShortcutsItemDescription[] = "Navigate home"; @@ -1766,7 +1765,7 @@ ManifestUpdateResult::kAppUpdated, 1); EXPECT_EQ( GetProvider().registrar().GetAppShortcutsMenuItemInfos(app_id)[0].name, - kAnotherShortcutsItemName16); + base::UTF8ToUTF16(kAnotherShortcutsItemName)); } IN_PROC_BROWSER_TEST_F(ManifestUpdateManagerBrowserTestWithShortcutsMenu,
diff --git a/chrome/build/win32.pgo.txt b/chrome/build/win32.pgo.txt index 61627deb..a8824dc 100644 --- a/chrome/build/win32.pgo.txt +++ b/chrome/build/win32.pgo.txt
@@ -1 +1 @@ -chrome-win32-master-1620334673-6dc5fe0a935955373e196bc7f5dad400e3a1e55b.profdata +chrome-win32-master-1620366527-78dc9eab7d7f9f11d443eaece4da349610b60e5f.profdata
diff --git a/chrome/build/win64.pgo.txt b/chrome/build/win64.pgo.txt index 4ab71b6..89f1ffa 100644 --- a/chrome/build/win64.pgo.txt +++ b/chrome/build/win64.pgo.txt
@@ -1 +1 @@ -chrome-win64-master-1620334673-2fc8758cdea89c260f068beff8d5460a3aabf2f6.profdata +chrome-win64-master-1620377603-618842026f3ac0ece6a2d2f779f200224c4f888f.profdata
diff --git a/chrome/common/chrome_paths_mac.mm b/chrome/common/chrome_paths_mac.mm index 66ea52a1..41538c6 100644 --- a/chrome/common/chrome_paths_mac.mm +++ b/chrome/common/chrome_paths_mac.mm
@@ -13,6 +13,7 @@ #import "base/mac/foundation_util.h" #include "base/memory/free_deleter.h" #include "base/path_service.h" +#include "base/strings/sys_string_conversions.h" #include "build/branding_buildflags.h" #include "build/build_config.h" #include "chrome/common/chrome_constants.h" @@ -40,9 +41,7 @@ base::FilePath framework_path = chrome::GetFrameworkBundlePath(); base::FilePath outer_app_dir = framework_path.DirName().DirName().DirName().DirName().DirName(); - const char* outer_app_dir_c = outer_app_dir.value().c_str(); - NSString* outer_app_dir_ns = - [NSString stringWithUTF8String:outer_app_dir_c]; + NSString* outer_app_dir_ns = base::SysUTF8ToNSString(outer_app_dir.value()); return [[NSBundle bundleWithPath:outer_app_dir_ns] retain]; }
diff --git a/chrome/common/extensions/chrome_manifest_url_handlers.cc b/chrome/common/extensions/chrome_manifest_url_handlers.cc index 33d53fc9..d1153d96 100644 --- a/chrome/common/extensions/chrome_manifest_url_handlers.cc +++ b/chrome/common/extensions/chrome_manifest_url_handlers.cc
@@ -150,7 +150,7 @@ } // An extension may override at most one page. - if (overrides->size() > 1) { + if (overrides->DictSize() > 1) { *error = base::ASCIIToUTF16(errors::kMultipleOverrides); return false; }
diff --git a/chrome/common/mac/launchd.mm b/chrome/common/mac/launchd.mm index d24e7214..5c7425d 100644 --- a/chrome/common/mac/launchd.mm +++ b/chrome/common/mac/launchd.mm
@@ -31,7 +31,7 @@ NSArray* library_paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, domain, YES); DCHECK_EQ([library_paths count], 1U); - NSString* library_path = [library_paths objectAtIndex:0]; + NSString* library_path = library_paths[0]; NSString *launch_dir_name = (type == Launchd::Daemon) ? @"LaunchDaemons" : @"LaunchAgents";
diff --git a/chrome/common/printing/printer_capabilities_mac.mm b/chrome/common/printing/printer_capabilities_mac.mm index a2c595c2..f9ec279 100644 --- a/chrome/common/printing/printer_capabilities_mac.mm +++ b/chrome/common/printing/printer_capabilities_mac.mm
@@ -72,14 +72,14 @@ if (![paper isKindOfClass:[NSDictionary class]]) continue; - int width = [[paper objectForKey:@"width"] intValue]; - int height = [[paper objectForKey:@"height"] intValue]; + int width = [paper[@"width"] intValue]; + int height = [paper[@"height"] intValue]; if (width <= 0 || height <= 0 || width > kMacPaperDimensionLimit || height > kMacPaperDimensionLimit) { continue; } - NSString* name = [paper objectForKey:@"name"]; + NSString* name = paper[@"name"]; if (![name isKindOfClass:[NSString class]] || [name length] == 0) continue;
diff --git a/chrome/service/cloud_print/connector_settings_unittest.cc b/chrome/service/cloud_print/connector_settings_unittest.cc index b02acf3c..36927d4 100644 --- a/chrome/service/cloud_print/connector_settings_unittest.cc +++ b/chrome/service/cloud_print/connector_settings_unittest.cc
@@ -127,8 +127,8 @@ EXPECT_EQ(settings1.server_url(), settings2.server_url()); EXPECT_EQ(settings1.proxy_id(), settings2.proxy_id()); EXPECT_EQ(settings1.delete_on_enum_fail(), settings2.delete_on_enum_fail()); - EXPECT_EQ(settings1.print_system_settings()->size(), - settings2.print_system_settings()->size()); + EXPECT_EQ(settings1.print_system_settings()->DictSize(), + settings2.print_system_settings()->DictSize()); EXPECT_EQ(settings1.xmpp_ping_enabled(), settings2.xmpp_ping_enabled()); EXPECT_EQ(settings1.xmpp_ping_timeout_sec(), settings2.xmpp_ping_timeout_sec());
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index 4d3f798..b14850e 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -226,9 +226,7 @@ "//chrome:strings", #"//chrome/app/theme:theme_resources", - "//chrome/browser:browser_process", "//chrome/browser:test_support", - "//chrome/browser/safe_browsing", "//chrome/child", "//chrome/common:non_code_constants", "//chrome/common:test_support", @@ -238,11 +236,6 @@ "//components/bookmarks/test", "//components/captive_portal/core:test_support", "//components/consent_auditor:test_support", - "//components/content_settings/core/browser", - "//components/crash/core/app", - "//components/domain_reliability", - "//components/federated_learning", - "//components/find_in_page", "//components/gcm_driver:test_support", "//components/gcm_driver/crypto:test_support", "//components/gcm_driver/instance_id:test_support", @@ -250,38 +243,26 @@ "//components/infobars/core", "//components/metrics:test_support", "//components/network_session_configurator/common", - "//components/network_time", "//components/network_time:network_time_test_support", "//components/omnibox/browser:test_support", - "//components/os_crypt", "//components/password_manager/core/browser:test_support", "//components/payments/core:test_support", "//components/performance_manager/test_support", - "//components/permissions", "//components/permissions:test_support", - "//components/policy/core/browser", - "//components/policy/core/common:test_support", "//components/prefs:test_support", - "//components/profile_metrics", - "//components/safe_browsing/core/db:database_manager", "//components/safe_browsing/core/db:v4_test_util", "//components/search_engines:test_support", "//components/sessions:test_support", "//components/signin/public/base:test_support", - "//components/startup_metric_utils/browser", - "//components/subresource_filter/content/browser", "//components/subresource_filter/content/browser:test_support", "//components/subresource_filter/core/common", "//components/sync:test_support", - "//components/sync_preferences", "//components/sync_preferences:test_support", "//components/sync_sessions:test_support", "//components/sync_user_events:test_support", "//components/update_client:test_support", - "//components/user_prefs", "//components/variations:test_support", "//components/web_resource:test_support", - "//components/webdata_services", "//content/public/app", "//content/public/child", "//content/public/common", @@ -299,9 +280,6 @@ "//ppapi/buildflags", "//printing/buildflags", "//services/cert_verifier:test_support", - "//services/data_decoder/public/cpp:test_support", - "//services/device/public/cpp:test_support", - "//services/device/public/cpp/geolocation", "//skia", "//sql", "//sql:test_support", @@ -309,17 +287,12 @@ "//testing/gtest", "//third_party/leveldatabase", "//ui/base", - "//ui/base:test_support", "//ui/events:events_base", "//ui/gfx:test_support", "//ui/gl", ] if (is_android) { - public_deps += [ - ":test_support_ui_android", - "//chrome:chrome_android_core", - ] if (enable_vr) { public_deps += [ "//chrome/browser/android/vr:test_support" ] @@ -330,23 +303,10 @@ public_deps += [ # Android uses //chrome:chrome_android_core instead of the //chrome/app # target. - ":test_support_ui", "//chrome/app:test_support", - "//chrome/browser/web_applications", - "//chrome/browser/web_applications/components", - "//components/crx_file", - "//components/keep_alive_registry", - "//components/pref_registry", - "//components/storage_monitor", - "//components/storage_monitor:test_support", "//components/ukm:test_support", "//components/ukm:ukm_test_helper", - "//components/web_modal", - "//components/zoom", "//components/zoom:test_support", - "//extensions/browser:test_support", - "//extensions/common:test_support", - "//ui/snapshot", ] sources += [ "../browser/enterprise/reporting/extension_request/extension_request_report_throttler_test.cc", @@ -369,11 +329,7 @@ "//chrome/app/chrome_crash_reporter_client.cc", "//chrome/app/chrome_crash_reporter_client_mac.mm", ] - deps += [ - "//build:branding_buildflags", - "//chrome/app_shim", - "//components/upload_list", - ] + deps += [ "//build:branding_buildflags" ] public_deps += [ "//components/crash/core/app", "//third_party/breakpad", @@ -404,7 +360,6 @@ "//chrome/app/chrome_crash_reporter_client_win.cc", ] public_deps += [ - "//chrome/chrome_elf:crash", "//chrome/install_static/test:test_support", "//components/crash/core/app", "//third_party/wtl", @@ -448,23 +403,11 @@ public_deps += [ "//ash", "//ash:test_support", - "//ash/components/account_manager", - "//ash/constants", - "//chrome/browser/chromeos", - "//chromeos/dbus/session_manager", - "//chromeos/dbus/tpm_manager", - "//chromeos/dbus/userdataauth", - "//chromeos/login/login_state", - "//chromeos/settings", - "//chromeos/tpm", - "//chromeos/tpm:test_support", - "//components/exo", "//components/ownership", "//components/user_manager:test_support", "//ui/aura", "//ui/aura:test_support", "//ui/base/ime/init", - "//ui/chromeos/resources:resources_grit", ] deps += [ "//chromeos/cryptohome", @@ -474,11 +417,7 @@ } if (is_chromeos_lacros) { - deps += [ - "//chromeos/lacros", - "//chromeos/lacros:test_support", - "//chromeos/services/machine_learning/public/cpp:stub", - ] + deps += [ "//chromeos/services/machine_learning/public/cpp:stub" ] } if (is_win || is_mac || (is_linux || is_chromeos_lacros)) { @@ -494,11 +433,6 @@ "base/test_browser_window_aura.cc", "base/test_browser_window_aura.h", ] - deps += [ - "//ui/aura:test_support", - "//ui/wm", - "//ui/wm/public", - ] } if (toolkit_views) { @@ -2394,6 +2328,7 @@ "../browser/ui/views/extensions/extension_installed_bubble_view_browsertest.cc", "../browser/ui/views/extensions/extension_uninstall_dialog_view_browsertest.cc", "../browser/ui/views/extensions/extensions_menu_view_browsertest.cc", + "../browser/ui/views/extensions/extensions_side_panel_controller_browsertest.cc", "../browser/ui/views/extensions/extensions_toolbar_browsertest.cc", "../browser/ui/views/extensions/extensions_toolbar_browsertest.h", "../browser/ui/views/extensions/extensions_toolbar_container_browsertest.cc",
diff --git a/chrome/test/base/chrome_unit_test_suite.cc b/chrome/test/base/chrome_unit_test_suite.cc index 1f94028..8e6151a 100644 --- a/chrome/test/base/chrome_unit_test_suite.cc +++ b/chrome/test/base/chrome_unit_test_suite.cc
@@ -29,6 +29,7 @@ #include "extensions/buildflags/buildflags.h" #include "gpu/ipc/service/image_transport_surface.h" #include "testing/gtest/include/gtest/gtest.h" +#include "ui/accessibility/platform/ax_platform_node.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/resource/resource_handle.h" #include "ui/base/ui_base_paths.h" @@ -103,6 +104,9 @@ TestingBrowserProcess::DeleteInstance(); // Some tests cause ChildThreadImpl to initialize a PowerMonitor. base::PowerMonitor::ShutdownForTesting(); + DCHECK(ui::AXPlatformNode::GetAccessibilityMode() == 0) + << "Please use ScopedAxModeSetter, or add a call to " + "AXPlatformNode::ResetAxModeForTesting() at the end of your test."; } private:
diff --git a/chrome/test/data/webui/settings/basic_page_test.js b/chrome/test/data/webui/settings/basic_page_test.js index 004cce2..15c52119 100644 --- a/chrome/test/data/webui/settings/basic_page_test.js +++ b/chrome/test/data/webui/settings/basic_page_test.js
@@ -9,7 +9,9 @@ import {isChromeOS} from 'chrome://resources/js/cr.m.js'; import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -import {pageVisibility} from 'chrome://settings/settings.js'; +import {loadTimeData, pageVisibility, Router, routes} from 'chrome://settings/settings.js'; + +import {flushTasks, isVisible} from '../test_util.m.js'; // clang-format on // Register mocha tests. @@ -54,3 +56,104 @@ assertFalse(!!sectionElement); }); }); + +suite('SettingsBasicPageRedesign', () => { + let page = null; + + setup(function() { + PolymerTest.clearBody(); + page = document.createElement('settings-basic-page'); + document.body.appendChild(page); + page.scroller = document.body; + }); + + /** @param {string} section */ + function assertActiveSection(section) { + const activeSections = + page.shadowRoot.querySelectorAll('settings-section[active]'); + assertEquals(1, activeSections.length); + assertEquals(section, activeSections[0].section); + + // Check that only the |active| section is visible. + for (const s of page.shadowRoot.querySelectorAll('settings-section')) { + assertEquals(s === activeSections[0], isVisible(s)); + } + } + + test('OnlyOneSectionShown', async () => { + assertTrue(loadTimeData.getBoolean('enableLandingPageRedesign')); + const attribute = + loadTimeData.getString('enableLandingPageRedesignAttribute'); + assertEquals('enable-landing-page-redesign', attribute); + + + // Do this manually as it is normally part of settings.html, which is not + // part of this test. + document.documentElement.toggleAttribute(attribute, true); + + // Ensure that all settings-section instances are rendered. + flush(); + await page.$$('#advancedPageTemplate').get(); + const sections = page.shadowRoot.querySelectorAll('settings-section'); + assertTrue(sections.length > 1); + + // RouteState.INITIAL -> RoutState.TOP_LEVEL + // Check that only one is marked as |active|. + assertActiveSection(routes.PEOPLE.section); + assertTrue(!!page.shadowRoot.querySelector( + 'settings-section[active] settings-people-page')); + + // RouteState.TOP_LEVEL -> RoutState.SECTION + // Check that navigating to a different route correctly updates the page. + Router.getInstance().navigateTo(routes.SEARCH); + await flushTasks(); + assertActiveSection(routes.SEARCH.section); + assertTrue(!!page.shadowRoot.querySelector( + 'settings-section[active] settings-search-page')); + + // Helper functions. + function getCardElement() { + return page.shadowRoot.querySelector( + 'settings-section[active] settings-appearance-page'); + } + + function getDefault() { + return getCardElement().shadowRoot.querySelector( + 'div[route-path="default"].iron-selected'); + } + + function getSubpage() { + return getCardElement().shadowRoot.querySelector( + 'settings-subpage.iron-selected settings-appearance-fonts-page'); + } + + // RouteState.SECTION -> RoutState.SECTION + Router.getInstance().navigateTo(routes.APPEARANCE); + await flushTasks(); + assertActiveSection(routes.APPEARANCE.section); + assertTrue(!!getCardElement()); + assertTrue(!!getDefault()); + assertFalse(!!getSubpage()); + + // RouteState.SECTION -> RoutState.SUBPAGE + Router.getInstance().navigateTo(routes.FONTS); + await flushTasks(); + assertActiveSection(routes.APPEARANCE.section); + assertTrue(!!getCardElement()); + assertFalse(!!getDefault()); + assertTrue(!!getSubpage()); + + // RouteState.SUBPAGE -> RoutState.SECTION + Router.getInstance().navigateTo(routes.APPEARANCE); + await flushTasks(); + assertActiveSection(routes.APPEARANCE.section); + assertTrue(!!getCardElement()); + assertTrue(!!getDefault()); + assertFalse(!!getSubpage()); + + // RouteState.SECTION -> RoutState.TOP_LEVEL + Router.getInstance().navigateTo(routes.BASIC); + await flushTasks(); + assertActiveSection(routes.PEOPLE.section); + }); +});
diff --git a/chrome/test/data/webui/settings/cr_settings_browsertest.js b/chrome/test/data/webui/settings/cr_settings_browsertest.js index 616650b..8eeec34 100644 --- a/chrome/test/data/webui/settings/cr_settings_browsertest.js +++ b/chrome/test/data/webui/settings/cr_settings_browsertest.js
@@ -9,6 +9,7 @@ GEN('#include "build/branding_buildflags.h"'); GEN('#include "build/chromeos_buildflags.h"'); +GEN('#include "chrome/browser/ui/ui_features.h"'); GEN('#include "chrome/common/chrome_features.h"'); GEN('#include "components/autofill/core/common/autofill_features.h"'); GEN('#include "components/password_manager/core/common/password_manager_features.h"'); @@ -72,6 +73,44 @@ }); // eslint-disable-next-line no-var +var CrSettingsBasicPageV3Test = class extends CrSettingsV3BrowserTest { + /** @override */ + get browsePreload() { + return 'chrome://settings/test_loader.html?module=settings/basic_page_test.js'; + } + + /** @override */ + get featureListInternal() { + return { + disabled: ['features::kSettingsLandingPageRedesign'], + }; + } +}; + +TEST_F('CrSettingsBasicPageV3Test', 'All', function() { + runMochaSuite('SettingsBasicPage'); +}); + +// eslint-disable-next-line no-var +var CrSettingsBasicPageRedesignV3Test = class extends CrSettingsV3BrowserTest { + /** @override */ + get browsePreload() { + return 'chrome://settings/test_loader.html?module=settings/basic_page_test.js'; + } + + /** @override */ + get featureListInternal() { + return { + enabled: ['features::kSettingsLandingPageRedesign'], + }; + } +}; + +TEST_F('CrSettingsBasicPageRedesignV3Test', 'All', function() { + runMochaSuite('SettingsBasicPageRedesign'); +}); + +// eslint-disable-next-line no-var var CrSettingsLanguagesPageV3Test = class extends CrSettingsV3BrowserTest { /** @override */ get browsePreload() { @@ -545,7 +584,6 @@ [['AllSites', 'all_sites_tests.js'], ['AppearanceFontsPage', 'appearance_fonts_page_test.js'], ['AppearancePage', 'appearance_page_test.js'], - ['BasicPage', 'basic_page_test.js'], [ 'SettingsCategoryDefaultRadioGroup', 'settings_category_default_radio_group_tests.js'
diff --git a/chromeos/components/eche_app_ui/BUILD.gn b/chromeos/components/eche_app_ui/BUILD.gn index 22b513d..1099bf54 100644 --- a/chromeos/components/eche_app_ui/BUILD.gn +++ b/chromeos/components/eche_app_ui/BUILD.gn
@@ -43,6 +43,7 @@ deps = [ "//ash/constants", + "//ash/public/cpp", "//chromeos/components/eche_app_ui/mojom", "//chromeos/components/eche_app_ui/proto", "//chromeos/components/multidevice:multidevice",
diff --git a/chromeos/components/eche_app_ui/DEPS b/chromeos/components/eche_app_ui/DEPS index cc74faf0..4155b1b 100644 --- a/chromeos/components/eche_app_ui/DEPS +++ b/chromeos/components/eche_app_ui/DEPS
@@ -1,5 +1,6 @@ include_rules = [ # Do not add chrome here (use a delegate instead). + "+ash/public/cpp", "+chromeos/grit/chromeos_sample_system_web_app_resources.h", "+components/keyed_service/core/keyed_service.h", "+components/prefs",
diff --git a/chromeos/components/eche_app_ui/mojom/BUILD.gn b/chromeos/components/eche_app_ui/mojom/BUILD.gn index 3b50430..c391233 100644 --- a/chromeos/components/eche_app_ui/mojom/BUILD.gn +++ b/chromeos/components/eche_app_ui/mojom/BUILD.gn
@@ -6,4 +6,19 @@ mojom("mojom") { sources = [ "eche_app.mojom" ] + + cpp_typemaps = [ + { + types = [ + { + mojom = "chromeos.eche_app.mojom.ScreenBacklightState" + cpp = "ash::ScreenState" + }, + ] + traits_headers = + [ "//chromeos/components/eche_app_ui/mojom/types_mojom_traits.h" ] + traits_sources = + [ "//chromeos/components/eche_app_ui/mojom/types_mojom_traits.cc" ] + }, + ] }
diff --git a/chromeos/components/eche_app_ui/mojom/OWNERS b/chromeos/components/eche_app_ui/mojom/OWNERS index 08850f4..1feb514 100644 --- a/chromeos/components/eche_app_ui/mojom/OWNERS +++ b/chromeos/components/eche_app_ui/mojom/OWNERS
@@ -1,2 +1,4 @@ per-file *.mojom=set noparent per-file *.mojom=file://ipc/SECURITY_OWNERS +per-file *_mojom_traits*.*=set noparent +per-file *_mojom_traits*.*=file://ipc/SECURITY_OWNERS
diff --git a/chromeos/components/eche_app_ui/mojom/eche_app.mojom b/chromeos/components/eche_app_ui/mojom/eche_app.mojom index a369ba7..1ce808b 100644 --- a/chromeos/components/eche_app_ui/mojom/eche_app.mojom +++ b/chromeos/components/eche_app_ui/mojom/eche_app.mojom
@@ -25,11 +25,32 @@ OnReceivedSignalingMessage(array<uint8> signal); }; +// Screen backlight state. +// Reference from ash/public/cpp/screen_backlight_type.h +enum ScreenBacklightState { + ON, + OFF, + OFF_AUTO, +}; + // Interface for getting system information. interface SystemInfoProvider { // Get the system info such as board name and device name. The // output parameter is JSON encoded set of data. GetSystemInfo() => (string system_info); + + // Registers a generic interface to observe events from browser-to-renderer. + SetSystemInfoObserver(pending_remote<SystemInfoObserver> observer); +}; + +// A generic interface to observe events of browser process, all events from +// browser-to-render should be added in this interface if there is no other +// reason. +interface SystemInfoObserver { + // Interface for monitoring screen backlight state of device. The state is + // detected from Chrome browser process and is notified to Eche App in + // renderer process. Updates with the latest screen backlight state. + OnScreenBacklightStateChanged(ScreenBacklightState state); }; // Interface for generating uid. The uid is unique and persistent.
diff --git a/chromeos/components/eche_app_ui/mojom/types_mojom_traits.cc b/chromeos/components/eche_app_ui/mojom/types_mojom_traits.cc new file mode 100644 index 0000000..09edcdaf --- /dev/null +++ b/chromeos/components/eche_app_ui/mojom/types_mojom_traits.cc
@@ -0,0 +1,45 @@ +// Copyright 2021 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 "chromeos/components/eche_app_ui/mojom/types_mojom_traits.h" + +namespace mojo { + +// static +chromeos::eche_app::mojom::ScreenBacklightState +EnumTraits<chromeos::eche_app::mojom::ScreenBacklightState, + ash::ScreenState>::ToMojom(ash::ScreenState input) { + switch (input) { + case ash::ScreenState::ON: + return chromeos::eche_app::mojom::ScreenBacklightState::ON; + case ash::ScreenState::OFF: + return chromeos::eche_app::mojom::ScreenBacklightState::OFF; + case ash::ScreenState::OFF_AUTO: + return chromeos::eche_app::mojom::ScreenBacklightState::OFF_AUTO; + } + + NOTREACHED(); +} + +// static +bool EnumTraits<chromeos::eche_app::mojom::ScreenBacklightState, + ash::ScreenState>:: + FromMojom(chromeos::eche_app::mojom::ScreenBacklightState input, + ash::ScreenState* output) { + switch (input) { + case chromeos::eche_app::mojom::ScreenBacklightState::ON: + *output = ash::ScreenState::ON; + return true; + case chromeos::eche_app::mojom::ScreenBacklightState::OFF: + *output = ash::ScreenState::OFF; + return true; + case chromeos::eche_app::mojom::ScreenBacklightState::OFF_AUTO: + *output = ash::ScreenState::OFF_AUTO; + return true; + } + NOTREACHED(); + return false; +} + +} // namespace mojo
diff --git a/chromeos/components/eche_app_ui/mojom/types_mojom_traits.h b/chromeos/components/eche_app_ui/mojom/types_mojom_traits.h new file mode 100644 index 0000000..c691776 --- /dev/null +++ b/chromeos/components/eche_app_ui/mojom/types_mojom_traits.h
@@ -0,0 +1,25 @@ +// Copyright 2021 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. + +#ifndef CHROMEOS_COMPONENTS_ECHE_APP_UI_MOJOM_TYPES_MOJOM_TRAITS_H_ +#define CHROMEOS_COMPONENTS_ECHE_APP_UI_MOJOM_TYPES_MOJOM_TRAITS_H_ + +#include "ash/public/cpp/screen_backlight.h" +#include "chromeos/components/eche_app_ui/mojom/eche_app.mojom-shared.h" +#include "mojo/public/cpp/bindings/struct_traits.h" + +namespace mojo { + +template <> +struct EnumTraits<chromeos::eche_app::mojom::ScreenBacklightState, + ash::ScreenState> { + static chromeos::eche_app::mojom::ScreenBacklightState ToMojom( + ash::ScreenState input); + static bool FromMojom(chromeos::eche_app::mojom::ScreenBacklightState input, + ash::ScreenState* output); +}; + +} // namespace mojo + +#endif // CHROMEOS_COMPONENTS_ECHE_APP_UI_MOJOM_TYPES_MOJOM_TRAITS_H_
diff --git a/chromeos/components/eche_app_ui/resources/browser_proxy.js b/chromeos/components/eche_app_ui/resources/browser_proxy.js index 6197bcbf..b0d0e4d 100644 --- a/chromeos/components/eche_app_ui/resources/browser_proxy.js +++ b/chromeos/components/eche_app_ui/resources/browser_proxy.js
@@ -19,6 +19,13 @@ // Returns a remote for UidGenerator interface which gets an uid from the // browser. const uidGenerator = chromeos.echeApp.mojom.UidGenerator.getRemote(); +// An object which receives request messages for the SystemInfoObserver +// mojom interface and dispatches them as callbacks. +const systemInfoObserverRouter = + new chromeos.echeApp.mojom.SystemInfoObserverCallbackRouter(); +// Set up a message pipe to the browser process to monitor screen state. +systemInfo.setSystemInfoObserver( + systemInfoObserverRouter.$.bindNewPipeAndPassRemote()); // The implementation of echeapi.d.ts const EcheApiBindingImpl = new class { @@ -42,6 +49,11 @@ getLocalUid() { return uidGenerator.getUid(); } + + onScreenBacklightStateChanged(callback) { + systemInfoObserverRouter.onScreenBacklightStateChanged.addListener( + callback); + } }; // Declare module echeapi and bind the implementation to echeapi.d.ts @@ -58,4 +70,6 @@ EcheApiBindingImpl.getLocalUid.bind(EcheApiBindingImpl); echeapi.system.getSystemInfo = EcheApiBindingImpl.getSystemInfo.bind(EcheApiBindingImpl); +echeapi.system.registerScreenBacklightState = + EcheApiBindingImpl.onScreenBacklightStateChanged.bind(EcheApiBindingImpl); window['echeapi'] = echeapi;
diff --git a/chromeos/components/eche_app_ui/system_info_provider.cc b/chromeos/components/eche_app_ui/system_info_provider.cc index 9b1b6ae..b81a1bf 100644 --- a/chromeos/components/eche_app_ui/system_info_provider.cc +++ b/chromeos/components/eche_app_ui/system_info_provider.cc
@@ -6,6 +6,7 @@ #include "base/json/json_reader.h" #include "base/json/json_writer.h" #include "base/values.h" +#include "chromeos/components/eche_app_ui/mojom/types_mojom_traits.h" #include "chromeos/components/eche_app_ui/system_info.h" namespace chromeos { @@ -15,9 +16,15 @@ const char kJsonBoardNameKey[] = "board_name"; SystemInfoProvider::SystemInfoProvider(std::unique_ptr<SystemInfo> system_info) - : system_info_(std::move(system_info)) {} + : system_info_(std::move(system_info)) { + if (ash::ScreenBacklight::Get()) + ash::ScreenBacklight::Get()->AddObserver(this); +} -SystemInfoProvider::~SystemInfoProvider() = default; +SystemInfoProvider::~SystemInfoProvider() { + if (ash::ScreenBacklight::Get()) + ash::ScreenBacklight::Get()->RemoveObserver(this); +} void SystemInfoProvider::GetSystemInfo( base::OnceCallback<void(const std::string&)> callback) { @@ -29,11 +36,24 @@ std::move(callback).Run(json_message); } +void SystemInfoProvider::SetSystemInfoObserver( + mojo::PendingRemote<mojom::SystemInfoObserver> observer) { + observer_remote_.reset(); + observer_remote_.Bind(std::move(observer)); +} + void SystemInfoProvider::Bind( mojo::PendingReceiver<mojom::SystemInfoProvider> receiver) { info_receiver_.reset(); info_receiver_.Bind(std::move(receiver)); } +void SystemInfoProvider::OnScreenStateChanged(ash::ScreenState screen_state) { + if (!observer_remote_.is_bound()) + return; + + observer_remote_->OnScreenBacklightStateChanged(screen_state); +} + } // namespace eche_app } // namespace chromeos
diff --git a/chromeos/components/eche_app_ui/system_info_provider.h b/chromeos/components/eche_app_ui/system_info_provider.h index 1118737..1412b52 100644 --- a/chromeos/components/eche_app_ui/system_info_provider.h +++ b/chromeos/components/eche_app_ui/system_info_provider.h
@@ -6,7 +6,9 @@ #define CHROMEOS_COMPONENTS_ECHE_APP_UI_SYSTEM_INFO_PROVIDER_H_ #include "chromeos/components/eche_app_ui/mojom/eche_app.mojom.h" +#include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/receiver.h" +#include "mojo/public/cpp/bindings/remote.h" namespace chromeos { namespace eche_app { @@ -18,7 +20,8 @@ // Provides the system information likes board/device names for EcheApp and // exposes the interface via mojoa. -class SystemInfoProvider : public mojom::SystemInfoProvider { +class SystemInfoProvider : public mojom::SystemInfoProvider, + public ash::ScreenBacklightObserver { public: explicit SystemInfoProvider(std::unique_ptr<SystemInfo> system_info); ~SystemInfoProvider() override; @@ -29,11 +32,17 @@ // mojom::SystemInfoProvider: void GetSystemInfo( base::OnceCallback<void(const std::string&)> callback) override; + void SetSystemInfoObserver( + mojo::PendingRemote<mojom::SystemInfoObserver> observer) override; void Bind(mojo::PendingReceiver<mojom::SystemInfoProvider> receiver); private: + // ash::ScreenBacklightObserver overrides; + void OnScreenStateChanged(ash::ScreenState screen_state) override; + mojo::Receiver<mojom::SystemInfoProvider> info_receiver_{this}; + mojo::Remote<mojom::SystemInfoObserver> observer_remote_; std::unique_ptr<SystemInfo> system_info_; };
diff --git a/chromeos/policy/weekly_time/weekly_time.cc b/chromeos/policy/weekly_time/weekly_time.cc index c1f3e7d4..4a3d87a1e 100644 --- a/chromeos/policy/weekly_time/weekly_time.cc +++ b/chromeos/policy/weekly_time/weekly_time.cc
@@ -26,7 +26,7 @@ // static const char WeeklyTime::kDayOfWeek[] = "day_of_week"; const char WeeklyTime::kTime[] = "time"; -const char WeeklyTime::kTimezoneOffset[] = "timezon_offset"; +const char WeeklyTime::kTimezoneOffset[] = "timezone_offset"; const std::vector<std::string> WeeklyTime::kWeekDays = { "UNSPECIFIED", "MONDAY", "TUESDAY", "WEDNESDAY",
diff --git a/components/arc/session/arc_container_client_adapter.cc b/components/arc/session/arc_container_client_adapter.cc index 93ab536..3f29fee 100644 --- a/components/arc/session/arc_container_client_adapter.cc +++ b/components/arc/session/arc_container_client_adapter.cc
@@ -37,18 +37,18 @@ } // Converts ArcSupervisionTransition into login_manager's. -login_manager::UpgradeArcContainerRequest_SupervisionTransition -ToLoginManagerSupervisionTransition(ArcSupervisionTransition transition) { +login_manager::UpgradeArcContainerRequest_ManagementTransition +ToLoginManagerManagementTransition(ArcSupervisionTransition transition) { switch (transition) { case ArcSupervisionTransition::NO_TRANSITION: return login_manager:: - UpgradeArcContainerRequest_SupervisionTransition_NONE; + UpgradeArcContainerRequest_ManagementTransition_NONE; case ArcSupervisionTransition::CHILD_TO_REGULAR: return login_manager:: - UpgradeArcContainerRequest_SupervisionTransition_CHILD_TO_REGULAR; + UpgradeArcContainerRequest_ManagementTransition_CHILD_TO_REGULAR; case ArcSupervisionTransition::REGULAR_TO_CHILD: return login_manager:: - UpgradeArcContainerRequest_SupervisionTransition_REGULAR_TO_CHILD; + UpgradeArcContainerRequest_ManagementTransition_REGULAR_TO_CHILD; } } @@ -154,8 +154,8 @@ request.set_locale(params.locale); for (const auto& language : params.preferred_languages) request.add_preferred_languages(language); - request.set_supervision_transition( - ToLoginManagerSupervisionTransition(params.supervision_transition)); + request.set_management_transition( + ToLoginManagerManagementTransition(params.supervision_transition)); chromeos::SessionManagerClient::Get()->UpgradeArcContainer( request, std::move(callback));
diff --git a/components/autofill/PRESUBMIT.py b/components/autofill/PRESUBMIT.py index 677910f..2cb87c0 100644 --- a/components/autofill/PRESUBMIT.py +++ b/components/autofill/PRESUBMIT.py
@@ -41,13 +41,19 @@ input_api.re.MULTILINE) warnings = [] + def exception(constant, feature): + if constant == "AutofillAddressEnhancementVotes" and \ + feature == "kAutofillAddressEnhancementVotes": + return True + return False + for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile): if (f.LocalPath().startswith('components/autofill/') and f.LocalPath().endswith('features.cc')): contents = input_api.ReadFile(f) mismatches = [(constant, feature) for (constant, feature) in pattern.findall(contents) - if constant != feature] + if constant != feature and not exception(constant, feature)] if mismatches: mismatch_strings = ['\t{} -- {}'.format(*m) for m in mismatches] mismatch_string = format('\n').join(mismatch_strings)
diff --git a/components/autofill/content/renderer/form_autofill_util_browsertest.cc b/components/autofill/content/renderer/form_autofill_util_browsertest.cc index 0b613eb9..c19c9049 100644 --- a/components/autofill/content/renderer/form_autofill_util_browsertest.cc +++ b/components/autofill/content/renderer/form_autofill_util_browsertest.cc
@@ -50,7 +50,7 @@ struct AutofillFieldUtilCase { const char* description; const char* html; - const char16_t* expected_label; + const char* expected_label; }; const char kElevenChildren[] = @@ -67,8 +67,8 @@ "<div>child9</div>" "<div>child10</div>" "</div>"; -const char16_t kElevenChildrenExpected[] = - u"child0child1child2child3child4child5child6child7child8"; +const char kElevenChildrenExpected[] = + "child0child1child2child3child4child5child6child7child8"; const char kElevenChildrenNested[] = "<div id='target'>" @@ -85,8 +85,7 @@ "<div>child10" "</div></div></div></div></div></div></div></div></div></div></div></div>"; // Take 10 elements -1 for target element, -1 as text is a leaf element. -const char16_t kElevenChildrenNestedExpected[] = - u"child0child1child2child3child4"; +const char kElevenChildrenNestedExpected[] = "child0child1child2child3child4"; const char kSkipElement[] = "<div id='target'>" @@ -95,13 +94,13 @@ "<div>child2</div>" "</div>"; // TODO(crbug.com/796918): Should be child0child2 -const char16_t kSkipElementExpected[] = u"child0"; +const char kSkipElementExpected[] = "child0"; const char kDivTableExample1[] = "<div>" "<div>label</div><div><input id='target'/></div>" "</div>"; -const char16_t kDivTableExample1Expected[] = u"label"; +const char kDivTableExample1Expected[] = "label"; const char kDivTableExample2[] = "<div>" @@ -109,7 +108,7 @@ "<div>should be skipped<input/></div>" "<div><input id='target'/></div>" "</div>"; -const char16_t kDivTableExample2Expected[] = u"label"; +const char kDivTableExample2Expected[] = "label"; const char kDivTableExample3[] = "<div>" @@ -117,7 +116,7 @@ "<div>label</div>" "<div><input id='target'/></div>" "</div>"; -const char16_t kDivTableExample3Expected[] = u"label"; +const char kDivTableExample3Expected[] = "label"; const char kDivTableExample4[] = "<div>" @@ -126,21 +125,21 @@ "<div><input id='target'/></div>" "</div>"; // TODO(crbug.com/796918): Should be label -const char16_t kDivTableExample4Expected[] = u""; +const char kDivTableExample4Expected[] = ""; const char kDivTableExample5[] = "<div>" "<div>label<div><input id='target'/></div>behind</div>" "</div>"; // TODO(crbug.com/796918): Should be label -const char16_t kDivTableExample5Expected[] = u"labelbehind"; +const char kDivTableExample5Expected[] = "labelbehind"; const char kDivTableExample6[] = "<div>" "<div>label<div><div>-<div><input id='target'/></div></div>" "</div>"; // TODO(crbug.com/796918): Should be "label" or "label-" -const char16_t kDivTableExample6Expected[] = u""; +const char kDivTableExample6Expected[] = ""; void VerifyButtonTitleCache(const WebFormElement& form_target, const ButtonTitleList& expected_button_titles, @@ -164,13 +163,13 @@ TEST_F(FormAutofillUtilsTest, FindChildTextTest) { static const AutofillFieldUtilCase test_cases[] = { - {"simple test", "<div id='target'>test</div>", u"test"}, + {"simple test", "<div id='target'>test</div>", "test"}, {"Concatenate test", "<div id='target'><span>one</span>two</div>", - u"onetwo"}, + "onetwo"}, // TODO(crbug.com/796918): should be "onetwo" {"Ignore input", "<div id='target'>one<input value='test'/>two</div>", - u"one"}, - {"Trim", "<div id='target'> one<span>two </span></div>", u"onetwo"}, + "one"}, + {"Trim", "<div id='target'> one<span>two </span></div>", "onetwo"}, {"eleven children", kElevenChildren, kElevenChildrenExpected}, // TODO(crbug.com/796918): Depth is only 5 elements {"eleven children nested", kElevenChildrenNested, @@ -183,7 +182,8 @@ ASSERT_NE(nullptr, web_frame); WebElement target = web_frame->GetDocument().GetElementById("target"); ASSERT_FALSE(target.IsNull()); - EXPECT_EQ(test_case.expected_label, FindChildText(target)); + EXPECT_EQ(base::UTF8ToUTF16(test_case.expected_label), + FindChildText(target)); } } @@ -205,7 +205,7 @@ to_skip.insert(web_to_skip[i]); } - EXPECT_EQ(test_case.expected_label, + EXPECT_EQ(base::UTF8ToUTF16(test_case.expected_label), FindChildTextWithIgnoreListForTesting(target, to_skip)); } } @@ -234,12 +234,12 @@ FormFieldData::LabelSource::kUnknown; std::u16string label; InferLabelForElementForTesting(form_target, &label, &label_source); - EXPECT_EQ(test_case.expected_label, label); + EXPECT_EQ(base::UTF8ToUTF16(test_case.expected_label), label); } } TEST_F(FormAutofillUtilsTest, InferLabelSourceTest) { - const char16_t kLabelSourceExpectedLabel[] = u"label"; + const char kLabelSourceExpectedLabel[] = "label"; static const AutofillFieldLabelSourceCase test_cases[] = { {"<div><div>label</div><div><input id='target'/></div></div>", FormFieldData::LabelSource::kDivTable}, @@ -279,7 +279,7 @@ std::u16string label; EXPECT_TRUE(autofill::form_util::InferLabelForElementForTesting( form_target, &label, &label_source)); - EXPECT_EQ(kLabelSourceExpectedLabel, label); + EXPECT_EQ(base::UTF8ToUTF16(kLabelSourceExpectedLabel), label); EXPECT_EQ(test_case.label_source, label_source); } } @@ -441,18 +441,19 @@ dummy_fieldsets, control_elements, nullptr, web_frame->GetDocument(), nullptr, EXTRACT_NONE, &target, nullptr)); const struct { - const char16_t* const name; + const char* const name; bool enabled; } kExpectedFields[] = { - {u"name1", true}, - {u"name2", false}, - {u"name3", true}, - {u"name4", false}, + {"name1", true}, + {"name2", false}, + {"name3", true}, + {"name4", false}, }; const size_t number_of_cases = base::size(kExpectedFields); ASSERT_EQ(number_of_cases, target.fields.size()); for (size_t i = 0; i < number_of_cases; ++i) { - EXPECT_EQ(kExpectedFields[i].name, target.fields[i].name); + EXPECT_EQ(base::UTF8ToUTF16(kExpectedFields[i].name), + target.fields[i].name); EXPECT_EQ(kExpectedFields[i].enabled, target.fields[i].is_enabled); } } @@ -481,18 +482,19 @@ dummy_fieldsets, control_elements, nullptr, web_frame->GetDocument(), nullptr, EXTRACT_NONE, &target, nullptr)); const struct { - const char16_t* const name; + const char* const name; bool readonly; } kExpectedFields[] = { - {u"name1", false}, - {u"name2", true}, - {u"name3", false}, - {u"name4", true}, + {"name1", false}, + {"name2", true}, + {"name3", false}, + {"name4", true}, }; const size_t number_of_cases = base::size(kExpectedFields); ASSERT_EQ(number_of_cases, target.fields.size()); for (size_t i = 0; i < number_of_cases; ++i) { - EXPECT_EQ(kExpectedFields[i].name, target.fields[i].name); + EXPECT_EQ(base::UTF8ToUTF16(kExpectedFields[i].name), + target.fields[i].name); EXPECT_EQ(kExpectedFields[i].readonly, target.fields[i].is_readonly); } }
diff --git a/components/autofill/core/browser/address_profile_save_manager.cc b/components/autofill/core/browser/address_profile_save_manager.cc index ab1899d..52ffc56 100644 --- a/components/autofill/core/browser/address_profile_save_manager.cc +++ b/components/autofill/core/browser/address_profile_save_manager.cc
@@ -4,6 +4,7 @@ #include "components/autofill/core/browser/address_profile_save_manager.h" +#include "components/autofill/core/browser/autofill_client.h" #include "components/autofill/core/browser/data_model/autofill_profile.h" #include "components/autofill/core/browser/personal_data_manager.h" #include "components/autofill/core/common/autofill_features.h" @@ -82,11 +83,19 @@ // The prompt should not have been shown yet. DCHECK(!pending_import_->prompt_shown()); + // TODO(crbug.com/1175693): Pass the correct SaveAddressProfilePromptOptions + // below. + + // TODO(crbug.com/1175693): Check pending_import_->set_prompt_was_shown() is + // always correct even in cases where it conflicts with + // SaveAddressProfilePromptOptions + // Initiate the prompt and mark it as shown. pending_import_->set_prompt_was_shown(); client_->ConfirmSaveAddressProfile( pending_import_->import_candidate().value(), base::OptionalOrNullptr(pending_import_->merge_candidate()), + AutofillClient::SaveAddressProfilePromptOptions{.show_prompt = true}, base::BindOnce(&AddressProfileSaveManager::OnUserDecision, weak_ptr_factory_.GetWeakPtr())); }
diff --git a/components/autofill/core/browser/address_rewriter_unittest.cc b/components/autofill/core/browser/address_rewriter_unittest.cc index 35df50d6..327a1b7c 100644 --- a/components/autofill/core/browser/address_rewriter_unittest.cc +++ b/components/autofill/core/browser/address_rewriter_unittest.cc
@@ -7,6 +7,7 @@ #include "base/strings/utf_string_conversions.h" #include "testing/gtest/include/gtest/gtest.h" +using base::UTF8ToUTF16; using autofill::AddressRewriter; TEST(AddressRewriterTest, InvalidCountryCode) { @@ -40,7 +41,8 @@ TEST(AddressRewriterTest, AR) { AddressRewriter ar = AddressRewriter::ForCountryCode(u"ar"); - EXPECT_EQ(ar.Rewrite(u"tierra del fuego antartida e islas del atlantico sur"), + EXPECT_EQ(ar.Rewrite(UTF8ToUTF16( + "tierra del fuego antartida e islas del atlantico sur")), ar.Rewrite(u"tierra del fuego")); EXPECT_EQ(ar.Rewrite(u"ciudad autonoma de buenos aires"), ar.Rewrite(u"capital federal"));
diff --git a/components/autofill/core/browser/autofill_client.h b/components/autofill/core/browser/autofill_client.h index 13a88a4..68a23db 100644 --- a/components/autofill/core/browser/autofill_client.h +++ b/components/autofill/core/browser/autofill_client.h
@@ -189,6 +189,11 @@ bool show_prompt = false; }; + // Used for options of save (and update) address profile prompt. + struct SaveAddressProfilePromptOptions { + bool show_prompt = true; + }; + // Required arguments to create a dropdown showing autofill suggestions. struct PopupOpenArgs { using AutoselectFirstSuggestion = @@ -463,9 +468,11 @@ // renders an update prompt where `original_profile` is the address profile // that will be updated if the user accepts the update prompt. Runs `callback` // once the user makes a decision with respect to the offer-to-save prompt. + // `options` carries extra configuration options for the prompt. virtual void ConfirmSaveAddressProfile( const AutofillProfile& profile, const AutofillProfile* original_profile, + AutofillClient::SaveAddressProfilePromptOptions options, AddressProfileSavePromptCallback callback) = 0; // Returns true if both the platform and the device support scanning credit @@ -554,7 +561,7 @@ virtual LogManager* GetLogManager() const; #if defined(OS_IOS) - // Checks whether the qurrent query is the most recent one. + // Checks whether the current query is the most recent one. virtual bool IsQueryIDRelevant(int query_id) = 0; #endif };
diff --git a/components/autofill/core/browser/autofill_form_test_utils.h b/components/autofill/core/browser/autofill_form_test_utils.h index 02f8d1e7b2..5608138 100644 --- a/components/autofill/core/browser/autofill_form_test_utils.h +++ b/components/autofill/core/browser/autofill_form_test_utils.h
@@ -43,11 +43,11 @@ bool is_focusable = true; const base::StringPiece16 label = kLabelText; const base::StringPiece16 name = kNameText; - base::Optional<const char16_t*> value = base::nullopt; + base::Optional<const char16_t*> value; const base::StringPiece autocomplete_attribute; const base::StringPiece form_control_type = "text"; bool should_autocomplete = true; - base::Optional<bool> is_autofilled = base::nullopt; + base::Optional<bool> is_autofilled; }; // Attributes provided to the test form. @@ -55,11 +55,11 @@ struct TestFormAttributes { const base::StringPiece description_for_logging; std::vector<FieldDataDescription<>> fields; - base::Optional<FormRendererId> unique_renderer_id = base::nullopt; + base::Optional<FormRendererId> unique_renderer_id; const base::StringPiece16 name = u"TestForm"; const base::StringPiece url = kFormUrl; const base::StringPiece action = kFormActionUrl; - base::Optional<url::Origin> main_frame_origin = base::nullopt; + base::Optional<url::Origin> main_frame_origin; bool is_form_tag = true; }; @@ -80,11 +80,11 @@ // first value denotes whether the comparison is to be done while second // denotes EXPECT_TRUE for true and EXPECT_FALSE for false. std::pair<bool, bool> is_complete_credit_card_form = {false, false}; - // base::nullopt means no checking. - base::Optional<int> field_count = base::nullopt; - base::Optional<int> autofill_count = base::nullopt; - base::Optional<int> section_count = base::nullopt; - base::Optional<int> response_field_count = base::nullopt; + // The implicit default value `base::nullopt` means no checking. + base::Optional<int> field_count; + base::Optional<int> autofill_count; + base::Optional<int> section_count; + base::Optional<int> response_field_count; }; // Expected field type values to be verified with the test form.
diff --git a/components/autofill/core/browser/data_model/autofill_profile_comparator_unittest.cc b/components/autofill/core/browser/data_model/autofill_profile_comparator_unittest.cc index f301c95..28e56cb 100644 --- a/components/autofill/core/browser/data_model/autofill_profile_comparator_unittest.cc +++ b/components/autofill/core/browser/data_model/autofill_profile_comparator_unittest.cc
@@ -56,6 +56,7 @@ using autofill::NameInfo; using autofill::PhoneNumber; using autofill::ServerFieldType; +using base::UTF8ToUTF16; namespace autofill { @@ -101,22 +102,22 @@ autofill::CountryNames::SetLocaleString(kLocale); } - NameInfo CreateNameInfo(const char16_t* first, - const char16_t* middle, - const char16_t* last, - const char16_t* full) { + NameInfo CreateNameInfo(const char* first, + const char* middle, + const char* last, + const char* full) { NameInfo name; name.SetRawInfoWithVerificationStatus( - NAME_FIRST, first, + NAME_FIRST, base::UTF8ToUTF16(first), autofill::structured_address::VerificationStatus::kObserved); name.SetRawInfoWithVerificationStatus( - NAME_MIDDLE, middle, + NAME_MIDDLE, base::UTF8ToUTF16(middle), autofill::structured_address::VerificationStatus::kObserved); name.SetRawInfoWithVerificationStatus( - NAME_LAST, last, + NAME_LAST, base::UTF8ToUTF16(last), autofill::structured_address::VerificationStatus::kObserved); name.SetRawInfoWithVerificationStatus( - NAME_FULL, full, + NAME_FULL, base::UTF8ToUTF16(full), autofill::structured_address::VerificationStatus::kObserved); return name; } @@ -189,10 +190,10 @@ AutofillProfile CopyAndModify( const AutofillProfile& profile, - const std::vector<std::pair<ServerFieldType, const char16_t*>>& updates) { + const std::vector<std::pair<ServerFieldType, const char*>>& updates) { AutofillProfile new_profile = profile; for (const auto& update : updates) { - new_profile.SetRawInfo(update.first, update.second); + new_profile.SetRawInfo(update.first, UTF8ToUTF16(update.second)); } new_profile.FinalizeAfterImport(); return new_profile; @@ -241,7 +242,7 @@ void MergePhoneNumbersAndExpect(const AutofillProfile& a, const AutofillProfile& b, - const std::u16string& expected_str) { + const std::string& expected_str) { AutofillProfile dummy; // Merge the phone numbers. @@ -250,7 +251,7 @@ // Construct the expected value. PhoneNumber expected(&dummy); - expected.SetRawInfo(PHONE_HOME_WHOLE_NUMBER, expected_str); + expected.SetRawInfo(PHONE_HOME_WHOLE_NUMBER, UTF8ToUTF16(expected_str)); // Validate that we get what we expect. EXPECT_EQ(expected.GetRawInfo(PHONE_HOME_WHOLE_NUMBER), @@ -711,20 +712,20 @@ "Carver City", "ca", "", "us"); AutofillProfile differentCountry = - CopyAndModify(p1, {{ADDRESS_HOME_COUNTRY, u"CA"}}); + CopyAndModify(p1, {{ADDRESS_HOME_COUNTRY, "CA"}}); AutofillProfile differentZip = - CopyAndModify(p1, {{ADDRESS_HOME_ZIP, u"32145"}}); + CopyAndModify(p1, {{ADDRESS_HOME_ZIP, "32145"}}); AutofillProfile differentState = CopyAndModify( - p1, {{ADDRESS_HOME_ZIP, u""}, {ADDRESS_HOME_STATE, u"Florida"}}); + p1, {{ADDRESS_HOME_ZIP, ""}, {ADDRESS_HOME_STATE, "Florida"}}); AutofillProfile differentCity = CopyAndModify( - p1, {{ADDRESS_HOME_ZIP, u""}, {ADDRESS_HOME_CITY, u"Metropolis"}}); + p1, {{ADDRESS_HOME_ZIP, ""}, {ADDRESS_HOME_CITY, "Metropolis"}}); AutofillProfile differentAddress = - CopyAndModify(p1, {{ADDRESS_HOME_LINE1, u"17 Park Lane"}, - {ADDRESS_HOME_LINE2, u"Suite 150"}}); + CopyAndModify(p1, {{ADDRESS_HOME_LINE1, "17 Park Lane"}, + {ADDRESS_HOME_LINE2, "Suite 150"}}); AutofillProfile differentLocality = - CopyAndModify(p1, {{ADDRESS_HOME_DEPENDENT_LOCALITY, u"Funky Chicken"}}); + CopyAndModify(p1, {{ADDRESS_HOME_DEPENDENT_LOCALITY, "Funky Chicken"}}); AutofillProfile differentSortingCode = - CopyAndModify(p1, {{ADDRESS_HOME_SORTING_CODE, u"98000 Monaco"}}); + CopyAndModify(p1, {{ADDRESS_HOME_SORTING_CODE, "98000 Monaco"}}); EXPECT_TRUE(comparator_.HaveMergeableAddresses(p1, empty)); EXPECT_TRUE(comparator_.HaveMergeableAddresses(empty, p2)); @@ -757,26 +758,26 @@ "+1 (234) 567-8910", /*finalize=*/false); AutofillProfile mergeable = - CopyAndModify(p, {{NAME_FIRST, u"MÁRÍÕÑ"}, - {NAME_MIDDLE, u"M."}, - {EMAIL_ADDRESS, u"MARION@ME.XYZ"}, - {COMPANY_NAME, u"Fox Industries Inc."}, - {ADDRESS_HOME_LINE1, u"123 zoo st. w., #5"}, - {ADDRESS_HOME_LINE1, u""}, - {ADDRESS_HOME_STATE, u"california"}, - {PHONE_HOME_WHOLE_NUMBER, u"5678910 ext. 77"}}); + CopyAndModify(p, {{NAME_FIRST, "MÁRÍÕÑ"}, + {NAME_MIDDLE, "M."}, + {EMAIL_ADDRESS, "MARION@ME.XYZ"}, + {COMPANY_NAME, "Fox Industries Inc."}, + {ADDRESS_HOME_LINE1, "123 zoo st. w., #5"}, + {ADDRESS_HOME_LINE1, ""}, + {ADDRESS_HOME_STATE, "california"}, + {PHONE_HOME_WHOLE_NUMBER, "5678910 ext. 77"}}); AutofillProfile not_mergeable_by_name = - CopyAndModify(p, {{NAME_FIRST, u"Steven"}, - {NAME_FULL, u""}, - {autofill::NAME_LAST_SECOND, u""}}); + CopyAndModify(p, {{NAME_FIRST, "Steven"}, + {NAME_FULL, ""}, + {autofill::NAME_LAST_SECOND, ""}}); AutofillProfile not_mergeable_by_email_address = - CopyAndModify(p, {{EMAIL_ADDRESS, u"marion.morrision@me.xyz"}}); + CopyAndModify(p, {{EMAIL_ADDRESS, "marion.morrision@me.xyz"}}); AutofillProfile not_mergeable_by_company_name = - CopyAndModify(p, {{COMPANY_NAME, u"Hound Corp"}}); + CopyAndModify(p, {{COMPANY_NAME, "Hound Corp"}}); AutofillProfile not_mergeable_by_address = - CopyAndModify(p, {{ADDRESS_HOME_LINE2, u"Unit 7"}}); + CopyAndModify(p, {{ADDRESS_HOME_LINE2, "Unit 7"}}); AutofillProfile not_mergeable_by_phone_number = - CopyAndModify(p, {{PHONE_HOME_WHOLE_NUMBER, u"555-1234"}}); + CopyAndModify(p, {{PHONE_HOME_WHOLE_NUMBER, "555-1234"}}); // Finalize the initial profile. // Note, all other profiles are already finalized. @@ -920,15 +921,15 @@ TEST_P(AutofillProfileComparatorTest, MergeCJKNames) { // Korean names that are all mergeable, but constructed differently. - NameInfo name1 = CreateNameInfo(u"호", u"", u"이영", u"이영 호"); - NameInfo name2 = CreateNameInfo(u"이영호", u"", u"", u"이영호"); - NameInfo name3 = CreateNameInfo(u"영호", u"", u"이", u"이영호"); - NameInfo name4 = CreateNameInfo(u"영호", u"", u"이", u""); - NameInfo name5 = CreateNameInfo(u"영호", u"", u"이", u"이 영호"); + NameInfo name1 = CreateNameInfo("호", "", "이영", "이영 호"); + NameInfo name2 = CreateNameInfo("이영호", "", "", "이영호"); + NameInfo name3 = CreateNameInfo("영호", "", "이", "이영호"); + NameInfo name4 = CreateNameInfo("영호", "", "이", ""); + NameInfo name5 = CreateNameInfo("영호", "", "이", "이 영호"); // Mergeable foreign name in Japanese with a 'KATAKANA MIDDLE DOT'. - NameInfo name6 = CreateNameInfo(u"", u"", u"", u"ゲイツ・ビル"); - NameInfo name7 = CreateNameInfo(u"ビル", u"", u"ゲイツ", u""); + NameInfo name6 = CreateNameInfo("", "", "", "ゲイツ・ビル"); + NameInfo name7 = CreateNameInfo("ビル", "", "ゲイツ", ""); // Set the use dates for the profiles, because |MergeCJKNames()| tries to use // the most recent profile if there is a conflict. The ordering is @@ -948,10 +949,10 @@ AutofillProfile p7 = CreateProfileWithName(name7); // Because |p1| is the most recent, it always wins over others. - MergeNamesAndExpect(p1, p2, CreateNameInfo(u"호", u"", u"이영", u"이영 호")); - MergeNamesAndExpect(p1, p3, CreateNameInfo(u"호", u"", u"이영", u"이영 호")); - MergeNamesAndExpect(p1, p4, CreateNameInfo(u"호", u"", u"이영", u"이영 호")); - MergeNamesAndExpect(p1, p5, CreateNameInfo(u"호", u"", u"이영", u"이영 호")); + MergeNamesAndExpect(p1, p2, CreateNameInfo("호", "", "이영", "이영 호")); + MergeNamesAndExpect(p1, p3, CreateNameInfo("호", "", "이영", "이영 호")); + MergeNamesAndExpect(p1, p4, CreateNameInfo("호", "", "이영", "이영 호")); + MergeNamesAndExpect(p1, p5, CreateNameInfo("호", "", "이영", "이영 호")); // The following tests are not applicable to the logic of the new structured // name. Because we consider not having a surname a valid option for the user. @@ -962,36 +963,34 @@ // |p2| is more recent than |p3|, |p4|, and |p5|. However, it does not // have a surname entry (it was probably parsed with the old logic), so // the other profiles are used as the source for given/surname. - MergeNamesAndExpect(p2, p3, CreateNameInfo(u"영호", u"", u"이", u"이영호")); - MergeNamesAndExpect(p2, p4, CreateNameInfo(u"영호", u"", u"이", u"이영호")); - MergeNamesAndExpect(p2, p5, CreateNameInfo(u"영호", u"", u"이", u"이영호")); + MergeNamesAndExpect(p2, p3, CreateNameInfo("영호", "", "이", "이영호")); + MergeNamesAndExpect(p2, p4, CreateNameInfo("영호", "", "이", "이영호")); + MergeNamesAndExpect(p2, p5, CreateNameInfo("영호", "", "이", "이영호")); } // |p3| is more recent than |p4| and |p5|. - MergeNamesAndExpect(p3, p4, CreateNameInfo(u"영호", u"", u"이", u"이영호")); - MergeNamesAndExpect(p3, p5, CreateNameInfo(u"영호", u"", u"이", u"이영호")); + MergeNamesAndExpect(p3, p4, CreateNameInfo("영호", "", "이", "이영호")); + MergeNamesAndExpect(p3, p5, CreateNameInfo("영호", "", "이", "이영호")); // |p4| is more recent than |p5|. However, it does not have an explicit // full name, so use the one from |p5|. - MergeNamesAndExpect(p4, p5, CreateNameInfo(u"영호", u"", u"이", u"이 영호")); + MergeNamesAndExpect(p4, p5, CreateNameInfo("영호", "", "이", "이 영호")); // There is no conflict between |p6| and |p7|, so use the parts from both. MergeNamesAndExpect(p6, p7, - CreateNameInfo(u"ビル", u"", u"ゲイツ", u"ゲイツ・ビル")); + CreateNameInfo("ビル", "", "ゲイツ", "ゲイツ・ビル")); } TEST_P(AutofillProfileComparatorTest, MergeEmailAddresses) { static const char kEmailA[] = "testaccount@domain.net"; - static const char16_t kEmailA16[] = u"testaccount@domain.net"; static const char kEmailB[] = "TestAccount@Domain.Net"; - static const char16_t kEmailB16[] = u"TestAccount@Domain.Net"; EmailInfo email_a; - email_a.SetRawInfo(EMAIL_ADDRESS, kEmailA16); + email_a.SetRawInfo(EMAIL_ADDRESS, UTF8ToUTF16(kEmailA)); AutofillProfile profile_a = CreateProfileWithEmail(kEmailA); profile_a.set_use_date(AutofillClock::Now()); EmailInfo email_b; - email_b.SetRawInfo(EMAIL_ADDRESS, kEmailB16); + email_b.SetRawInfo(EMAIL_ADDRESS, UTF8ToUTF16(kEmailB)); AutofillProfile profile_b = CreateProfileWithEmail(kEmailB); profile_b.set_use_date(profile_a.use_date() + base::TimeDelta::FromDays(1)); @@ -1003,36 +1002,32 @@ TEST_P(AutofillProfileComparatorTest, MergeCompanyNames) { static const char kCompanyA[] = "Some Company"; - static const char16_t kCompanyA16[] = u"Some Company"; static const char kCompanyB[] = "SÔMÈ ÇÖMPÁÑÝ"; - static const char16_t kCompanyB16[] = u"SÔMÈ ÇÖMPÁÑÝ"; static const char kCompanyC[] = "SÔMÈ ÇÖMPÁÑÝ A.G."; - static const char16_t kCompanyC16[] = u"SÔMÈ ÇÖMPÁÑÝ A.G."; static const char kCompanyD[] = "1987"; - static const char16_t kCompanyD16[] = u"1987"; CompanyInfo company_a; - company_a.SetRawInfo(COMPANY_NAME, kCompanyA16); + company_a.SetRawInfo(COMPANY_NAME, UTF8ToUTF16(kCompanyA)); AutofillProfile profile_a = CreateProfileWithCompanyName(kCompanyA); profile_a.set_use_date(AutofillClock::Now()); // Company Name B is post_normalization identical to Company Name A. The use // date will be used to choose between them. CompanyInfo company_b; - company_b.SetRawInfo(COMPANY_NAME, kCompanyB16); + company_b.SetRawInfo(COMPANY_NAME, UTF8ToUTF16(kCompanyB)); AutofillProfile profile_b = CreateProfileWithCompanyName(kCompanyB); profile_b.set_use_date(profile_a.use_date() + base::TimeDelta::FromDays(1)); // Company Name C is the most complete. Even though it has the earliest use // date, it will be preferred to the other two. CompanyInfo company_c; - company_c.SetRawInfo(COMPANY_NAME, kCompanyC16); + company_c.SetRawInfo(COMPANY_NAME, UTF8ToUTF16(kCompanyC)); AutofillProfile profile_c = CreateProfileWithCompanyName(kCompanyC); profile_c.set_use_date(profile_a.use_date() - base::TimeDelta::FromDays(1)); // Company Name D is in the format of a birthyear, invalid and non-verified. CompanyInfo company_d; - company_d.SetRawInfo(COMPANY_NAME, kCompanyD16); + company_d.SetRawInfo(COMPANY_NAME, UTF8ToUTF16(kCompanyD)); AutofillProfile profile_d = CreateProfileWithCompanyName(kCompanyD); profile_a.set_use_date(AutofillClock::Now()); @@ -1059,23 +1054,16 @@ TEST_P(AutofillProfileComparatorTest, MergePhoneNumbers_NA) { static const char kPhoneA[] = "5550199"; - static const char16_t kPhoneA16[] = u"5550199"; static const char kPhoneB[] = "555.0199"; - static const char16_t kPhoneB16[] = u"555.0199"; static const char kPhoneC[] = "555-0199 ext321"; - static const char16_t kPhoneC16[] = u"555-0199 ext321"; static const char kPhoneD[] = "8005550199"; - static const char16_t kPhoneD16[] = u"8005550199"; static const char kPhoneE[] = "800-555-0199 #321"; - static const char16_t kPhoneE16[] = u"800-555-0199 #321"; static const char kPhoneF[] = "1-800-555-0199 #321"; - static const char16_t kPhoneF16[] = u"1-800-555-0199 #321"; static const char kPhoneG[] = "+1 (800) 555.0199;ext=321"; - static const char16_t kPhoneG16[] = u"+1 (800) 555.0199;ext=321"; - static const char16_t kMergedShortNumber[] = u"5550199"; - static const char16_t kMergedShortNumberExt[] = u"5550199 ext. 321"; - static const char16_t kMergedFullNumber[] = u"+1 800-555-0199"; - static const char16_t kMergedFullNumberExt[] = u"+1 800-555-0199 ext. 321"; + static const char kMergedShortNumber[] = "5550199"; + static const char kMergedShortNumberExt[] = "5550199 ext. 321"; + static const char kMergedFullNumber[] = "+1 800-555-0199"; + static const char kMergedFullNumberExt[] = "+1 800-555-0199 ext. 321"; AutofillProfile profile_a = CreateProfileWithPhoneNumber(kPhoneA); AutofillProfile profile_b = CreateProfileWithPhoneNumber(kPhoneB); @@ -1086,7 +1074,7 @@ AutofillProfile profile_g = CreateProfileWithPhoneNumber(kPhoneG); // Profile A - MergePhoneNumbersAndExpect(profile_a, profile_a, kPhoneA16); + MergePhoneNumbersAndExpect(profile_a, profile_a, kPhoneA); MergePhoneNumbersAndExpect(profile_a, profile_b, kMergedShortNumber); MergePhoneNumbersAndExpect(profile_a, profile_c, kMergedShortNumberExt); MergePhoneNumbersAndExpect(profile_a, profile_d, kMergedFullNumber); @@ -1096,7 +1084,7 @@ // Profile B MergePhoneNumbersAndExpect(profile_b, profile_a, kMergedShortNumber); - MergePhoneNumbersAndExpect(profile_b, profile_b, kPhoneB16); + MergePhoneNumbersAndExpect(profile_b, profile_b, kPhoneB); MergePhoneNumbersAndExpect(profile_b, profile_c, kMergedShortNumberExt); MergePhoneNumbersAndExpect(profile_b, profile_d, kMergedFullNumber); MergePhoneNumbersAndExpect(profile_b, profile_e, kMergedFullNumberExt); @@ -1106,7 +1094,7 @@ // Profile C MergePhoneNumbersAndExpect(profile_c, profile_a, kMergedShortNumberExt); MergePhoneNumbersAndExpect(profile_c, profile_b, kMergedShortNumberExt); - MergePhoneNumbersAndExpect(profile_c, profile_c, kPhoneC16); + MergePhoneNumbersAndExpect(profile_c, profile_c, kPhoneC); MergePhoneNumbersAndExpect(profile_c, profile_d, kMergedFullNumberExt); MergePhoneNumbersAndExpect(profile_c, profile_e, kMergedFullNumberExt); MergePhoneNumbersAndExpect(profile_c, profile_f, kMergedFullNumberExt); @@ -1116,7 +1104,7 @@ MergePhoneNumbersAndExpect(profile_d, profile_a, kMergedFullNumber); MergePhoneNumbersAndExpect(profile_d, profile_b, kMergedFullNumber); MergePhoneNumbersAndExpect(profile_d, profile_c, kMergedFullNumberExt); - MergePhoneNumbersAndExpect(profile_d, profile_d, kPhoneD16); + MergePhoneNumbersAndExpect(profile_d, profile_d, kPhoneD); MergePhoneNumbersAndExpect(profile_d, profile_e, kMergedFullNumberExt); MergePhoneNumbersAndExpect(profile_d, profile_f, kMergedFullNumberExt); MergePhoneNumbersAndExpect(profile_d, profile_g, kMergedFullNumberExt); @@ -1126,7 +1114,7 @@ MergePhoneNumbersAndExpect(profile_e, profile_b, kMergedFullNumberExt); MergePhoneNumbersAndExpect(profile_e, profile_c, kMergedFullNumberExt); MergePhoneNumbersAndExpect(profile_e, profile_d, kMergedFullNumberExt); - MergePhoneNumbersAndExpect(profile_e, profile_e, kPhoneE16); + MergePhoneNumbersAndExpect(profile_e, profile_e, kPhoneE); MergePhoneNumbersAndExpect(profile_e, profile_f, kMergedFullNumberExt); MergePhoneNumbersAndExpect(profile_e, profile_g, kMergedFullNumberExt); @@ -1136,7 +1124,7 @@ MergePhoneNumbersAndExpect(profile_f, profile_c, kMergedFullNumberExt); MergePhoneNumbersAndExpect(profile_f, profile_d, kMergedFullNumberExt); MergePhoneNumbersAndExpect(profile_f, profile_e, kMergedFullNumberExt); - MergePhoneNumbersAndExpect(profile_f, profile_f, kPhoneF16); + MergePhoneNumbersAndExpect(profile_f, profile_f, kPhoneF); MergePhoneNumbersAndExpect(profile_f, profile_g, kMergedFullNumberExt); // Profile G @@ -1146,7 +1134,7 @@ MergePhoneNumbersAndExpect(profile_g, profile_d, kMergedFullNumberExt); MergePhoneNumbersAndExpect(profile_g, profile_e, kMergedFullNumberExt); MergePhoneNumbersAndExpect(profile_g, profile_f, kMergedFullNumberExt); - MergePhoneNumbersAndExpect(profile_g, profile_g, kPhoneG16); + MergePhoneNumbersAndExpect(profile_g, profile_g, kPhoneG); } TEST_P(AutofillProfileComparatorTest, MergePhoneNumbers_Intl) { @@ -1154,15 +1142,11 @@ const AutofillType kCountry(ADDRESS_HOME_COUNTRY); static const char kPhoneA[] = "+49492180185611"; - static const char16_t kPhoneA16[] = u"+49492180185611"; static const char kPhoneB[] = "+49 4921 801 856-11"; - static const char16_t kPhoneB16[] = u"+49 4921 801 856-11"; static const char kPhoneC[] = "+49 4921 8018 5611;ext=22"; - static const char16_t kPhoneC16[] = u"+49 4921 8018 5611;ext=22"; static const char kPhoneD[] = "04921 80185611"; // National Format. - static const char16_t kPhoneD16[] = u"04921 80185611"; // National Format. - static const char16_t kMergedFullNumber[] = u"+49 4921 80185611"; - static const char16_t kMergedFullNumberExt[] = u"+49 4921 80185611 ext. 22"; + static const char kMergedFullNumber[] = "+49 4921 80185611"; + static const char kMergedFullNumberExt[] = "+49 4921 80185611 ext. 22"; AutofillProfile profile_a = CreateProfileWithPhoneNumber(kPhoneA); AutofillProfile profile_b = CreateProfileWithPhoneNumber(kPhoneB); @@ -1175,25 +1159,25 @@ profile_d.SetInfo(kCountry, kGermany, kLocale); // Profile A - MergePhoneNumbersAndExpect(profile_a, profile_a, kPhoneA16); + MergePhoneNumbersAndExpect(profile_a, profile_a, kPhoneA); MergePhoneNumbersAndExpect(profile_a, profile_b, kMergedFullNumber); MergePhoneNumbersAndExpect(profile_a, profile_c, kMergedFullNumberExt); // Profile B MergePhoneNumbersAndExpect(profile_b, profile_a, kMergedFullNumber); - MergePhoneNumbersAndExpect(profile_b, profile_b, kPhoneB16); + MergePhoneNumbersAndExpect(profile_b, profile_b, kPhoneB); MergePhoneNumbersAndExpect(profile_b, profile_c, kMergedFullNumberExt); // Profile C MergePhoneNumbersAndExpect(profile_c, profile_a, kMergedFullNumberExt); MergePhoneNumbersAndExpect(profile_c, profile_b, kMergedFullNumberExt); - MergePhoneNumbersAndExpect(profile_c, profile_c, kPhoneC16); + MergePhoneNumbersAndExpect(profile_c, profile_c, kPhoneC); // Profile D MergePhoneNumbersAndExpect(profile_d, profile_a, kMergedFullNumber); MergePhoneNumbersAndExpect(profile_d, profile_b, kMergedFullNumber); MergePhoneNumbersAndExpect(profile_d, profile_c, kMergedFullNumberExt); - MergePhoneNumbersAndExpect(profile_d, profile_d, kPhoneD16); + MergePhoneNumbersAndExpect(profile_d, profile_d, kPhoneD); } TEST_P(AutofillProfileComparatorTest, MergeAddresses) {
diff --git a/components/autofill/core/browser/data_model/autofill_structured_address.cc b/components/autofill/core/browser/data_model/autofill_structured_address.cc index 0fbedb8..0a92649 100644 --- a/components/autofill/core/browser/data_model/autofill_structured_address.cc +++ b/components/autofill/core/browser/data_model/autofill_structured_address.cc
@@ -150,8 +150,9 @@ base::UTF16ToUTF8(GetRootNode().GetValueForType(ADDRESS_HOME_COUNTRY)); if (country_code == "BR") { - return u"${ADDRESS_HOME_STREET_NAME}${ADDRESS_HOME_HOUSE_NUMBER;, }" - u"${ADDRESS_HOME_FLOOR;, ;º andar}${ADDRESS_HOME_APT_NUM;, apto ;}"; + return base::UTF8ToUTF16( + "${ADDRESS_HOME_STREET_NAME}${ADDRESS_HOME_HOUSE_NUMBER;, }" + "${ADDRESS_HOME_FLOOR;, ;º andar}${ADDRESS_HOME_APT_NUM;, apto ;}"); } if (country_code == "DE") {
diff --git a/components/autofill/core/browser/data_model/autofill_structured_address_unittest.cc b/components/autofill/core/browser/data_model/autofill_structured_address_unittest.cc index 4b1a2f3..c608c723 100644 --- a/components/autofill/core/browser/data_model/autofill_structured_address_unittest.cc +++ b/components/autofill/core/browser/data_model/autofill_structured_address_unittest.cc
@@ -25,12 +25,12 @@ using AddressComponentTestValues = std::vector<AddressComponentTestValue>; struct AddressLineParsingTestCase { - std::string country_code = ""; - std::string street_address = ""; - std::string street_name = ""; - std::string house_number = ""; - std::string floor = ""; - std::string apartment = ""; + std::string country_code; + std::string street_address; + std::string street_name; + std::string house_number; + std::string floor; + std::string apartment; }; std::ostream& operator<<(std::ostream& out,
diff --git a/components/autofill/core/browser/field_filler_unittest.cc b/components/autofill/core/browser/field_filler_unittest.cc index b359e402..e4eebbee 100644 --- a/components/autofill/core/browser/field_filler_unittest.cc +++ b/components/autofill/core/browser/field_filler_unittest.cc
@@ -36,7 +36,9 @@ #include "third_party/libaddressinput/src/cpp/include/libaddressinput/storage.h" #include "third_party/libaddressinput/src/cpp/test/testdata_source.h" +using base::ASCIIToUTF16; using base::StringToInt; +using base::UTF8ToUTF16; namespace autofill { @@ -134,10 +136,10 @@ } struct CreditCardTestCase { - std::u16string card_number_; + std::string card_number_; size_t total_splits_; std::vector<int> splits_; - std::vector<std::u16string> expected_results_; + std::vector<std::string> expected_results_; }; // Returns the offset to be set within the credit card number field. @@ -537,23 +539,23 @@ struct AutofillFieldFillerTestCase { HtmlFieldType field_type; size_t field_max_length; - std::u16string expected_value; + std::string expected_value; AutofillFieldFillerTestCase(HtmlFieldType field_type, size_t field_max_length, - std::u16string expected_value) + std::string expected_value) : field_type(field_type), field_max_length(field_max_length), expected_value(expected_value) {} }; struct AutofillPhoneFieldFillerTestCase : public AutofillFieldFillerTestCase { - std::u16string phone_home_whole_number_value; + std::string phone_home_whole_number_value; AutofillPhoneFieldFillerTestCase(HtmlFieldType field_type, size_t field_max_length, - std::u16string expected_value, - std::u16string phone_home_whole_number_value) + std::string expected_value, + std::string phone_home_whole_number_value) : AutofillFieldFillerTestCase(field_type, field_max_length, expected_value), @@ -574,10 +576,10 @@ AutofillProfile address; address.SetRawInfo(PHONE_HOME_WHOLE_NUMBER, - test_case.phone_home_whole_number_value); + ASCIIToUTF16(test_case.phone_home_whole_number_value)); FieldFiller filler(/*app_locale=*/"en-US", /*address_normalizer=*/nullptr); filler.FillFormField(field, &address, &field, /*cvc=*/std::u16string()); - EXPECT_EQ(test_case.expected_value, field.value); + EXPECT_EQ(ASCIIToUTF16(test_case.expected_value), field.value); } INSTANTIATE_TEST_SUITE_P( @@ -586,43 +588,43 @@ testing::Values( // Filling a prefix type field should just fill the prefix. AutofillPhoneFieldFillerTestCase{HTML_TYPE_TEL_LOCAL_PREFIX, - /*field_max_length=*/0, u"555", - u"+15145554578"}, + /*field_max_length=*/0, "555", + "+15145554578"}, // Filling a suffix type field with a phone number of 7 digits should // just fill the suffix. AutofillPhoneFieldFillerTestCase{HTML_TYPE_TEL_LOCAL_SUFFIX, - /*field_max_length=*/0, u"4578", - u"+15145554578"}, + /*field_max_length=*/0, "4578", + "+15145554578"}, // Filling a phone type field with a max length of 3 should fill only // the prefix. AutofillPhoneFieldFillerTestCase{HTML_TYPE_TEL_LOCAL, - /*field_max_length=*/3, u"555", - u"+15145554578"}, + /*field_max_length=*/3, "555", + "+15145554578"}, // TODO(crbug.com/581485): There should be a test case where the full // number is requested (HTML_TYPE_TEL) but a field_max_length of 3 would // fill the prefix. // Filling a phone type field with a max length of 4 should fill only // the suffix. AutofillPhoneFieldFillerTestCase{HTML_TYPE_TEL, - /*field_max_length=*/4, u"4578", - u"+15145554578"}, + /*field_max_length=*/4, "4578", + "+15145554578"}, // Filling a phone type field with a max length of 10 with a phone // number including the country code should fill the phone number // without the country code. AutofillPhoneFieldFillerTestCase{HTML_TYPE_TEL, - /*field_max_length=*/10, u"5145554578", - u"+15145554578"}, + /*field_max_length=*/10, "5145554578", + "+15145554578"}, // Filling a phone type field with a max length of 5 with a phone number // should fill with the last 5 digits of that phone number. AutofillPhoneFieldFillerTestCase{HTML_TYPE_TEL, - /*field_max_length=*/5, u"54578", - u"+15145554578"}, + /*field_max_length=*/5, "54578", + "+15145554578"}, // Filling a phone type field with a max length of 10 with a phone // number including the country code should fill the phone number // without the country code. AutofillPhoneFieldFillerTestCase{HTML_TYPE_TEL, - /*field_max_length=*/10, u"123456789", - u"+886123456789"})); + /*field_max_length=*/10, "123456789", + "+886123456789"})); class ExpirationYearTest : public testing::TestWithParam<AutofillFieldFillerTestCase> { @@ -641,7 +643,7 @@ card.SetExpirationDateFromString(u"12/2023"); FieldFiller filler(/*app_locale=*/"en-US", /*address_normalizer=*/nullptr); filler.FillFormField(field, &card, &field, /*cvc=*/std::u16string()); - EXPECT_EQ(test_case.expected_value, field.value); + EXPECT_EQ(ASCIIToUTF16(test_case.expected_value), field.value); } INSTANTIATE_TEST_SUITE_P( @@ -652,37 +654,37 @@ // 2 digits of the expiration year if the field has an unspecified max // length (0) or if it's greater than 1. AutofillFieldFillerTestCase{HTML_TYPE_CREDIT_CARD_EXP_2_DIGIT_YEAR, - /* default value */ 0, u"23"}, + /* default value */ 0, "23"}, AutofillFieldFillerTestCase{HTML_TYPE_CREDIT_CARD_EXP_2_DIGIT_YEAR, 2, - u"23"}, + "23"}, AutofillFieldFillerTestCase{HTML_TYPE_CREDIT_CARD_EXP_2_DIGIT_YEAR, 12, - u"23"}, + "23"}, // A field predicted as a 2 digit expiration year should fill the last // digit of the expiration year if the field has a max length of 1. AutofillFieldFillerTestCase{HTML_TYPE_CREDIT_CARD_EXP_2_DIGIT_YEAR, 1, - u"3"}, + "3"}, // A field predicted as a 4 digit expiration year should fill the 4 // digits of the expiration year if the field has an unspecified max // length (0) or if it's greater than 3 . AutofillFieldFillerTestCase{HTML_TYPE_CREDIT_CARD_EXP_4_DIGIT_YEAR, - /* default value */ 0, u"2023"}, + /* default value */ 0, "2023"}, AutofillFieldFillerTestCase{HTML_TYPE_CREDIT_CARD_EXP_4_DIGIT_YEAR, 4, - u"2023"}, + "2023"}, AutofillFieldFillerTestCase{HTML_TYPE_CREDIT_CARD_EXP_4_DIGIT_YEAR, 12, - u"2023"}, + "2023"}, // A field predicted as a 4 digits expiration year should fill the last // 2 digits of the expiration year if the field has a max length of 2. AutofillFieldFillerTestCase{HTML_TYPE_CREDIT_CARD_EXP_4_DIGIT_YEAR, 2, - u"23"}, + "23"}, // A field predicted as a 4 digits expiration year should fill the last // digit of the expiration year if the field has a max length of 1. AutofillFieldFillerTestCase{HTML_TYPE_CREDIT_CARD_EXP_4_DIGIT_YEAR, 1, - u"3"})); + "3"})); struct FillUtilExpirationDateTestCase { HtmlFieldType field_type; size_t field_max_length; - std::u16string expected_value; + std::string expected_value; bool expected_response; }; @@ -704,7 +706,7 @@ FieldFiller filler(/*app_locale=*/"en-US", /*address_normalizer=*/nullptr); bool response = filler.FillFormField(field, &card, &field, /*cvc=*/std::u16string()); - EXPECT_EQ(test_case.expected_value, field.value); + EXPECT_EQ(ASCIIToUTF16(test_case.expected_value), field.value); EXPECT_EQ(response, test_case.expected_response); } @@ -719,30 +721,30 @@ // 7: Use format MM/YYYY FillUtilExpirationDateTestCase{ HTML_TYPE_CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR, - /* default value */ 0, u"03/22", true}, + /* default value */ 0, "03/22", true}, // Unsupported max lengths of 1-3, fail FillUtilExpirationDateTestCase{ - HTML_TYPE_CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR, 1, u"", false}, + HTML_TYPE_CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR, 1, "", false}, FillUtilExpirationDateTestCase{ - HTML_TYPE_CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR, 2, u"", false}, + HTML_TYPE_CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR, 2, "", false}, FillUtilExpirationDateTestCase{ - HTML_TYPE_CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR, 3, u"", false}, + HTML_TYPE_CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR, 3, "", false}, // A max length of 4 indicates a format of MMYY. FillUtilExpirationDateTestCase{ - HTML_TYPE_CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR, 4, u"0322", true}, + HTML_TYPE_CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR, 4, "0322", true}, // A max length of 6 indicates a format of MMYYYY, the 21st century is // assumed. // Desired case of proper max length >= 5 FillUtilExpirationDateTestCase{ - HTML_TYPE_CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR, 5, u"03/22", true}, + HTML_TYPE_CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR, 5, "03/22", true}, FillUtilExpirationDateTestCase{ - HTML_TYPE_CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR, 6, u"032022", true}, + HTML_TYPE_CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR, 6, "032022", true}, // A max length of 7 indicates a format of MM/YYYY, the 21st century is // assumed. FillUtilExpirationDateTestCase{ - HTML_TYPE_CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR, 7, u"03/2022", true}, + HTML_TYPE_CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR, 7, "03/2022", true}, FillUtilExpirationDateTestCase{ - HTML_TYPE_CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR, 12, u"03/22", true}, + HTML_TYPE_CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR, 12, "03/22", true}, // A field predicted as a expiration date w/ 4 digit year should fill // with a format of MM/YYYY unless it has max-length of: @@ -751,29 +753,28 @@ // 6: Use format MMYYYY FillUtilExpirationDateTestCase{ HTML_TYPE_CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR, - /* default value */ 0, u"03/2022", true}, + /* default value */ 0, "03/2022", true}, // Unsupported max lengths of 1-3, fail FillUtilExpirationDateTestCase{ - HTML_TYPE_CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR, 1, u"", false}, + HTML_TYPE_CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR, 1, "", false}, FillUtilExpirationDateTestCase{ - HTML_TYPE_CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR, 2, u"", false}, + HTML_TYPE_CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR, 2, "", false}, FillUtilExpirationDateTestCase{ - HTML_TYPE_CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR, 3, u"", false}, + HTML_TYPE_CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR, 3, "", false}, // A max length of 4 indicates a format of MMYY. FillUtilExpirationDateTestCase{ - HTML_TYPE_CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR, 4, u"0322", true}, + HTML_TYPE_CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR, 4, "0322", true}, // A max length of 5 indicates a format of MM/YY. FillUtilExpirationDateTestCase{ - HTML_TYPE_CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR, 5, u"03/22", true}, + HTML_TYPE_CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR, 5, "03/22", true}, // A max length of 6 indicates a format of MMYYYY. FillUtilExpirationDateTestCase{ - HTML_TYPE_CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR, 6, u"032022", true}, + HTML_TYPE_CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR, 6, "032022", true}, // Desired case of proper max length >= 7 FillUtilExpirationDateTestCase{ - HTML_TYPE_CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR, 7, u"03/2022", true}, + HTML_TYPE_CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR, 7, "03/2022", true}, FillUtilExpirationDateTestCase{ - HTML_TYPE_CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR, 12, u"03/2022", - true})); + HTML_TYPE_CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR, 12, "03/2022", true})); TEST_F(AutofillFieldFillerTest, FillSelectControlByValue) { std::vector<const char*> kOptions = { @@ -822,9 +823,9 @@ struct FillSelectTestCase { std::vector<const char*> select_values; - const char16_t* input_value; - const char16_t* expected_value_without_normalization; - const char16_t* expected_value_with_normalization = nullptr; + const char* input_value; + const char* expected_value_without_normalization; + const char* expected_value_with_normalization = nullptr; }; class AutofillSelectWithStatesTest @@ -879,17 +880,19 @@ // Without a normalizer. AutofillProfile address = test::GetFullProfile(); - address.SetRawInfo(ADDRESS_HOME_STATE, test_case.input_value); + address.SetRawInfo(ADDRESS_HOME_STATE, UTF8ToUTF16(test_case.input_value)); FieldFiller filler(/*app_locale=*/"en-US", /*address_normalizer=*/nullptr); filler.FillFormField(field, &address, &field, /*cvc=*/std::u16string()); // nullptr means we expect them not to match without normalization. if (test_case.expected_value_without_normalization != nullptr) { - EXPECT_EQ(test_case.expected_value_without_normalization, field.value); + EXPECT_EQ(UTF8ToUTF16(test_case.expected_value_without_normalization), + field.value); } // With a normalizer. AutofillProfile canadian_address = test::GetFullCanadianProfile(); - canadian_address.SetRawInfo(ADDRESS_HOME_STATE, test_case.input_value); + canadian_address.SetRawInfo(ADDRESS_HOME_STATE, + UTF8ToUTF16(test_case.input_value)); // Fill a first time without loading the rules for the region. FieldFiller canadian_filler(/*app_locale=*/"en-US", normalizer()); canadian_filler.FillFormField(field, &canadian_address, &field, @@ -897,17 +900,20 @@ // If the expectation with normalization is nullptr, this means that the same // result than without a normalizer is expected. if (test_case.expected_value_with_normalization == nullptr) { - EXPECT_EQ(test_case.expected_value_without_normalization, field.value); + EXPECT_EQ(UTF8ToUTF16(test_case.expected_value_without_normalization), + field.value); } else { // We needed a normalizer with loaded rules. The first fill should have // failed. - EXPECT_NE(test_case.expected_value_with_normalization, field.value); + EXPECT_NE(UTF8ToUTF16(test_case.expected_value_with_normalization), + field.value); // Load the rules and try again. normalizer()->LoadRulesForRegion("CA"); canadian_filler.FillFormField(field, &canadian_address, &field, /*cvc=*/std::u16string()); - EXPECT_EQ(test_case.expected_value_with_normalization, field.value); + EXPECT_EQ(UTF8ToUTF16(test_case.expected_value_with_normalization), + field.value); } } @@ -916,54 +922,54 @@ AutofillSelectWithStatesTest, testing::Values( // Filling the abbreviation. - FillSelectTestCase{{"Alabama", "California"}, u"CA", u"California"}, + FillSelectTestCase{{"Alabama", "California"}, "CA", "California"}, // Attempting to fill the full name in a select full of abbreviations. - FillSelectTestCase{{"AL", "CA"}, u"California", u"CA"}, + FillSelectTestCase{{"AL", "CA"}, "California", "CA"}, // Different case and diacritics. - FillSelectTestCase{{"QUÉBEC", "ALBERTA"}, u"Quebec", u"QUÉBEC"}, + FillSelectTestCase{{"QUÉBEC", "ALBERTA"}, "Quebec", "QUÉBEC"}, // The value and the field options are different but normalize to the // same (NB). FillSelectTestCase{{"Nouveau-Brunswick", "Alberta"}, - u"New Brunswick", + "New Brunswick", nullptr, - u"Nouveau-Brunswick"}, - FillSelectTestCase{{"NB", "AB"}, u"New Brunswick", nullptr, u"NB"}, - FillSelectTestCase{{"NB", "AB"}, u"Nouveau-Brunswick", nullptr, u"NB"}, + "Nouveau-Brunswick"}, + FillSelectTestCase{{"NB", "AB"}, "New Brunswick", nullptr, "NB"}, + FillSelectTestCase{{"NB", "AB"}, "Nouveau-Brunswick", nullptr, "NB"}, FillSelectTestCase{{"Nouveau-Brunswick", "Alberta"}, - u"NB", + "NB", nullptr, - u"Nouveau-Brunswick"}, + "Nouveau-Brunswick"}, FillSelectTestCase{{"New Brunswick", "Alberta"}, - u"NB", + "NB", nullptr, - u"New Brunswick"}, + "New Brunswick"}, // Inexact state names. FillSelectTestCase{ {"SC - South Carolina", "CA - California", "NC - North Carolina"}, - u"California", - u"CA - California"}, + "California", + "CA - California"}, // Don't accidentally match "Virginia" to "West Virginia". FillSelectTestCase{ {"WV - West Virginia", "VA - Virginia", "NV - North Virginia"}, - u"Virginia", - u"VA - Virginia"}, + "Virginia", + "VA - Virginia"}, // Do accidentally match "Virginia" to "West Virginia". // TODO(crbug.com/624770): This test should not pass, but it does // because "Virginia" is a substring of "West Virginia". FillSelectTestCase{{"WV - West Virginia", "TX - Texas"}, - u"Virginia", - u"WV - West Virginia"}, + "Virginia", + "WV - West Virginia"}, // Tests that substring matches work for full state names (a full token // match isn't required). Also tests that matches work for states with // whitespace in the middle. FillSelectTestCase{{"California.", "North Carolina."}, - u"North Carolina", - u"North Carolina."}, + "North Carolina", + "North Carolina."}, FillSelectTestCase{{"NC - North Carolina", "CA - California"}, - u"CA", - u"CA - California"}, + "CA", + "CA - California"}, // These are not states. - FillSelectTestCase{{"NCNCA", "SCNCA"}, u"NC", u""})); + FillSelectTestCase{{"NCNCA", "SCNCA"}, "NC", ""})); TEST_F(AutofillFieldFillerTest, FillSelectWithCountries) { AutofillField field; @@ -1272,12 +1278,16 @@ FieldFiller filler(/*app_locale=*/"en-US", /*address_normalizer=*/nullptr); field.set_heuristic_type(ADDRESS_HOME_STREET_ADDRESS); - std::u16string value = u"123 Fake St.\nApt. 42"; + std::u16string value = + u"123 Fake St.\n" + u"Apt. 42"; address()->SetInfo(AutofillType(ADDRESS_HOME_STREET_ADDRESS), value, "en-US"); filler.FillFormField(field, address(), &field, /*cvc=*/std::u16string()); EXPECT_EQ(value, field.value); - std::u16string ja_value = u"桜丘町26-1\nセルリアンタワー6階"; + std::u16string ja_value = UTF8ToUTF16( + "桜丘町26-1\n" + "セルリアンタワー6階"); address()->SetInfo(AutofillType(ADDRESS_HOME_STREET_ADDRESS), ja_value, "ja-JP"); address()->set_language_code("ja-JP"); @@ -1291,12 +1301,16 @@ field.set_server_type(ADDRESS_HOME_STREET_ADDRESS); FieldFiller filler(/*app_locale=*/"en-US", /*address_normalizer=*/nullptr); - std::u16string value = u"123 Fake St.\nApt. 42"; + std::u16string value = + u"123 Fake St.\n" + u"Apt. 42"; address()->SetInfo(AutofillType(ADDRESS_HOME_STREET_ADDRESS), value, "en-US"); filler.FillFormField(field, address(), &field, /*cvc=*/std::u16string()); EXPECT_EQ(u"123 Fake St., Apt. 42", field.value); - std::u16string ja_value = u"桜丘町26-1\nセルリアンタワー6階"; + std::u16string ja_value = UTF8ToUTF16( + "桜丘町26-1\n" + "セルリアンタワー6階"); address()->SetInfo(AutofillType(ADDRESS_HOME_STREET_ADDRESS), ja_value, "ja-JP"); address()->set_language_code("ja-JP"); @@ -1322,11 +1336,13 @@ TEST_F(AutofillFieldFillerTest, FillCreditCardNumberWithEqualSizeSplits) { // Case 2: card number broken up into four equal groups, of length 4. CreditCardTestCase test; - test.card_number_ = u"5187654321098765"; + test.card_number_ = "5187654321098765"; test.total_splits_ = 4; int splits[] = {4, 4, 4, 4}; test.splits_ = std::vector<int>(splits, splits + base::size(splits)); - test.expected_results_ = {u"5187", u"6543", u"2109", u"8765"}; + std::string results[] = {"5187", "6543", "2109", "8765"}; + test.expected_results_ = + std::vector<std::string>(results, results + base::size(results)); FieldFiller filler(/*app_locale=*/"en-US", /*address_normalizer=*/nullptr); for (size_t i = 0; i < test.total_splits_; ++i) { @@ -1336,12 +1352,12 @@ cc_number_part.set_credit_card_number_offset(4 * i); // Fill with a card-number; should fill just the card_number_part. - credit_card()->SetNumber(test.card_number_); + credit_card()->SetNumber(ASCIIToUTF16(test.card_number_)); filler.FillFormField(cc_number_part, credit_card(), &cc_number_part, /*cvc=*/std::u16string()); // Verify for expected results. - EXPECT_EQ(test.expected_results_[i], + EXPECT_EQ(ASCIIToUTF16(test.expected_results_[i]), cc_number_part.value.substr(0, cc_number_part.max_length)); EXPECT_EQ(4 * i, cc_number_part.credit_card_number_offset()); } @@ -1350,23 +1366,25 @@ AutofillField cc_number_full; cc_number_full.set_heuristic_type(CREDIT_CARD_NUMBER); - credit_card()->SetNumber(test.card_number_); + credit_card()->SetNumber(ASCIIToUTF16(test.card_number_)); filler.FillFormField(cc_number_full, credit_card(), &cc_number_full, /*cvc=*/std::u16string()); // Verify for expected results. - EXPECT_EQ(test.card_number_, cc_number_full.value); + EXPECT_EQ(ASCIIToUTF16(test.card_number_), cc_number_full.value); } TEST_F(AutofillFieldFillerTest, FillCreditCardNumberWithUnequalSizeSplits) { // Case 3: card with 15 digits number, broken up into three unequal groups, of // lengths 4, 6, and 5. CreditCardTestCase test; - test.card_number_ = u"423456789012345"; + test.card_number_ = "423456789012345"; test.total_splits_ = 3; int splits[] = {4, 6, 5}; test.splits_ = std::vector<int>(splits, splits + base::size(splits)); - test.expected_results_ = {u"4234", u"567890", u"12345"}; + std::string results[] = {"4234", "567890", "12345"}; + test.expected_results_ = + std::vector<std::string>(results, results + base::size(results)); FieldFiller filler(/*app_locale=*/"en-US", /*address_normalizer=*/nullptr); // Start executing test cases to verify parts and full credit card number. @@ -1377,12 +1395,12 @@ cc_number_part.set_credit_card_number_offset(GetNumberOffset(i, test)); // Fill with a card-number; should fill just the card_number_part. - credit_card()->SetNumber(test.card_number_); + credit_card()->SetNumber(ASCIIToUTF16(test.card_number_)); filler.FillFormField(cc_number_part, credit_card(), &cc_number_part, /*cvc=*/std::u16string()); // Verify for expected results. - EXPECT_EQ(test.expected_results_[i], + EXPECT_EQ(ASCIIToUTF16(test.expected_results_[i]), cc_number_part.value.substr(0, cc_number_part.max_length)); EXPECT_EQ(GetNumberOffset(i, test), cc_number_part.credit_card_number_offset()); @@ -1391,12 +1409,12 @@ // Verify that full card-number shall get fill properly as well. AutofillField cc_number_full; cc_number_full.set_heuristic_type(CREDIT_CARD_NUMBER); - credit_card()->SetNumber(test.card_number_); + credit_card()->SetNumber(ASCIIToUTF16(test.card_number_)); filler.FillFormField(cc_number_full, credit_card(), &cc_number_full, /*cvc=*/std::u16string()); // Verify for expected results. - EXPECT_EQ(test.card_number_, cc_number_full.value); + EXPECT_EQ(ASCIIToUTF16(test.card_number_), cc_number_full.value); } TEST_F(AutofillFieldFillerTest, FindShortestSubstringMatchInSelect) { @@ -1446,8 +1464,8 @@ struct FillStateTextTestCase { HtmlFieldType field_type; size_t field_max_length; - std::u16string value_to_fill; - std::u16string expected_value; + std::string value_to_fill; + std::string expected_value; bool should_fill; }; @@ -1465,12 +1483,12 @@ FieldFiller filler(/*app_locale=*/"en-US", /*address_normalizer=*/nullptr); AutofillProfile address = test::GetFullProfile(); - address.SetRawInfo(ADDRESS_HOME_STATE, test_case.value_to_fill); + address.SetRawInfo(ADDRESS_HOME_STATE, UTF8ToUTF16(test_case.value_to_fill)); bool has_filled = filler.FillFormField(field, &address, &field, /*cvc=*/std::u16string()); EXPECT_EQ(test_case.should_fill, has_filled); - EXPECT_EQ(test_case.expected_value, field.value); + EXPECT_EQ(ASCIIToUTF16(test_case.expected_value), field.value); } INSTANTIATE_TEST_SUITE_P( @@ -1481,28 +1499,28 @@ // should // fill the state value as is. FillStateTextTestCase{HTML_TYPE_ADDRESS_LEVEL1, /* default value */ 0, - u"New York", u"New York", true}, + "New York", "New York", true}, FillStateTextTestCase{HTML_TYPE_ADDRESS_LEVEL1, /* default value */ 0, - u"NY", u"NY", true}, + "NY", "NY", true}, // Filling a state to a text field with a maxlength value equal to the // value's length should fill the state value as is. - FillStateTextTestCase{HTML_TYPE_ADDRESS_LEVEL1, 8, u"New York", - u"New York", true}, + FillStateTextTestCase{HTML_TYPE_ADDRESS_LEVEL1, 8, "New York", + "New York", true}, // Filling a state to a text field with a maxlength value lower than the // value's length but higher than the value's abbreviation should fill // the state abbreviation. - FillStateTextTestCase{HTML_TYPE_ADDRESS_LEVEL1, 2, u"New York", u"NY", + FillStateTextTestCase{HTML_TYPE_ADDRESS_LEVEL1, 2, "New York", "NY", true}, - FillStateTextTestCase{HTML_TYPE_ADDRESS_LEVEL1, 2, u"NY", u"NY", true}, + FillStateTextTestCase{HTML_TYPE_ADDRESS_LEVEL1, 2, "NY", "NY", true}, // Filling a state to a text field with a maxlength value lower than the // value's length and the value's abbreviation should not fill at all. - FillStateTextTestCase{HTML_TYPE_ADDRESS_LEVEL1, 1, u"New York", u"", + FillStateTextTestCase{HTML_TYPE_ADDRESS_LEVEL1, 1, "New York", "", false}, - FillStateTextTestCase{HTML_TYPE_ADDRESS_LEVEL1, 1, u"NY", u"", false}, + FillStateTextTestCase{HTML_TYPE_ADDRESS_LEVEL1, 1, "NY", "", false}, // Filling a state to a text field with a maxlength value lower than the // value's length and that has no associated abbreviation should not // fill at all. - FillStateTextTestCase{HTML_TYPE_ADDRESS_LEVEL1, 3, u"Quebec", u"", + FillStateTextTestCase{HTML_TYPE_ADDRESS_LEVEL1, 3, "Quebec", "", false})); // Tests that the correct option is chosen in the selection box when one of the
diff --git a/components/autofill/core/browser/form_parsing/form_field_unittest.cc b/components/autofill/core/browser/form_parsing/form_field_unittest.cc index 2d04f20..54e0c2e 100644 --- a/components/autofill/core/browser/form_parsing/form_field_unittest.cc +++ b/components/autofill/core/browser/form_parsing/form_field_unittest.cc
@@ -15,6 +15,7 @@ #include "testing/gtest/include/gtest/gtest.h" using autofill::features::kAutofillFixFillableFieldTypes; +using base::ASCIIToUTF16; namespace autofill { @@ -25,9 +26,9 @@ } // Sets both the field label and parseable label to |label|. -void SetFieldLabels(AutofillField* field, const std::u16string& label) { - field->label = label; - field->set_parseable_label(label); +void SetFieldLabels(AutofillField* field, const std::string& label) { + field->label = base::UTF8ToUTF16(label); + field->set_parseable_label(base::UTF8ToUTF16(label)); } } // namespace @@ -39,76 +40,76 @@ EXPECT_TRUE(FormField::Match(&field, std::u16string(), MATCH_LABEL)); // Empty pattern matches non-empty string. - SetFieldLabels(&field, u"a"); + SetFieldLabels(&field, "a"); EXPECT_TRUE(FormField::Match(&field, std::u16string(), MATCH_LABEL)); // Strictly empty pattern matches empty string. - SetFieldLabels(&field, u""); + SetFieldLabels(&field, ""); EXPECT_TRUE(FormField::Match(&field, u"^$", MATCH_LABEL)); // Strictly empty pattern does not match non-empty string. - SetFieldLabels(&field, u"a"); + SetFieldLabels(&field, "a"); EXPECT_FALSE(FormField::Match(&field, u"^$", MATCH_LABEL)); // Non-empty pattern doesn't match empty string. - SetFieldLabels(&field, u""); + SetFieldLabels(&field, ""); EXPECT_FALSE(FormField::Match(&field, u"a", MATCH_LABEL)); // Beginning of line. - SetFieldLabels(&field, u"head_tail"); + SetFieldLabels(&field, "head_tail"); EXPECT_TRUE(FormField::Match(&field, u"^head", MATCH_LABEL)); EXPECT_FALSE(FormField::Match(&field, u"^tail", MATCH_LABEL)); // End of line. - SetFieldLabels(&field, u"head_tail"); + SetFieldLabels(&field, "head_tail"); EXPECT_FALSE(FormField::Match(&field, u"head$", MATCH_LABEL)); EXPECT_TRUE(FormField::Match(&field, u"tail$", MATCH_LABEL)); // Exact. - SetFieldLabels(&field, u"head_tail"); + SetFieldLabels(&field, "head_tail"); EXPECT_FALSE(FormField::Match(&field, u"^head$", MATCH_LABEL)); EXPECT_FALSE(FormField::Match(&field, u"^tail$", MATCH_LABEL)); EXPECT_TRUE(FormField::Match(&field, u"^head_tail$", MATCH_LABEL)); // Escaped dots. - SetFieldLabels(&field, u"m.i."); + SetFieldLabels(&field, "m.i."); // Note: This pattern is misleading as the "." characters are wild cards. EXPECT_TRUE(FormField::Match(&field, u"m.i.", MATCH_LABEL)); EXPECT_TRUE(FormField::Match(&field, u"m\\.i\\.", MATCH_LABEL)); - SetFieldLabels(&field, u"mXiX"); + SetFieldLabels(&field, "mXiX"); EXPECT_TRUE(FormField::Match(&field, u"m.i.", MATCH_LABEL)); EXPECT_FALSE(FormField::Match(&field, u"m\\.i\\.", MATCH_LABEL)); // Repetition. - SetFieldLabels(&field, u"headtail"); + SetFieldLabels(&field, "headtail"); EXPECT_TRUE(FormField::Match(&field, u"head.*tail", MATCH_LABEL)); - SetFieldLabels(&field, u"headXtail"); + SetFieldLabels(&field, "headXtail"); EXPECT_TRUE(FormField::Match(&field, u"head.*tail", MATCH_LABEL)); - SetFieldLabels(&field, u"headXXXtail"); + SetFieldLabels(&field, "headXXXtail"); EXPECT_TRUE(FormField::Match(&field, u"head.*tail", MATCH_LABEL)); - SetFieldLabels(&field, u"headtail"); + SetFieldLabels(&field, "headtail"); EXPECT_FALSE(FormField::Match(&field, u"head.+tail", MATCH_LABEL)); - SetFieldLabels(&field, u"headXtail"); + SetFieldLabels(&field, "headXtail"); EXPECT_TRUE(FormField::Match(&field, u"head.+tail", MATCH_LABEL)); - SetFieldLabels(&field, u"headXXXtail"); + SetFieldLabels(&field, "headXXXtail"); EXPECT_TRUE(FormField::Match(&field, u"head.+tail", MATCH_LABEL)); // Alternation. - SetFieldLabels(&field, u"head_tail"); + SetFieldLabels(&field, "head_tail"); EXPECT_TRUE(FormField::Match(&field, u"head|other", MATCH_LABEL)); EXPECT_TRUE(FormField::Match(&field, u"tail|other", MATCH_LABEL)); EXPECT_FALSE(FormField::Match(&field, u"bad|good", MATCH_LABEL)); // Case sensitivity. - SetFieldLabels(&field, u"xxxHeAd_tAiLxxx"); + SetFieldLabels(&field, "xxxHeAd_tAiLxxx"); EXPECT_TRUE(FormField::Match(&field, u"head_tail", MATCH_LABEL)); // Word boundaries. - SetFieldLabels(&field, u"contains word:"); + SetFieldLabels(&field, "contains word:"); EXPECT_TRUE(FormField::Match(&field, u"\\bword\\b", MATCH_LABEL)); EXPECT_FALSE(FormField::Match(&field, u"\\bcon\\b", MATCH_LABEL)); - // Make sure the circumflex in 'crêpe' is not treated as a word boundary. - field.label = u"crêpe"; + // Make sure the circumflex in 'crepe' is not treated as a word boundary. + field.label = base::UTF8ToUTF16("cr\xC3\xAApe"); EXPECT_FALSE(FormField::Match(&field, u"\\bcr\\b", MATCH_LABEL)); }
diff --git a/components/autofill/core/browser/form_processing/name_processing_util.cc b/components/autofill/core/browser/form_processing/name_processing_util.cc index fc78a6ca..29140ba 100644 --- a/components/autofill/core/browser/form_processing/name_processing_util.cc +++ b/components/autofill/core/browser/form_processing/name_processing_util.cc
@@ -28,7 +28,7 @@ constexpr int kMinCommonNameLongPrefixLength = 16; // Regular expression for checking if |parseable_name| is valid after stripping // affixes. -constexpr char16_t kParseableNameValidationRe[] = u"\\D"; +constexpr char kParseableNameValidationRe[] = "\\D"; using NamePieces = std::vector<base::StringPiece16>; using OptionalNamePieces = base::Optional<NamePieces>; @@ -85,7 +85,7 @@ // is the |autofill::kParseableNameValidationRe| regex. bool IsValidParseableName(const base::StringPiece16 parseable_name) { static const std::u16string kParseableNameValidationPattern = - kParseableNameValidationRe; + base::UTF8ToUTF16(kParseableNameValidationRe); return MatchesPattern(parseable_name, kParseableNameValidationPattern); }
diff --git a/components/autofill/core/browser/geo/phone_number_i18n_unittest.cc b/components/autofill/core/browser/geo/phone_number_i18n_unittest.cc index 9139a8e..5b5148f 100644 --- a/components/autofill/core/browser/geo/phone_number_i18n_unittest.cc +++ b/components/autofill/core/browser/geo/phone_number_i18n_unittest.cc
@@ -15,6 +15,9 @@ #include "testing/gtest/include/gtest/gtest.h" #include "third_party/libphonenumber/phonenumber_api.h" +using base::ASCIIToUTF16; +using base::UTF8ToUTF16; + namespace autofill { using i18n::ConstructPhoneNumber; @@ -23,15 +26,20 @@ using i18n::PhoneNumbersMatch; TEST(PhoneNumberI18NTest, NormalizePhoneNumber) { - // "Large" digits; these are not ASCII. - std::u16string phone1(u"16507498323"); + // "Large" digits. + std::u16string phone1( + UTF8ToUTF16("\xEF\xBC\x91\xEF\xBC\x96\xEF\xBC\x95\xEF\xBC\x90" + "\xEF\xBC\x97\xEF\xBC\x94\xEF\xBC\x99\xEF\xBC\x98" + "\xEF\xBC\x93\xEF\xBC\x92\xEF\xBC\x93")); EXPECT_EQ(NormalizePhoneNumber(phone1, "US"), u"16507498323"); // Devanagari script digits. - std::u16string phone2(u"١٦٥٠٨٣٢٣٧٤٩"); + std::u16string phone2( + UTF8ToUTF16("\xD9\xA1\xD9\xA6\xD9\xA5\xD9\xA0\xD9\xA8\xD9\xA3" + "\xD9\xA2\xD9\xA3\xD9\xA7\xD9\xA4\xD9\xA9")); EXPECT_EQ(NormalizePhoneNumber(phone2, "US"), u"16508323749"); - std::u16string phone3(u"1650333425٥"); + std::u16string phone3(UTF8ToUTF16("16503334\xef\xbc\x92\x35\xd9\xa5")); EXPECT_EQ(NormalizePhoneNumber(phone3, "US"), u"16503334255"); std::u16string phone4(u"+1(650)2346789"); @@ -45,20 +53,20 @@ // Expected parsing result. bool isPossibleNumber; // Inputs. - std::u16string input; + std::string input; std::string assumed_region; // Further expectations. - std::u16string number; - std::u16string city_code; - std::u16string country_code; + std::string number; + std::string city_code; + std::string country_code; std::string deduced_region; }; namespace { // Returns a string which is too long to be considered a phone number. -std::u16string GenerateTooLongString() { - return std::u16string(i18n::kMaxPhoneNumberSize + 1, u'7'); +std::string GenerateTooLongString() { + return std::string(i18n::kMaxPhoneNumberSize + 1, '7'); } } // namespace @@ -67,18 +75,19 @@ TEST_P(ParseNumberTest, ParsePhoneNumber) { auto test_case = GetParam(); - SCOPED_TRACE(test_case.input.c_str()); + SCOPED_TRACE("Testing phone number " + test_case.input); std::u16string country_code, city_code, number; std::string deduced_region; ::i18n::phonenumbers::PhoneNumber unused_i18n_number; - EXPECT_EQ(test_case.isPossibleNumber, - ParsePhoneNumber(test_case.input, test_case.assumed_region, - &country_code, &city_code, &number, - &deduced_region, &unused_i18n_number)); - EXPECT_EQ(test_case.number, number); - EXPECT_EQ(test_case.city_code, city_code); - EXPECT_EQ(test_case.country_code, country_code); + EXPECT_EQ( + test_case.isPossibleNumber, + ParsePhoneNumber(UTF8ToUTF16(test_case.input), test_case.assumed_region, + &country_code, &city_code, &number, &deduced_region, + &unused_i18n_number)); + EXPECT_EQ(ASCIIToUTF16(test_case.number), number); + EXPECT_EQ(ASCIIToUTF16(test_case.city_code), city_code); + EXPECT_EQ(ASCIIToUTF16(test_case.country_code), country_code); EXPECT_EQ(test_case.deduced_region, deduced_region); } @@ -87,93 +96,99 @@ ParseNumberTest, testing::Values( // Test for empty string. Should give back empty strings. - ParseNumberTestCase{false, u"", "US"}, + ParseNumberTestCase{false, "", "US"}, // Test for string with less than 7 digits. Should give back empty // strings. - ParseNumberTestCase{false, u"1234", "US"}, + ParseNumberTestCase{false, "1234", "US"}, // Too long strings should not be parsed. ParseNumberTestCase{false, GenerateTooLongString(), "US"}, // Test for string with exactly 7 digits. It is too short. // Should fail parsing in US. - ParseNumberTestCase{false, u"17134567", "US"}, + ParseNumberTestCase{false, "17134567", "US"}, // Does not have area code, but still a possible number with // unknown("ZZ") deduced region. - ParseNumberTestCase{true, u"7134567", "US", u"7134567", u"", u"", "ZZ"}, + ParseNumberTestCase{true, "7134567", "US", "7134567", "", "", "ZZ"}, // Valid Canadian toll-free number. - ParseNumberTestCase{true, u"3101234", "CA", u"3101234", u"", u"", "ZZ"}, + ParseNumberTestCase{true, "3101234", "CA", "3101234", "", "", "ZZ"}, // Test for string with greater than 7 digits but less than 10 digits. // Should fail parsing in US. - ParseNumberTestCase{false, u"123456789", "US"}, + ParseNumberTestCase{false, "123456789", "US"}, // Test for string with greater than 7 digits but less than 10 digits // and // separators. // Should fail parsing in US. - ParseNumberTestCase{false, u"12.345-6789", "US"}, + ParseNumberTestCase{false, "12.345-6789", "US"}, // Non-printable ASCII. - ParseNumberTestCase{false, u"123", "US"}, - ParseNumberTestCase{false, u"123\u007f567", "US"}, + ParseNumberTestCase{false, "123\x11", "US"}, + ParseNumberTestCase{false, + "123\x7F" + "567", + "US"}, // Unicode noncharacters. - ParseNumberTestCase{false, u"1\ufdef23", "US"}, - // Invalid UTF16. - ParseNumberTestCase{false, u"1\xdfff", "US"}, + ParseNumberTestCase{false, + "1\xEF\xB7\xAF" + "23", + "US"}, + // Invalid UTF8. + ParseNumberTestCase{false, "1\xC0", "US"}, // Test for string with exactly 10 digits. // Should give back phone number and city code. // This one has an incorrect area code but could still be a possible // number with unknown("ZZ") deducted region. - ParseNumberTestCase{true, u"1234567890", "US", u"1234567890", u"", u"", + ParseNumberTestCase{true, "1234567890", "US", "1234567890", "", "", "ZZ"}, // This is actually not a valid number because the first number after // area code is 1. But it's still a possible number, just with deduced // country set to unknown("ZZ"). - ParseNumberTestCase{true, u"6501567890", "US", u"1567890", u"650", u"", + ParseNumberTestCase{true, "6501567890", "US", "1567890", "650", "", "ZZ"}, - ParseNumberTestCase{true, u"6504567890", "US", u"4567890", u"650", u"", + ParseNumberTestCase{true, "6504567890", "US", "4567890", "650", "", "US"}, // Test for string with exactly 10 digits and separators. // Should give back phone number and city code. - ParseNumberTestCase{true, u"(650) 456-7890", "US", u"4567890", u"650", - u"", "US"}, + ParseNumberTestCase{true, "(650) 456-7890", "US", "4567890", "650", "", + "US"}, // Tests for string with over 10 digits. // 01 is incorrect prefix in the USA, we interpret 011 as prefix, and // rest is parsed as a Singapore number(country code "SG"). - ParseNumberTestCase{true, u"0116504567890", "US", u"04567890", u"", - u"65", "SG"}, + ParseNumberTestCase{true, "0116504567890", "US", "04567890", "", "65", + "SG"}, // 011 is a correct "dial out" prefix in the USA - the parsing should // succeed. - ParseNumberTestCase{true, u"01116504567890", "US", u"4567890", u"650", - u"1", "US"}, + ParseNumberTestCase{true, "01116504567890", "US", "4567890", "650", "1", + "US"}, // 011 is a correct "dial out" prefix in the USA but the rest of the // number // can't parse as a US number. - ParseNumberTestCase{true, u"01178124567890", "US", u"4567890", u"812", - u"7", "RU"}, + ParseNumberTestCase{true, "01178124567890", "US", "4567890", "812", "7", + "RU"}, // Test for string with over 10 digits with separator characters. // Should give back phone number, city code, and country code. "011" is // US "dial out" code, which is discarded. - ParseNumberTestCase{true, u"(0111) 650-456.7890", "US", u"4567890", - u"650", u"1", "US"}, + ParseNumberTestCase{true, "(0111) 650-456.7890", "US", "4567890", "650", + "1", "US"}, // Now try phone from Czech republic - it has 00 dial out code, 420 // country // code and variable length area codes. - ParseNumberTestCase{true, u"+420 27-89.10.112", "US", u"910112", u"278", - u"420", "CZ"}, - ParseNumberTestCase{false, u"27-89.10.112", "US"}, - ParseNumberTestCase{true, u"27-89.10.112", "CZ", u"910112", u"278", u"", + ParseNumberTestCase{true, "+420 27-89.10.112", "US", "910112", "278", + "420", "CZ"}, + ParseNumberTestCase{false, "27-89.10.112", "US"}, + ParseNumberTestCase{true, "27-89.10.112", "CZ", "910112", "278", "", "CZ"}, - ParseNumberTestCase{false, u"420 57-89.10.112", "US"}, - ParseNumberTestCase{true, u"420 57-89.10.112", "CZ", u"910112", u"578", - u"420", "CZ"}, + ParseNumberTestCase{false, "420 57-89.10.112", "US"}, + ParseNumberTestCase{true, "420 57-89.10.112", "CZ", "910112", "578", + "420", "CZ"}, // Parses vanity numbers. - ParseNumberTestCase{true, u"1-650-FLOWERS", "US", u"3569377", u"650", - u"1", "US"}, + ParseNumberTestCase{true, "1-650-FLOWERS", "US", "3569377", "650", "1", + "US"}, // 800 is not an area code, but the destination code. In our library // these // codes should be treated the same as area codes. - ParseNumberTestCase{true, u"1-800-FLOWERS", "US", u"3569377", u"800", - u"1", "US"}, + ParseNumberTestCase{true, "1-800-FLOWERS", "US", "3569377", "800", "1", + "US"}, // Don't add a country code where there was none. - ParseNumberTestCase{true, u"(08) 450 777 7777", "DE", u"7777777", - u"8450", u"", "DE"})); + ParseNumberTestCase{true, "(08) 450 777 7777", "DE", "7777777", "8450", + "", "DE"})); TEST(PhoneNumberI18NTest, ConstructPhoneNumber) { std::u16string number; @@ -301,18 +316,18 @@ // Test for the GetFormattedPhoneNumberForDisplay method. struct PhoneNumberFormatCase { - PhoneNumberFormatCase(const char16_t* phone, - const char16_t* country, - const char16_t* expected_format, + PhoneNumberFormatCase(const char* phone, + const char* country, + const char* expected_format, const char* locale = "") : phone(phone), country(country), expected_format(expected_format), locale(locale) {} - const char16_t* phone; - const char16_t* country; - const char16_t* expected_format; + const char* phone; + const char* country; + const char* expected_format; const char* locale; }; @@ -322,10 +337,13 @@ TEST_P(GetFormattedPhoneNumberForDisplayTest, GetFormattedPhoneNumberForDisplay) { AutofillProfile profile; - profile.SetRawInfo(PHONE_HOME_WHOLE_NUMBER, GetParam().phone); - profile.SetRawInfo(ADDRESS_HOME_COUNTRY, GetParam().country); - EXPECT_EQ(GetParam().expected_format, i18n::GetFormattedPhoneNumberForDisplay( - profile, GetParam().locale)); + profile.SetRawInfo(PHONE_HOME_WHOLE_NUMBER, + base::UTF8ToUTF16(GetParam().phone)); + profile.SetRawInfo(ADDRESS_HOME_COUNTRY, + base::UTF8ToUTF16(GetParam().country)); + EXPECT_EQ(GetParam().expected_format, + base::UTF16ToUTF8(i18n::GetFormattedPhoneNumberForDisplay( + profile, GetParam().locale))); } INSTANTIATE_TEST_SUITE_P( @@ -336,104 +354,104 @@ // US phone in US. ////////////////////////// // Formatted phone numbers. - PhoneNumberFormatCase(u"+1 415-555-5555", u"US", u"+1 415-555-5555"), - PhoneNumberFormatCase(u"1 415-555-5555", u"US", u"+1 415-555-5555"), - PhoneNumberFormatCase(u"415-555-5555", u"US", u"+1 415-555-5555"), + PhoneNumberFormatCase("+1 415-555-5555", "US", "+1 415-555-5555"), + PhoneNumberFormatCase("1 415-555-5555", "US", "+1 415-555-5555"), + PhoneNumberFormatCase("415-555-5555", "US", "+1 415-555-5555"), // Raw phone numbers. - PhoneNumberFormatCase(u"+14155555555", u"US", u"+1 415-555-5555"), - PhoneNumberFormatCase(u"14155555555", u"US", u"+1 415-555-5555"), - PhoneNumberFormatCase(u"4155555555", u"US", u"+1 415-555-5555"), + PhoneNumberFormatCase("+14155555555", "US", "+1 415-555-5555"), + PhoneNumberFormatCase("14155555555", "US", "+1 415-555-5555"), + PhoneNumberFormatCase("4155555555", "US", "+1 415-555-5555"), ////////////////////////// // US phone in CA. ////////////////////////// // Formatted phone numbers. - PhoneNumberFormatCase(u"+1 415-555-5555", u"CA", u"+1 415-555-5555"), - PhoneNumberFormatCase(u"1 415-555-5555", u"CA", u"+1 415-555-5555"), - PhoneNumberFormatCase(u"415-555-5555", u"CA", u"+1 415-555-5555"), + PhoneNumberFormatCase("+1 415-555-5555", "CA", "+1 415-555-5555"), + PhoneNumberFormatCase("1 415-555-5555", "CA", "+1 415-555-5555"), + PhoneNumberFormatCase("415-555-5555", "CA", "+1 415-555-5555"), // Raw phone numbers. - PhoneNumberFormatCase(u"+14155555555", u"CA", u"+1 415-555-5555"), - PhoneNumberFormatCase(u"14155555555", u"CA", u"+1 415-555-5555"), - PhoneNumberFormatCase(u"4155555555", u"CA", u"+1 415-555-5555"), + PhoneNumberFormatCase("+14155555555", "CA", "+1 415-555-5555"), + PhoneNumberFormatCase("14155555555", "CA", "+1 415-555-5555"), + PhoneNumberFormatCase("4155555555", "CA", "+1 415-555-5555"), ////////////////////////// // US phone in AU. ////////////////////////// // A US phone with the country code is correctly formatted as an US // number. - PhoneNumberFormatCase(u"+1 415-555-5555", u"AU", u"+1 415-555-5555"), - PhoneNumberFormatCase(u"1 415-555-5555", u"AU", u"+1 415-555-5555"), + PhoneNumberFormatCase("+1 415-555-5555", "AU", "+1 415-555-5555"), + PhoneNumberFormatCase("1 415-555-5555", "AU", "+1 415-555-5555"), // Without a country code, the phone is formatted for the profile's // country, if it's valid. - PhoneNumberFormatCase(u"2 9374 4000", u"AU", u"+61 2 9374 4000"), + PhoneNumberFormatCase("2 9374 4000", "AU", "+61 2 9374 4000"), // Without a country code, formatting returns the number as entered by // user, if it's invalid. - PhoneNumberFormatCase(u"415-555-5555", u"AU", u"4155555555"), + PhoneNumberFormatCase("415-555-5555", "AU", "4155555555"), ////////////////////////// // US phone in MX. ////////////////////////// // A US phone with the country code is correctly formatted as an US // number. - PhoneNumberFormatCase(u"+1 415-555-5555", u"MX", u"+1 415-555-5555"), + PhoneNumberFormatCase("+1 415-555-5555", "MX", "+1 415-555-5555"), // "+52 415 555 5555" is a valid number for Mexico, - PhoneNumberFormatCase(u"1 415-555-5555", u"MX", u"+52 415 555 5555"), + PhoneNumberFormatCase("1 415-555-5555", "MX", "+52 415 555 5555"), // Without a country code, the phone is formatted for the profile's // country. - PhoneNumberFormatCase(u"415-555-5555", u"MX", u"+52 415 555 5555"), + PhoneNumberFormatCase("415-555-5555", "MX", "+52 415 555 5555"), ////////////////////////// // AU phone in AU. ////////////////////////// // Formatted phone numbers. - PhoneNumberFormatCase(u"+61 2 9374 4000", u"AU", u"+61 2 9374 4000"), - PhoneNumberFormatCase(u"61 2 9374 4000", u"AU", u"+61 2 9374 4000"), - PhoneNumberFormatCase(u"02 9374 4000", u"AU", u"+61 2 9374 4000"), - PhoneNumberFormatCase(u"2 9374 4000", u"AU", u"+61 2 9374 4000"), + PhoneNumberFormatCase("+61 2 9374 4000", "AU", "+61 2 9374 4000"), + PhoneNumberFormatCase("61 2 9374 4000", "AU", "+61 2 9374 4000"), + PhoneNumberFormatCase("02 9374 4000", "AU", "+61 2 9374 4000"), + PhoneNumberFormatCase("2 9374 4000", "AU", "+61 2 9374 4000"), // Raw phone numbers. - PhoneNumberFormatCase(u"+61293744000", u"AU", u"+61 2 9374 4000"), - PhoneNumberFormatCase(u"61293744000", u"AU", u"+61 2 9374 4000"), - PhoneNumberFormatCase(u"0293744000", u"AU", u"+61 2 9374 4000"), - PhoneNumberFormatCase(u"293744000", u"AU", u"+61 2 9374 4000"), + PhoneNumberFormatCase("+61293744000", "AU", "+61 2 9374 4000"), + PhoneNumberFormatCase("61293744000", "AU", "+61 2 9374 4000"), + PhoneNumberFormatCase("0293744000", "AU", "+61 2 9374 4000"), + PhoneNumberFormatCase("293744000", "AU", "+61 2 9374 4000"), ////////////////////////// // AU phone in US. ////////////////////////// // An AU phone with the country code is correctly formatted as an AU // number. - PhoneNumberFormatCase(u"+61 2 9374 4000", u"US", u"+61 2 9374 4000"), - PhoneNumberFormatCase(u"61 2 9374 4000", u"US", u"+61 2 9374 4000"), + PhoneNumberFormatCase("+61 2 9374 4000", "US", "+61 2 9374 4000"), + PhoneNumberFormatCase("61 2 9374 4000", "US", "+61 2 9374 4000"), // Without a country code, the phone is formatted for the profile's // country. // This local AU number is associated with US profile, the number is // not a valid US number, therefore formatting will just return what // user entered. - PhoneNumberFormatCase(u"02 9374 4000", u"US", u"0293744000"), + PhoneNumberFormatCase("02 9374 4000", "US", "0293744000"), // This local GR(Greece) number is formatted as an US number, if it's // valid US number. - PhoneNumberFormatCase(u"22 6800 0090", u"US", u"+1 226-800-0090"), + PhoneNumberFormatCase("22 6800 0090", "US", "+1 226-800-0090"), ////////////////////////// // MX phone in MX. ////////////////////////// // Formatted phone numbers. - PhoneNumberFormatCase(u"+52 55 5342 8400", u"MX", u"+52 55 5342 8400"), - PhoneNumberFormatCase(u"52 55 5342 8400", u"MX", u"+52 55 5342 8400"), - PhoneNumberFormatCase(u"55 5342 8400", u"MX", u"+52 55 5342 8400"), + PhoneNumberFormatCase("+52 55 5342 8400", "MX", "+52 55 5342 8400"), + PhoneNumberFormatCase("52 55 5342 8400", "MX", "+52 55 5342 8400"), + PhoneNumberFormatCase("55 5342 8400", "MX", "+52 55 5342 8400"), // Raw phone numbers. - PhoneNumberFormatCase(u"+525553428400", u"MX", u"+52 55 5342 8400"), - PhoneNumberFormatCase(u"525553428400", u"MX", u"+52 55 5342 8400"), - PhoneNumberFormatCase(u"5553428400", u"MX", u"+52 55 5342 8400"), + PhoneNumberFormatCase("+525553428400", "MX", "+52 55 5342 8400"), + PhoneNumberFormatCase("525553428400", "MX", "+52 55 5342 8400"), + PhoneNumberFormatCase("5553428400", "MX", "+52 55 5342 8400"), ////////////////////////// // MX phone in US. ////////////////////////// // A MX phone with the country code is correctly formatted as a MX // number. - PhoneNumberFormatCase(u"+52 55 5342 8400", u"US", u"+52 55 5342 8400"), - PhoneNumberFormatCase(u"52 55 5342 8400", u"US", u"+52 55 5342 8400"), + PhoneNumberFormatCase("+52 55 5342 8400", "US", "+52 55 5342 8400"), + PhoneNumberFormatCase("52 55 5342 8400", "US", "+52 55 5342 8400"), // This number is not a valid US number, we won't try to format. - PhoneNumberFormatCase(u"55 5342 8400", u"US", u"5553428400"))); + PhoneNumberFormatCase("55 5342 8400", "US", "5553428400"))); INSTANTIATE_TEST_SUITE_P( GetFormattedPhoneNumberForDisplay_EdgeCases, @@ -443,40 +461,31 @@ // No country. ////////////////////////// // Fallback to locale if no country is set. - PhoneNumberFormatCase(u"52 55 5342 8400", - u"", - u"+52 55 5342 8400", + PhoneNumberFormatCase("52 55 5342 8400", + "", + "+52 55 5342 8400", "es_MX"), - PhoneNumberFormatCase(u"55 5342 8400", - u"", - u"+52 55 5342 8400", - "es_MX"), - PhoneNumberFormatCase(u"61 2 9374 4000", - u"", - u"+61 2 9374 4000", - "en_AU"), - PhoneNumberFormatCase(u"02 9374 4000", - u"", - u"+61 2 9374 4000", - "en_AU"), + PhoneNumberFormatCase("55 5342 8400", "", "+52 55 5342 8400", "es_MX"), + PhoneNumberFormatCase("61 2 9374 4000", "", "+61 2 9374 4000", "en_AU"), + PhoneNumberFormatCase("02 9374 4000", "", "+61 2 9374 4000", "en_AU"), // Numbers in local format yet are invalid with user locale, user might // be trying to enter a foreign number, calling formatting will just // return what the user entered. - PhoneNumberFormatCase(u"55 5342 8400", u"", u"5553428400", "en_US"), - PhoneNumberFormatCase(u"55 5342 8400", u"", u"5553428400"), - PhoneNumberFormatCase(u"226 123 1234", u"", u"2261231234", "en_US"), - PhoneNumberFormatCase(u"293744000", u"", u"293744000"), - PhoneNumberFormatCase(u"02 9374 4000", u"", u"0293744000"), + PhoneNumberFormatCase("55 5342 8400", "", "5553428400", "en_US"), + PhoneNumberFormatCase("55 5342 8400", "", "5553428400"), + PhoneNumberFormatCase("226 123 1234", "", "2261231234", "en_US"), + PhoneNumberFormatCase("293744000", "", "293744000"), + PhoneNumberFormatCase("02 9374 4000", "", "0293744000"), ////////////////////////// // No country or locale. ////////////////////////// // Format according to the country code. - PhoneNumberFormatCase(u"61 2 9374 4000", u"", u"+61 2 9374 4000"), - PhoneNumberFormatCase(u"52 55 5342 8400", u"", u"+52 55 5342 8400"), - PhoneNumberFormatCase(u"1 415 555 5555", u"", u"+1 415-555-5555"), + PhoneNumberFormatCase("61 2 9374 4000", "", "+61 2 9374 4000"), + PhoneNumberFormatCase("52 55 5342 8400", "", "+52 55 5342 8400"), + PhoneNumberFormatCase("1 415 555 5555", "", "+1 415-555-5555"), // If no country code is found, formats for US. - PhoneNumberFormatCase(u"415-555-5555", u"", u"+1 415-555-5555"))); + PhoneNumberFormatCase("415-555-5555", "", "+1 415-555-5555"))); } // namespace autofill
diff --git a/components/autofill/core/browser/payments/credit_card_access_manager.h b/components/autofill/core/browser/payments/credit_card_access_manager.h index 798d406..3e80a26 100644 --- a/components/autofill/core/browser/payments/credit_card_access_manager.h +++ b/components/autofill/core/browser/payments/credit_card_access_manager.h
@@ -269,7 +269,7 @@ // Timestamp used for user-perceived latency metrics. base::Optional<base::TimeTicks> - card_selected_without_unmask_details_timestamp_ = base::nullopt; + card_selected_without_unmask_details_timestamp_; // Meant for histograms recorded in FullCardRequest. base::TimeTicks form_parsed_timestamp_;
diff --git a/components/autofill/core/browser/payments/credit_card_access_manager_unittest.cc b/components/autofill/core/browser/payments/credit_card_access_manager_unittest.cc index 890cfee..96ab3fdb 100644 --- a/components/autofill/core/browser/payments/credit_card_access_manager_unittest.cc +++ b/components/autofill/core/browser/payments/credit_card_access_manager_unittest.cc
@@ -82,10 +82,10 @@ const char kTestGUID[] = "00000000-0000-0000-0000-000000000001"; const char kTestNumber[] = "4234567890123456"; // Visa const char16_t kTestNumber16[] = u"4234567890123456"; +const char kTestCvc[] = "123"; const char16_t kTestCvc16[] = u"123"; #if !defined(OS_IOS) -const char kTestCvc[] = "123"; // Base64 encoding of "This is a test challenge". constexpr char kTestChallenge[] = "VGhpcyBpcyBhIHRlc3QgY2hhbGxlbmdl"; // Base64 encoding of "This is a test Credential ID". @@ -1844,8 +1844,8 @@ CreateServerCard(kTestGUID, kTestNumber, /*masked=*/false); CreditCard* unmasked_card = credit_card_access_manager_->GetCreditCard(kTestGUID); - credit_card_access_manager_->CacheUnmaskedCardInfo(*unmasked_card, - kTestCvc16); + credit_card_access_manager_->CacheUnmaskedCardInfo( + *unmasked_card, base::UTF8ToUTF16(kTestCvc)); CreateServerCard(kTestGUID, kTestNumber, /*masked=*/true); CreditCard* masked_card =
diff --git a/components/autofill/core/browser/payments/credit_card_cvc_authenticator.h b/components/autofill/core/browser/payments/credit_card_cvc_authenticator.h index 7d9dd8b..3bffe561 100644 --- a/components/autofill/core/browser/payments/credit_card_cvc_authenticator.h +++ b/components/autofill/core/browser/payments/credit_card_cvc_authenticator.h
@@ -55,8 +55,8 @@ bool did_succeed = false; const CreditCard* card = nullptr; std::u16string cvc = std::u16string(); - base::Optional<base::Value> creation_options = base::nullopt; - base::Optional<base::Value> request_options = base::nullopt; + base::Optional<base::Value> creation_options; + base::Optional<base::Value> request_options; std::string card_authorization_token = std::string(); }; class Requester {
diff --git a/components/autofill/core/browser/personal_data_manager_unittest.cc b/components/autofill/core/browser/personal_data_manager_unittest.cc index a10d33c..10e3952 100644 --- a/components/autofill/core/browser/personal_data_manager_unittest.cc +++ b/components/autofill/core/browser/personal_data_manager_unittest.cc
@@ -78,7 +78,6 @@ namespace { const char kPrimaryAccountEmail[] = "syncuser@example.com"; -const char16_t kPrimaryAccountEmail16[] = u"syncuser@example.com"; const char kSyncTransportAccountEmail[] = "transport@example.com"; enum UserMode { USER_MODE_NORMAL, USER_MODE_INCOGNITO }; @@ -3976,7 +3975,7 @@ // merge logic works correctly. typedef struct { autofill::ServerFieldType field_type; - std::u16string field_value; + std::string field_value; } ProfileField; typedef std::vector<ProfileField> ProfileFields; @@ -4037,7 +4036,7 @@ // Apply changes to the original profile (if applicable). for (ProfileField change : test_case.changes_to_original) { original_profile.SetRawInfoWithVerificationStatus( - change.field_type, change.field_value, + change.field_type, base::UTF8ToUTF16(change.field_value), structured_address::VerificationStatus::kObserved); } @@ -4053,7 +4052,7 @@ // Apply changes to the second profile (if applicable). for (ProfileField change : test_case.changes_to_new) { profile2.SetRawInfoWithVerificationStatus( - change.field_type, change.field_value, + change.field_type, base::UTF8ToUTF16(change.field_value), structured_address::VerificationStatus::kObserved); } @@ -4086,7 +4085,7 @@ // Make sure the new information was merged correctly. for (ProfileField changed_field : test_case.changed_field_values) { - EXPECT_EQ(changed_field.field_value, + EXPECT_EQ(base::UTF8ToUTF16(changed_field.field_value), saved_profiles.front()->GetRawInfo(changed_field.field_type)); } // Verify that the merged profile's use count, use date and modification @@ -4122,66 +4121,66 @@ // Test that saving an identical profile except for the name results // in two profiles being saved. SaveImportedProfileTestCase{ProfileFields(), - {{NAME_FIRST, u"Marionette"}}}, + {{NAME_FIRST, "Marionette"}}}, // Test that saving an identical profile except with the middle name // initial instead of the full middle name results in the profiles // getting merged and the full middle name being kept. SaveImportedProfileTestCase{ ProfileFields(), - {{NAME_MIDDLE, u"M"}}, - {{NAME_MIDDLE, u"Mitchell"}, - {NAME_FULL, u"Marion Mitchell Morrison"}}}, + {{NAME_MIDDLE, "M"}}, + {{NAME_MIDDLE, "Mitchell"}, + {NAME_FULL, "Marion Mitchell Morrison"}}}, // Test that saving an identical profile except with the full middle // name instead of the middle name initial results in the profiles // getting merged and the full middle name replacing the initial. - SaveImportedProfileTestCase{{{NAME_MIDDLE, u"M"}}, - {{NAME_MIDDLE, u"Mitchell"}}, - {{NAME_MIDDLE, u"Mitchell"}}}, + SaveImportedProfileTestCase{{{NAME_MIDDLE, "M"}}, + {{NAME_MIDDLE, "Mitchell"}}, + {{NAME_MIDDLE, "Mitchell"}}}, // Test that saving an identical profile except with no middle name // results in the profiles getting merged and the full middle name // being kept. SaveImportedProfileTestCase{ProfileFields(), - {{NAME_MIDDLE, u""}}, - {{NAME_MIDDLE, u"Mitchell"}}}, + {{NAME_MIDDLE, ""}}, + {{NAME_MIDDLE, "Mitchell"}}}, // Test that saving an identical profile except with a middle name // initial results in the profiles getting merged and the middle // name initial being saved. - SaveImportedProfileTestCase{{{NAME_MIDDLE, u""}}, - {{NAME_MIDDLE, u"M"}}, - {{NAME_MIDDLE, u"M"}}}, + SaveImportedProfileTestCase{{{NAME_MIDDLE, ""}}, + {{NAME_MIDDLE, "M"}}, + {{NAME_MIDDLE, "M"}}}, // Test that saving an identical profile except with a middle name // results in the profiles getting merged and the full middle name // being saved. - SaveImportedProfileTestCase{{{NAME_MIDDLE, u""}}, - {{NAME_MIDDLE, u"Mitchell"}}, - {{NAME_MIDDLE, u"Mitchell"}}}, + SaveImportedProfileTestCase{{{NAME_MIDDLE, ""}}, + {{NAME_MIDDLE, "Mitchell"}}, + {{NAME_MIDDLE, "Mitchell"}}}, // Test that saving a identical profile except with the full name // set instead of the name parts results in the two profiles being // merged and all the name parts kept and the full name being added. SaveImportedProfileTestCase{ { - {NAME_FIRST, u"Marion"}, - {NAME_MIDDLE, u"Mitchell"}, - {NAME_LAST, u"Morrison"}, - {NAME_FULL, u""}, + {NAME_FIRST, "Marion"}, + {NAME_MIDDLE, "Mitchell"}, + {NAME_LAST, "Morrison"}, + {NAME_FULL, ""}, }, { - {NAME_FIRST, u""}, - {NAME_MIDDLE, u""}, - {NAME_LAST, u""}, - {NAME_FULL, u"Marion Mitchell Morrison"}, + {NAME_FIRST, ""}, + {NAME_MIDDLE, ""}, + {NAME_LAST, ""}, + {NAME_FULL, "Marion Mitchell Morrison"}, }, { - {NAME_FIRST, u"Marion"}, - {NAME_MIDDLE, u"Mitchell"}, - {NAME_LAST, u"Morrison"}, - {NAME_FULL, u"Marion Mitchell Morrison"}, + {NAME_FIRST, "Marion"}, + {NAME_MIDDLE, "Mitchell"}, + {NAME_LAST, "Morrison"}, + {NAME_FULL, "Marion Mitchell Morrison"}, }, }, @@ -4191,22 +4190,22 @@ // added. SaveImportedProfileTestCase{ { - {NAME_FIRST, u""}, - {NAME_MIDDLE, u""}, - {NAME_LAST, u""}, - {NAME_FULL, u"Marion Mitchell Morrison"}, + {NAME_FIRST, ""}, + {NAME_MIDDLE, ""}, + {NAME_LAST, ""}, + {NAME_FULL, "Marion Mitchell Morrison"}, }, { - {NAME_FIRST, u"Marion"}, - {NAME_MIDDLE, u"Mitchell"}, - {NAME_LAST, u"Morrison"}, - {NAME_FULL, u""}, + {NAME_FIRST, "Marion"}, + {NAME_MIDDLE, "Mitchell"}, + {NAME_LAST, "Morrison"}, + {NAME_FULL, ""}, }, { - {NAME_FIRST, u"Marion"}, - {NAME_MIDDLE, u"Mitchell"}, - {NAME_LAST, u"Morrison"}, - {NAME_FULL, u"Marion Mitchell Morrison"}, + {NAME_FIRST, "Marion"}, + {NAME_MIDDLE, "Mitchell"}, + {NAME_LAST, "Morrison"}, + {NAME_FULL, "Marion Mitchell Morrison"}, }, }, @@ -4215,16 +4214,16 @@ // names are different. SaveImportedProfileTestCase{ { - {NAME_FIRST, u"Marion"}, - {NAME_MIDDLE, u"Mitchell"}, - {NAME_LAST, u"Morrison"}, - {NAME_FULL, u""}, + {NAME_FIRST, "Marion"}, + {NAME_MIDDLE, "Mitchell"}, + {NAME_LAST, "Morrison"}, + {NAME_FULL, ""}, }, { - {NAME_FIRST, u""}, - {NAME_MIDDLE, u""}, - {NAME_LAST, u""}, - {NAME_FULL, u"John Thompson Smith"}, + {NAME_FIRST, ""}, + {NAME_MIDDLE, ""}, + {NAME_LAST, ""}, + {NAME_FULL, "John Thompson Smith"}, }, }, @@ -4233,16 +4232,16 @@ // names are different. SaveImportedProfileTestCase{ { - {NAME_FIRST, u""}, - {NAME_MIDDLE, u""}, - {NAME_LAST, u""}, - {NAME_FULL, u"John Thompson Smith"}, + {NAME_FIRST, ""}, + {NAME_MIDDLE, ""}, + {NAME_LAST, ""}, + {NAME_FULL, "John Thompson Smith"}, }, { - {NAME_FIRST, u"Marion"}, - {NAME_MIDDLE, u"Mitchell"}, - {NAME_LAST, u"Morrison"}, - {NAME_FULL, u""}, + {NAME_FIRST, "Marion"}, + {NAME_MIDDLE, "Mitchell"}, + {NAME_LAST, "Morrison"}, + {NAME_FULL, ""}, }, }, @@ -4250,147 +4249,146 @@ // address line results in two profiles being saved. SaveImportedProfileTestCase{ ProfileFields(), - {{ADDRESS_HOME_LINE1, u"123 Aquarium St."}}}, + {{ADDRESS_HOME_LINE1, "123 Aquarium St."}}}, // Test that saving an identical profile except for the second // address line results in two profiles being saved. SaveImportedProfileTestCase{ProfileFields(), - {{ADDRESS_HOME_LINE2, u"unit 7"}}}, + {{ADDRESS_HOME_LINE2, "unit 7"}}}, // Tests that saving an identical profile that has a new piece of // information (company name) results in a merge and that the // original empty value gets overwritten by the new information. - SaveImportedProfileTestCase{{{COMPANY_NAME, u""}}, + SaveImportedProfileTestCase{{{COMPANY_NAME, ""}}, ProfileFields(), - {{COMPANY_NAME, u"Fox"}}}, + {{COMPANY_NAME, "Fox"}}}, // Tests that saving an identical profile except a loss of // information results in a merge but the original value is not // overwritten (no information loss). SaveImportedProfileTestCase{ProfileFields(), - {{COMPANY_NAME, u""}}, - {{COMPANY_NAME, u"Fox"}}}, + {{COMPANY_NAME, ""}}, + {{COMPANY_NAME, "Fox"}}}, // Tests that saving an identical profile except a slightly // different postal code results in a merge with the new value kept. - SaveImportedProfileTestCase{{{ADDRESS_HOME_ZIP, u"R2C 0A1"}}, - {{ADDRESS_HOME_ZIP, u"R2C0A1"}}, - {{ADDRESS_HOME_ZIP, u"R2C0A1"}}}, - SaveImportedProfileTestCase{{{ADDRESS_HOME_ZIP, u"R2C0A1"}}, - {{ADDRESS_HOME_ZIP, u"R2C 0A1"}}, - {{ADDRESS_HOME_ZIP, u"R2C 0A1"}}}, - SaveImportedProfileTestCase{{{ADDRESS_HOME_ZIP, u"r2c 0a1"}}, - {{ADDRESS_HOME_ZIP, u"R2C0A1"}}, - {{ADDRESS_HOME_ZIP, u"R2C0A1"}}}, + SaveImportedProfileTestCase{{{ADDRESS_HOME_ZIP, "R2C 0A1"}}, + {{ADDRESS_HOME_ZIP, "R2C0A1"}}, + {{ADDRESS_HOME_ZIP, "R2C0A1"}}}, + SaveImportedProfileTestCase{{{ADDRESS_HOME_ZIP, "R2C0A1"}}, + {{ADDRESS_HOME_ZIP, "R2C 0A1"}}, + {{ADDRESS_HOME_ZIP, "R2C 0A1"}}}, + SaveImportedProfileTestCase{{{ADDRESS_HOME_ZIP, "r2c 0a1"}}, + {{ADDRESS_HOME_ZIP, "R2C0A1"}}, + {{ADDRESS_HOME_ZIP, "R2C0A1"}}}, // Tests that saving an identical profile plus a new piece of // information on the address line 2 results in a merge and that the // original empty value gets overwritten by the new information. - SaveImportedProfileTestCase{{{ADDRESS_HOME_LINE2, u""}}, + SaveImportedProfileTestCase{{{ADDRESS_HOME_LINE2, ""}}, ProfileFields(), - {{ADDRESS_HOME_LINE2, u"unit 5"}}}, + {{ADDRESS_HOME_LINE2, "unit 5"}}}, // Tests that saving an identical profile except a loss of // information on the address line 2 results in a merge but that the // original value gets not overwritten (no information loss). SaveImportedProfileTestCase{ProfileFields(), - {{ADDRESS_HOME_LINE2, u""}}, - {{ADDRESS_HOME_LINE2, u"unit 5"}}}, + {{ADDRESS_HOME_LINE2, ""}}, + {{ADDRESS_HOME_LINE2, "unit 5"}}}, // Tests that saving an identical except with more punctuation in // the fist address line, while the second is empty, results in a // merge and that the original address gets overwritten. - SaveImportedProfileTestCase{ - {{ADDRESS_HOME_LINE2, u""}}, - {{ADDRESS_HOME_LINE2, u""}, - {ADDRESS_HOME_LINE1, u"123, Zoo St."}}, - {{ADDRESS_HOME_LINE1, u"123, Zoo St."}}}, + SaveImportedProfileTestCase{{{ADDRESS_HOME_LINE2, ""}}, + {{ADDRESS_HOME_LINE2, ""}, + {ADDRESS_HOME_LINE1, "123, Zoo St."}}, + {{ADDRESS_HOME_LINE1, "123, Zoo St."}}}, // Tests that saving an identical profile except with less // punctuation in the fist address line, while the second is empty, // results in a merge and that the longer address is retained. - SaveImportedProfileTestCase{{{ADDRESS_HOME_LINE2, u""}, - {ADDRESS_HOME_LINE1, u"123, Zoo St."}}, - {{ADDRESS_HOME_LINE2, u""}}, - {{ADDRESS_HOME_LINE1, u"123 Zoo St"}}}, + SaveImportedProfileTestCase{{{ADDRESS_HOME_LINE2, ""}, + {ADDRESS_HOME_LINE1, "123, Zoo St."}}, + {{ADDRESS_HOME_LINE2, ""}}, + {{ADDRESS_HOME_LINE1, "123 Zoo St"}}}, // Tests that saving an identical profile except additional // punctuation in the two address lines results in a merge and that // the newer address is retained. SaveImportedProfileTestCase{ProfileFields(), - {{ADDRESS_HOME_LINE1, u"123, Zoo St."}, - {ADDRESS_HOME_LINE2, u"unit. 5"}}, - {{ADDRESS_HOME_LINE1, u"123, Zoo St."}, - {ADDRESS_HOME_LINE2, u"unit. 5"}}}, + {{ADDRESS_HOME_LINE1, "123, Zoo St."}, + {ADDRESS_HOME_LINE2, "unit. 5"}}, + {{ADDRESS_HOME_LINE1, "123, Zoo St."}, + {ADDRESS_HOME_LINE2, "unit. 5"}}}, // Tests that saving an identical profile except less punctuation in // the two address lines results in a merge and that the newer // address is retained. - SaveImportedProfileTestCase{{{ADDRESS_HOME_LINE1, u"123, Zoo St."}, - {ADDRESS_HOME_LINE2, u"unit. 5"}}, + SaveImportedProfileTestCase{{{ADDRESS_HOME_LINE1, "123, Zoo St."}, + {ADDRESS_HOME_LINE2, "unit. 5"}}, ProfileFields(), - {{ADDRESS_HOME_LINE1, u"123 Zoo St"}, - {ADDRESS_HOME_LINE2, u"unit 5"}}}, + {{ADDRESS_HOME_LINE1, "123 Zoo St"}, + {ADDRESS_HOME_LINE2, "unit 5"}}}, // Tests that saving an identical profile with accented characters // in the two address lines results in a merge and that the newer // address is retained. SaveImportedProfileTestCase{ProfileFields(), - {{ADDRESS_HOME_LINE1, u"123 Zôö St"}, - {ADDRESS_HOME_LINE2, u"üñìt 5"}}, - {{ADDRESS_HOME_LINE1, u"123 Zôö St"}, - {ADDRESS_HOME_LINE2, u"üñìt 5"}}}, + {{ADDRESS_HOME_LINE1, "123 Zôö St"}, + {ADDRESS_HOME_LINE2, "üñìt 5"}}, + {{ADDRESS_HOME_LINE1, "123 Zôö St"}, + {ADDRESS_HOME_LINE2, "üñìt 5"}}}, // Tests that saving an identical profile without accented // characters in the two address lines results in a merge and that // the newer address is retained. - SaveImportedProfileTestCase{{{ADDRESS_HOME_LINE1, u"123 Zôö St"}, - {ADDRESS_HOME_LINE2, u"üñìt 5"}}, + SaveImportedProfileTestCase{{{ADDRESS_HOME_LINE1, "123 Zôö St"}, + {ADDRESS_HOME_LINE2, "üñìt 5"}}, ProfileFields(), - {{ADDRESS_HOME_LINE1, u"123 Zoo St"}, - {ADDRESS_HOME_LINE2, u"unit 5"}}}, + {{ADDRESS_HOME_LINE1, "123 Zoo St"}, + {ADDRESS_HOME_LINE2, "unit 5"}}}, // Tests that saving an identical profile except that the address // line 1 is in the address line 2 results in a merge and that the // multi-lne address is retained. SaveImportedProfileTestCase{ ProfileFields(), - {{ADDRESS_HOME_LINE1, u"123 Zoo St, unit 5"}, - {ADDRESS_HOME_LINE2, u""}}, - {{ADDRESS_HOME_LINE1, u"123 Zoo St"}, - {ADDRESS_HOME_LINE2, u"unit 5"}}}, + {{ADDRESS_HOME_LINE1, "123 Zoo St, unit 5"}, + {ADDRESS_HOME_LINE2, ""}}, + {{ADDRESS_HOME_LINE1, "123 Zoo St"}, + {ADDRESS_HOME_LINE2, "unit 5"}}}, // Tests that saving an identical profile except that the address // line 2 contains part of the old address line 1 results in a merge // and that the original address lines of the reference profile get // overwritten. SaveImportedProfileTestCase{ - {{ADDRESS_HOME_LINE1, u"123 Zoo St, unit 5"}, - {ADDRESS_HOME_LINE2, u""}}, + {{ADDRESS_HOME_LINE1, "123 Zoo St, unit 5"}, + {ADDRESS_HOME_LINE2, ""}}, ProfileFields(), - {{ADDRESS_HOME_LINE1, u"123 Zoo St"}, - {ADDRESS_HOME_LINE2, u"unit 5"}}}, + {{ADDRESS_HOME_LINE1, "123 Zoo St"}, + {ADDRESS_HOME_LINE2, "unit 5"}}}, // Tests that saving an identical profile except that the state is // the abbreviation instead of the full form results in a merge and // that the original state gets overwritten. - SaveImportedProfileTestCase{{{ADDRESS_HOME_STATE, u"California"}}, + SaveImportedProfileTestCase{{{ADDRESS_HOME_STATE, "California"}}, ProfileFields(), - {{ADDRESS_HOME_STATE, u"CA"}}}, + {{ADDRESS_HOME_STATE, "CA"}}}, // Tests that saving an identical profile except that the state is // the full form instead of the abbreviation results in a merge and // that the abbreviated state is retained. SaveImportedProfileTestCase{ProfileFields(), - {{ADDRESS_HOME_STATE, u"California"}}, - {{ADDRESS_HOME_STATE, u"CA"}}}, + {{ADDRESS_HOME_STATE, "California"}}, + {{ADDRESS_HOME_STATE, "CA"}}}, // Tests that saving and identical profile except that the company // name has different punctuation and case results in a merge and // that the syntax of the new profile replaces the old one. - SaveImportedProfileTestCase{{{COMPANY_NAME, u"Stark inc"}}, - {{COMPANY_NAME, u"Stark Inc."}}, - {{COMPANY_NAME, u"Stark Inc."}}}))); + SaveImportedProfileTestCase{{{COMPANY_NAME, "Stark inc"}}, + {{COMPANY_NAME, "Stark Inc."}}, + {{COMPANY_NAME, "Stark Inc."}}}))); // Tests that MergeProfile tries to merge the imported profile into the // existing profile in decreasing order of frecency. @@ -5669,7 +5667,8 @@ // Make sure that the added address has the email address of the currently // signed-in user. - EXPECT_EQ(kPrimaryAccountEmail16, profiles[0]->GetRawInfo(EMAIL_ADDRESS)); + EXPECT_EQ(base::UTF8ToUTF16(kPrimaryAccountEmail), + profiles[0]->GetRawInfo(EMAIL_ADDRESS)); } // Tests that the converted wallet address is merged into an existing local @@ -7840,16 +7839,16 @@ } struct ShareNicknameTestParam { - std::u16string local_nickname; - std::u16string server_nickname; - std::u16string expected_nickname; + std::string local_nickname; + std::string server_nickname; + std::string expected_nickname; }; const ShareNicknameTestParam kShareNicknameTestParam[] = { - {u"", u"", u""}, - {u"", u"server nickname", u"server nickname"}, - {u"local nickname", u"", u"local nickname"}, - {u"local nickname", u"server nickname", u"local nickname"}, + {"", "", ""}, + {"", "server nickname", "server nickname"}, + {"local nickname", "", "local nickname"}, + {"local nickname", "server nickname", "local nickname"}, }; class PersonalDataManagerTestForSharingNickname @@ -7857,9 +7856,9 @@ public testing::WithParamInterface<ShareNicknameTestParam> { public: PersonalDataManagerTestForSharingNickname() - : local_nickname_(GetParam().local_nickname), - server_nickname_(GetParam().server_nickname), - expected_nickname_(GetParam().expected_nickname) {} + : local_nickname_(base::UTF8ToUTF16(GetParam().local_nickname)), + server_nickname_(base::UTF8ToUTF16(GetParam().server_nickname)), + expected_nickname_(base::UTF8ToUTF16(GetParam().expected_nickname)) {} CreditCard GetLocalCard() { CreditCard local_card("287151C8-6AB1-487C-9095-28E80BE5DA15",
diff --git a/components/autofill/core/browser/test_autofill_client.cc b/components/autofill/core/browser/test_autofill_client.cc index 107100b5..77d9a2d 100644 --- a/components/autofill/core/browser/test_autofill_client.cc +++ b/components/autofill/core/browser/test_autofill_client.cc
@@ -223,6 +223,7 @@ void TestAutofillClient::ConfirmSaveAddressProfile( const AutofillProfile& profile, const AutofillProfile* original_profile, + SaveAddressProfilePromptOptions options, AddressProfileSavePromptCallback callback) {} bool TestAutofillClient::HasCreditCardScanFeature() {
diff --git a/components/autofill/core/browser/test_autofill_client.h b/components/autofill/core/browser/test_autofill_client.h index 8bd76c4..73d5499 100644 --- a/components/autofill/core/browser/test_autofill_client.h +++ b/components/autofill/core/browser/test_autofill_client.h
@@ -125,6 +125,7 @@ void ConfirmSaveAddressProfile( const AutofillProfile& profile, const AutofillProfile* original_profile, + SaveAddressProfilePromptOptions options, AddressProfileSavePromptCallback callback) override; bool HasCreditCardScanFeature() override; void ScanCreditCard(CreditCardScanCallback callback) override;
diff --git a/components/autofill/core/browser/ui/address_form_label_formatter_unittest.cc b/components/autofill/core/browser/ui/address_form_label_formatter_unittest.cc index 04f396f..c77fd7f 100644 --- a/components/autofill/core/browser/ui/address_form_label_formatter_unittest.cc +++ b/components/autofill/core/browser/ui/address_form_label_formatter_unittest.cc
@@ -175,8 +175,9 @@ LabelFormatter::Create(profiles, "pt-BR", NAME_FIRST, GetFieldTypes()); EXPECT_THAT(formatter->GetLabels(), - ElementsAre(u"Av. Pedro Álvares Cabral, 1301, Vila Mariana, São " - u"Paulo-SP, 04094-050")); + ElementsAre(base::UTF8ToUTF16( + "Av. Pedro Álvares Cabral, 1301, Vila Mariana, São " + "Paulo-SP, 04094-050"))); } TEST(AddressFormLabelFormatterTest, GetLabelsForFormWithoutName) {
diff --git a/components/consent_auditor/consent_auditor_impl_unittest.cc b/components/consent_auditor/consent_auditor_impl_unittest.cc index 566b920..b7e303a6 100644 --- a/components/consent_auditor/consent_auditor_impl_unittest.cc +++ b/components/consent_auditor/consent_auditor_impl_unittest.cc
@@ -197,7 +197,7 @@ EXPECT_EQ(kCurrentAppLocale, locale); // They are two separate records; the latter did not overwrite the former. - EXPECT_EQ(2u, consents->size()); + EXPECT_EQ(2u, consents->DictSize()); EXPECT_TRUE( consents->FindKeyOfType("feature1", base::Value::Type::DICTIONARY)); @@ -224,7 +224,7 @@ EXPECT_EQ(kFeature2NewAppLocale, locale); // We still have two records. - EXPECT_EQ(2u, consents->size()); + EXPECT_EQ(2u, consents->DictSize()); } TEST_F(ConsentAuditorImplTest, RecordGaiaConsentAsUserConsent) {
diff --git a/components/enterprise/browser/reporting/common_pref_names.cc b/components/enterprise/browser/reporting/common_pref_names.cc index 8b15ce9..cc93b96b 100644 --- a/components/enterprise/browser/reporting/common_pref_names.cc +++ b/components/enterprise/browser/reporting/common_pref_names.cc
@@ -17,4 +17,8 @@ const char kLastUploadTimestamp[] = "enterprise_reporting.last_upload_timestamp"; +// The timestamp of the last enterprise report upload is succeeded. +const char kLastUploadSucceededTimestamp[] = + "enterprise_reporting.last_upload_succeeded_timestamp"; + } // namespace enterprise_reporting
diff --git a/components/enterprise/browser/reporting/common_pref_names.h b/components/enterprise/browser/reporting/common_pref_names.h index c5d5e66..39b968a 100644 --- a/components/enterprise/browser/reporting/common_pref_names.h +++ b/components/enterprise/browser/reporting/common_pref_names.h
@@ -15,6 +15,8 @@ extern const char kLastUploadTimestamp[]; +extern const char kLastUploadSucceededTimestamp[]; + } // namespace enterprise_reporting #endif // COMPONENTS_ENTERPRISE_BROWSER_REPORTING_COMMON_PREF_NAMES_H_
diff --git a/components/enterprise/browser/reporting/report_scheduler.cc b/components/enterprise/browser/reporting/report_scheduler.cc index 214b27e..44775461 100644 --- a/components/enterprise/browser/reporting/report_scheduler.cc +++ b/components/enterprise/browser/reporting/report_scheduler.cc
@@ -254,6 +254,9 @@ if (IsExtensionRequestUploaded(active_trigger_)) delegate_->OnExtensionRequestUploaded(); + + delegate_->GetLocalState()->SetTime(kLastUploadSucceededTimestamp, + base::Time::Now()); FALLTHROUGH; case ReportUploader::kTransientError: // Stop retrying and schedule the next report to avoid stale report.
diff --git a/components/feature_engagement/public/android/java/src/org/chromium/components/feature_engagement/FeatureConstants.java b/components/feature_engagement/public/android/java/src/org/chromium/components/feature_engagement/FeatureConstants.java index d9233b68..546c16b 100644 --- a/components/feature_engagement/public/android/java/src/org/chromium/components/feature_engagement/FeatureConstants.java +++ b/components/feature_engagement/public/android/java/src/org/chromium/components/feature_engagement/FeatureConstants.java
@@ -234,7 +234,7 @@ /** * An IPH feature to inform users that installing a PWA is an option. */ - String PWA_INSTALL_AVAILABLE_FEATURE = "IPH_PwaInstallAvailable"; + String PWA_INSTALL_AVAILABLE_FEATURE = "IPH_PwaInstallAvailableFeature"; /** * An IPH feature to inform about changing permissions in PageInfo.
diff --git a/components/feature_engagement/public/feature_constants.cc b/components/feature_engagement/public/feature_constants.cc index 36f9686..6ca49a40 100644 --- a/components/feature_engagement/public/feature_constants.cc +++ b/components/feature_engagement/public/feature_constants.cc
@@ -154,7 +154,7 @@ const base::Feature kIPHChromeReengagementNotification3Feature{ "IPH_ChromeReengagementNotification3", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kIPHPwaInstallAvailableFeature{ - "IPH_PwaInstallAvailable", base::FEATURE_DISABLED_BY_DEFAULT}; + "IPH_PwaInstallAvailableFeature", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kIPHShareScreenshotFeature{ "IPH_ShareScreenshot", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kIPHWebFeedFollowFeature{"IPH_WebFeedFollow",
diff --git a/components/flags_ui/pref_service_flags_storage.cc b/components/flags_ui/pref_service_flags_storage.cc index f73fb1c6..007ed343 100644 --- a/components/flags_ui/pref_service_flags_storage.cc +++ b/components/flags_ui/pref_service_flags_storage.cc
@@ -25,10 +25,9 @@ const base::ListValue* enabled_experiments = prefs_->GetList(prefs::kAboutFlagsEntries); std::set<std::string> flags; - for (auto it = enabled_experiments->begin(); it != enabled_experiments->end(); - ++it) { + for (const auto& entry : enabled_experiments->GetList()) { std::string experiment_name; - if (!it->GetAsString(&experiment_name)) { + if (!entry.GetAsString(&experiment_name)) { LOG(WARNING) << "Invalid entry in " << prefs::kAboutFlagsEntries; continue; }
diff --git a/components/history/core/browser/history_backend_unittest.cc b/components/history/core/browser/history_backend_unittest.cc index d519c70d4..3d104ea2 100644 --- a/components/history/core/browser/history_backend_unittest.cc +++ b/components/history/core/browser/history_backend_unittest.cc
@@ -568,13 +568,13 @@ const SimulateNotificationCallback& callback); static const KeywordID kTestKeywordId; - static const char16_t kTestSearchTerm1[]; - static const char16_t kTestSearchTerm2[]; + static const char kTestSearchTerm1[]; + static const char kTestSearchTerm2[]; }; const KeywordID InMemoryHistoryBackendTest::kTestKeywordId = 42; -const char16_t InMemoryHistoryBackendTest::kTestSearchTerm1[] = u"banana"; -const char16_t InMemoryHistoryBackendTest::kTestSearchTerm2[] = u"orange"; +const char InMemoryHistoryBackendTest::kTestSearchTerm1[] = "banana"; +const char InMemoryHistoryBackendTest::kTestSearchTerm2[] = "orange"; // http://crbug.com/114287 #if defined(OS_WIN) @@ -1168,7 +1168,7 @@ // This verifies that a notification is fired. In-depth testing of logic should // be done in HistoryTest.SetTitle. TEST_F(HistoryBackendTest, SetPageTitleFiresNotificationWithCorrectDetails) { - const char16_t kTestUrlTitle[] = u"Google Search"; + const char kTestUrlTitle[] = "Google Search"; ASSERT_TRUE(backend_.get()); @@ -1186,7 +1186,7 @@ backend_->AddPagesWithDetails(rows, history::SOURCE_BROWSED); ClearBroadcastedNotifications(); - backend_->SetPageTitle(row2.url(), kTestUrlTitle); + backend_->SetPageTitle(row2.url(), base::UTF8ToUTF16(kTestUrlTitle)); // Ensure that a notification was fired, and further verify that the IDs in // the notification are set to those that are in effect in the main database. @@ -1197,7 +1197,7 @@ const URLRows& changed_urls = urls_modified_notifications()[0]; ASSERT_EQ(1u, changed_urls.size()); - EXPECT_EQ(kTestUrlTitle, changed_urls[0].title()); + EXPECT_EQ(base::UTF8ToUTF16(kTestUrlTitle), changed_urls[0].title()); EXPECT_EQ(stored_row2.id(), changed_urls[0].id()); } @@ -2901,8 +2901,8 @@ // between them is the type of the notification sent out. void InMemoryHistoryBackendTest::TestAddingAndChangingURLRows( const SimulateNotificationCallback& callback) { - const char16_t kTestTypedURLAlternativeTitle[] = u"Google Search Again"; - const char16_t kTestNonTypedURLAlternativeTitle[] = u"Google News Again"; + const char kTestTypedURLAlternativeTitle[] = "Google Search Again"; + const char kTestNonTypedURLAlternativeTitle[] = "Google News Again"; // Notify the in-memory database that a typed and non-typed URLRow (which were // never before seen by the cache) have been modified. @@ -2919,14 +2919,15 @@ EXPECT_EQ(row1.id(), cached_row1.id()); // Try changing attributes (other than typed_count) for existing URLRows. - row1.set_title(kTestTypedURLAlternativeTitle); - row2.set_title(kTestNonTypedURLAlternativeTitle); + row1.set_title(base::UTF8ToUTF16(kTestTypedURLAlternativeTitle)); + row2.set_title(base::UTF8ToUTF16(kTestNonTypedURLAlternativeTitle)); callback.Run(&row1, &row2, nullptr); // URLRows that are cached by the in-memory database should be updated. EXPECT_NE(0, mem_backend_->db()->GetRowForURL(row1.url(), &cached_row1)); EXPECT_EQ(0, mem_backend_->db()->GetRowForURL(row2.url(), &cached_row2)); - EXPECT_EQ(kTestTypedURLAlternativeTitle, cached_row1.title()); + EXPECT_EQ(base::UTF8ToUTF16(kTestTypedURLAlternativeTitle), + cached_row1.title()); // Now decrease the typed count for the typed URLRow, and increase it for the // previously non-typed URLRow. @@ -2939,7 +2940,8 @@ EXPECT_EQ(0, mem_backend_->db()->GetRowForURL(row1.url(), &cached_row1)); EXPECT_NE(0, mem_backend_->db()->GetRowForURL(row2.url(), &cached_row2)); EXPECT_EQ(row2.id(), cached_row2.id()); - EXPECT_EQ(kTestNonTypedURLAlternativeTitle, cached_row2.title()); + EXPECT_EQ(base::UTF8ToUTF16(kTestNonTypedURLAlternativeTitle), + cached_row2.title()); } TEST_F(InMemoryHistoryBackendTest, OnURLsModified) { @@ -3012,8 +3014,8 @@ TEST_F(InMemoryHistoryBackendTest, SetKeywordSearchTerms) { URLRow row1(CreateTestTypedURL()); URLRow row2(CreateTestNonTypedURL()); - std::u16string term1(kTestSearchTerm1); - std::u16string term2(kTestSearchTerm2); + std::u16string term1(base::UTF8ToUTF16(kTestSearchTerm1)); + std::u16string term2(base::UTF8ToUTF16(kTestSearchTerm2)); PopulateTestURLsAndSearchTerms(&row1, &row2, term1, term2); // Both URLs now have associated search terms, so the in-memory database @@ -3035,8 +3037,8 @@ TEST_F(InMemoryHistoryBackendTest, DeleteKeywordSearchTerms) { URLRow row1(CreateTestTypedURL()); URLRow row2(CreateTestNonTypedURL()); - std::u16string term1(kTestSearchTerm1); - std::u16string term2(kTestSearchTerm2); + std::u16string term1(base::UTF8ToUTF16(kTestSearchTerm1)); + std::u16string term2(base::UTF8ToUTF16(kTestSearchTerm2)); PopulateTestURLsAndSearchTerms(&row1, &row2, term1, term2); // Delete both search terms. This should be reflected in the in-memory DB. @@ -3060,8 +3062,8 @@ TEST_F(InMemoryHistoryBackendTest, DeleteAllSearchTermsForKeyword) { URLRow row1(CreateTestTypedURL()); URLRow row2(CreateTestNonTypedURL()); - std::u16string term1(kTestSearchTerm1); - std::u16string term2(kTestSearchTerm2); + std::u16string term1(base::UTF8ToUTF16(kTestSearchTerm1)); + std::u16string term2(base::UTF8ToUTF16(kTestSearchTerm2)); PopulateTestURLsAndSearchTerms(&row1, &row2, term1, term2); // Delete all corresponding search terms from the in-memory database. @@ -3085,8 +3087,8 @@ TEST_F(InMemoryHistoryBackendTest, OnURLsDeletedWithSearchTerms) { URLRow row1(CreateTestTypedURL()); URLRow row2(CreateTestNonTypedURL()); - std::u16string term1(kTestSearchTerm1); - std::u16string term2(kTestSearchTerm2); + std::u16string term1(base::UTF8ToUTF16(kTestSearchTerm1)); + std::u16string term2(base::UTF8ToUTF16(kTestSearchTerm2)); PopulateTestURLsAndSearchTerms(&row1, &row2, term1, term2); // Notify the in-memory database that the second typed URL has been deleted.
diff --git a/components/ntp_snippets/remote/remote_suggestions_provider_impl_unittest.cc b/components/ntp_snippets/remote/remote_suggestions_provider_impl_unittest.cc index 5b51b432..0837c6e 100644 --- a/components/ntp_snippets/remote/remote_suggestions_provider_impl_unittest.cc +++ b/components/ntp_snippets/remote/remote_suggestions_provider_impl_unittest.cc
@@ -124,7 +124,7 @@ const char kSuggestionUrl2[] = "http://foo.com/bar"; -const char16_t kTestJsonDefaultCategoryTitle[] = u"Some title"; +const char kTestJsonDefaultCategoryTitle[] = "Some title"; const int kOtherCategoryId = 2; const int kUnknownRemoteCategoryId = 1234; @@ -592,7 +592,8 @@ } TEST_F(RemoteSuggestionsProviderImplTest, CategoryTitle) { - const std::u16string test_default_title = kTestJsonDefaultCategoryTitle; + const std::u16string test_default_title = + base::UTF8ToUTF16(kTestJsonDefaultCategoryTitle); // Don't send an initial response -- we want to test what happens without any // server status.
diff --git a/components/ntp_tiles/custom_links_manager_impl_unittest.cc b/components/ntp_tiles/custom_links_manager_impl_unittest.cc index a273d5c..1c36355 100644 --- a/components/ntp_tiles/custom_links_manager_impl_unittest.cc +++ b/components/ntp_tiles/custom_links_manager_impl_unittest.cc
@@ -26,29 +26,28 @@ struct TestCaseItem { const char* url; - const char16_t* title; + const char* title; }; -const TestCaseItem kTestCase1[] = {{"http://foo1.com/", u"Foo1"}}; +const TestCaseItem kTestCase1[] = {{"http://foo1.com/", "Foo1"}}; const TestCaseItem kTestCase2[] = { - {"http://foo1.com/", u"Foo1"}, - {"http://foo2.com/", u"Foo2"}, + {"http://foo1.com/", "Foo1"}, + {"http://foo2.com/", "Foo2"}, }; const TestCaseItem kTestCase3[] = { - {"http://foo1.com/", u"Foo1"}, - {"http://foo2.com/", u"Foo2"}, - {"http://foo3.com/", u"Foo3"}, + {"http://foo1.com/", "Foo1"}, + {"http://foo2.com/", "Foo2"}, + {"http://foo3.com/", "Foo3"}, }; const TestCaseItem kTestCaseMax[] = { - {"http://foo1.com/", u"Foo1"}, {"http://foo2.com/", u"Foo2"}, - {"http://foo3.com/", u"Foo3"}, {"http://foo4.com/", u"Foo4"}, - {"http://foo5.com/", u"Foo5"}, {"http://foo6.com/", u"Foo6"}, - {"http://foo7.com/", u"Foo7"}, {"http://foo8.com/", u"Foo8"}, - {"http://foo9.com/", u"Foo9"}, {"http://foo10.com/", u"Foo10"}, + {"http://foo1.com/", "Foo1"}, {"http://foo2.com/", "Foo2"}, + {"http://foo3.com/", "Foo3"}, {"http://foo4.com/", "Foo4"}, + {"http://foo5.com/", "Foo5"}, {"http://foo6.com/", "Foo6"}, + {"http://foo7.com/", "Foo7"}, {"http://foo8.com/", "Foo8"}, + {"http://foo9.com/", "Foo9"}, {"http://foo10.com/", "Foo10"}, }; const char kTestTitle[] = "Test"; -const char16_t kTestTitle16[] = u"Test"; const char kTestUrl[] = "http://test.com/"; base::Value::ListStorage FillTestListStorage(const char* url, @@ -63,10 +62,10 @@ return new_link_list; } -void AddTile(NTPTilesVector* tiles, const char* url, const char16_t* title) { +void AddTile(NTPTilesVector* tiles, const char* url, const char* title) { NTPTile tile; tile.url = GURL(url); - tile.title = title; + tile.title = base::UTF8ToUTF16(title); tiles->push_back(std::move(tile)); } @@ -81,7 +80,8 @@ std::vector<Link> FillTestLinks(base::span<const TestCaseItem> test_cases) { std::vector<Link> links; for (const auto& test_case : test_cases) { - links.emplace_back(Link{GURL(test_case.url), test_case.title, true}); + links.emplace_back( + Link{GURL(test_case.url), base::UTF8ToUTF16(test_case.title), true}); } return links; } @@ -160,8 +160,10 @@ // Add link. std::vector<Link> expected_links = initial_links; - expected_links.emplace_back(Link{GURL(kTestUrl), kTestTitle16, false}); - EXPECT_TRUE(custom_links_->AddLink(GURL(kTestUrl), kTestTitle16)); + expected_links.emplace_back( + Link{GURL(kTestUrl), base::UTF8ToUTF16(kTestTitle), false}); + EXPECT_TRUE( + custom_links_->AddLink(GURL(kTestUrl), base::UTF8ToUTF16(kTestTitle))); EXPECT_EQ(expected_links, custom_links_->GetLinks()); } @@ -172,7 +174,8 @@ ASSERT_EQ(initial_links, custom_links_->GetLinks()); // Try to add link. This should fail and not modify the list. - EXPECT_FALSE(custom_links_->AddLink(GURL(kTestUrl), kTestTitle16)); + EXPECT_FALSE( + custom_links_->AddLink(GURL(kTestUrl), base::UTF8ToUTF16(kTestTitle))); EXPECT_EQ(initial_links, custom_links_->GetLinks()); } @@ -183,8 +186,8 @@ ASSERT_EQ(initial_links, custom_links_->GetLinks()); // Try to add duplicate link. This should fail and not modify the list. - EXPECT_FALSE( - custom_links_->AddLink(GURL(kTestCase1[0].url), kTestCase1[0].title)); + EXPECT_FALSE(custom_links_->AddLink(GURL(kTestCase1[0].url), + base::UTF8ToUTF16(kTestCase1[0].title))); EXPECT_EQ(initial_links, custom_links_->GetLinks()); } @@ -197,20 +200,25 @@ EXPECT_TRUE(custom_links_->UpdateLink(GURL(kTestCase1[0].url), GURL(kTestUrl), std::u16string())); EXPECT_EQ( - std::vector<Link>({Link{GURL(kTestUrl), kTestCase1[0].title, false}}), + std::vector<Link>({Link{GURL(kTestUrl), + base::UTF8ToUTF16(kTestCase1[0].title), false}}), custom_links_->GetLinks()); // Update the link's title. - EXPECT_TRUE(custom_links_->UpdateLink(GURL(kTestUrl), GURL(), kTestTitle16)); - EXPECT_EQ(std::vector<Link>({Link{GURL(kTestUrl), kTestTitle16, false}}), + EXPECT_TRUE(custom_links_->UpdateLink(GURL(kTestUrl), GURL(), + base::UTF8ToUTF16(kTestTitle))); + EXPECT_EQ(std::vector<Link>( + {Link{GURL(kTestUrl), base::UTF8ToUTF16(kTestTitle), false}}), custom_links_->GetLinks()); // Update the link's URL and title. - EXPECT_TRUE(custom_links_->UpdateLink(GURL(kTestUrl), GURL(kTestCase1[0].url), - kTestCase1[0].title)); - EXPECT_EQ(std::vector<Link>( - {Link{GURL(kTestCase1[0].url), kTestCase1[0].title, false}}), - custom_links_->GetLinks()); + EXPECT_TRUE( + custom_links_->UpdateLink(GURL(kTestUrl), GURL(kTestCase1[0].url), + base::UTF8ToUTF16(kTestCase1[0].title))); + EXPECT_EQ( + std::vector<Link>({Link{GURL(kTestCase1[0].url), + base::UTF8ToUTF16(kTestCase1[0].title), false}}), + custom_links_->GetLinks()); } TEST_F(CustomLinksManagerImplTest, UpdateLinkWithInvalidParams) { @@ -221,7 +229,8 @@ // Try to update a link that does not exist. This should fail and not modify // the list. - EXPECT_FALSE(custom_links_->UpdateLink(GURL(kTestUrl), GURL(), kTestTitle16)); + EXPECT_FALSE(custom_links_->UpdateLink(GURL(kTestUrl), GURL(), + base::UTF8ToUTF16(kTestTitle))); EXPECT_EQ(initial_links, custom_links_->GetLinks()); // Try to pass empty params. This should fail and not modify the list. @@ -230,7 +239,8 @@ EXPECT_EQ(initial_links, custom_links_->GetLinks()); // Try to pass an invalid URL. This should fail and not modify the list. - EXPECT_FALSE(custom_links_->UpdateLink(GURL("test"), GURL(), kTestTitle16)); + EXPECT_FALSE(custom_links_->UpdateLink(GURL("test"), GURL(), + base::UTF8ToUTF16(kTestTitle))); EXPECT_EQ(initial_links, custom_links_->GetLinks()); EXPECT_FALSE(custom_links_->UpdateLink(GURL(kTestCase1[0].url), GURL("test"), std::u16string())); @@ -278,19 +288,25 @@ // Move the last link to the front. EXPECT_TRUE(custom_links_->ReorderLink(GURL(kTestCase3[2].url), (size_t)0)); - EXPECT_EQ(std::vector<Link>( - {Link{GURL(kTestCase3[2].url), kTestCase3[2].title, true}, - Link{GURL(kTestCase3[0].url), kTestCase3[0].title, true}, - Link{GURL(kTestCase3[1].url), kTestCase3[1].title, true}}), - custom_links_->GetLinks()); + EXPECT_EQ( + std::vector<Link>({Link{GURL(kTestCase3[2].url), + base::UTF8ToUTF16(kTestCase3[2].title), true}, + Link{GURL(kTestCase3[0].url), + base::UTF8ToUTF16(kTestCase3[0].title), true}, + Link{GURL(kTestCase3[1].url), + base::UTF8ToUTF16(kTestCase3[1].title), true}}), + custom_links_->GetLinks()); // Move the same link to the right. EXPECT_TRUE(custom_links_->ReorderLink(GURL(kTestCase3[2].url), (size_t)1)); - EXPECT_EQ(std::vector<Link>( - {Link{GURL(kTestCase3[0].url), kTestCase3[0].title, true}, - Link{GURL(kTestCase3[2].url), kTestCase3[2].title, true}, - Link{GURL(kTestCase3[1].url), kTestCase3[1].title, true}}), - custom_links_->GetLinks()); + EXPECT_EQ( + std::vector<Link>({Link{GURL(kTestCase3[0].url), + base::UTF8ToUTF16(kTestCase3[0].title), true}, + Link{GURL(kTestCase3[2].url), + base::UTF8ToUTF16(kTestCase3[2].title), true}, + Link{GURL(kTestCase3[1].url), + base::UTF8ToUTF16(kTestCase3[1].title), true}}), + custom_links_->GetLinks()); // Move the same link to the end. EXPECT_TRUE(custom_links_->ReorderLink(GURL(kTestCase3[2].url), (size_t)2)); @@ -300,9 +316,10 @@ TEST_F(CustomLinksManagerImplTest, DeleteLink) { // Initialize. NTPTilesVector initial_tiles; - AddTile(&initial_tiles, kTestUrl, kTestTitle16); + AddTile(&initial_tiles, kTestUrl, kTestTitle); ASSERT_TRUE(custom_links_->Initialize(initial_tiles)); - ASSERT_EQ(std::vector<Link>({Link{GURL(kTestUrl), kTestTitle16, true}}), + ASSERT_EQ(std::vector<Link>( + {Link{GURL(kTestUrl), base::UTF8ToUTF16(kTestTitle), true}}), custom_links_->GetLinks()); // Delete link. @@ -331,10 +348,12 @@ EXPECT_EQ(initial_links, custom_links_->GetLinks()); // Add link. - EXPECT_TRUE(custom_links_->AddLink(GURL(kTestUrl), kTestTitle16)); + EXPECT_TRUE( + custom_links_->AddLink(GURL(kTestUrl), base::UTF8ToUTF16(kTestTitle))); EXPECT_EQ(std::vector<Link>( - {Link{GURL(kTestCase1[0].url), kTestCase1[0].title, true}, - {Link{GURL(kTestUrl), kTestTitle16, false}}}), + {Link{GURL(kTestCase1[0].url), + base::UTF8ToUTF16(kTestCase1[0].title), true}, + {Link{GURL(kTestUrl), base::UTF8ToUTF16(kTestTitle), false}}}), custom_links_->GetLinks()); // Undo add link. @@ -356,7 +375,8 @@ EXPECT_TRUE(custom_links_->UpdateLink(GURL(kTestCase1[0].url), GURL(kTestUrl), std::u16string())); EXPECT_EQ( - std::vector<Link>({Link{GURL(kTestUrl), kTestCase1[0].title, false}}), + std::vector<Link>({Link{GURL(kTestUrl), + base::UTF8ToUTF16(kTestCase1[0].title), false}}), custom_links_->GetLinks()); // Undo update link. @@ -364,11 +384,11 @@ EXPECT_EQ(initial_links, custom_links_->GetLinks()); // Update the link's title. - EXPECT_TRUE( - custom_links_->UpdateLink(GURL(kTestCase1[0].url), GURL(), kTestTitle16)); - EXPECT_EQ( - std::vector<Link>({Link{GURL(kTestCase1[0].url), kTestTitle16, false}}), - custom_links_->GetLinks()); + EXPECT_TRUE(custom_links_->UpdateLink(GURL(kTestCase1[0].url), GURL(), + base::UTF8ToUTF16(kTestTitle))); + EXPECT_EQ(std::vector<Link>({Link{GURL(kTestCase1[0].url), + base::UTF8ToUTF16(kTestTitle), false}}), + custom_links_->GetLinks()); // Undo update link. EXPECT_TRUE(custom_links_->UndoAction()); @@ -382,8 +402,9 @@ TEST_F(CustomLinksManagerImplTest, UndoDeleteLink) { // Initialize. NTPTilesVector initial_tiles; - AddTile(&initial_tiles, kTestUrl, kTestTitle16); - std::vector<Link> expected_links({Link{GURL(kTestUrl), kTestTitle16, true}}); + AddTile(&initial_tiles, kTestUrl, kTestTitle); + std::vector<Link> expected_links( + {Link{GURL(kTestUrl), base::UTF8ToUTF16(kTestTitle), true}}); ASSERT_TRUE(custom_links_->Initialize(initial_tiles)); ASSERT_EQ(expected_links, custom_links_->GetLinks()); @@ -402,8 +423,10 @@ ASSERT_TRUE(custom_links_->GetLinks().empty()); // Add link. - std::vector<Link> expected_links({Link{GURL(kTestUrl), kTestTitle16, false}}); - ASSERT_TRUE(custom_links_->AddLink(GURL(kTestUrl), kTestTitle16)); + std::vector<Link> expected_links( + {Link{GURL(kTestUrl), base::UTF8ToUTF16(kTestTitle), false}}); + ASSERT_TRUE( + custom_links_->AddLink(GURL(kTestUrl), base::UTF8ToUTF16(kTestTitle))); ASSERT_EQ(expected_links, custom_links_->GetLinks()); // Delete link. @@ -441,9 +464,10 @@ {history::URLRow(GURL(kTestCase2[1].url))}, /*favicon_urls=*/std::set<GURL>(), /*restrict_urls=*/base::nullopt)); - EXPECT_EQ(std::vector<Link>( - {Link{GURL(kTestCase2[0].url), kTestCase2[0].title, true}}), - custom_links_->GetLinks()); + EXPECT_EQ( + std::vector<Link>({Link{GURL(kTestCase2[0].url), + base::UTF8ToUTF16(kTestCase2[0].title), true}}), + custom_links_->GetLinks()); task_environment_.RunUntilIdle(); } @@ -510,12 +534,14 @@ // Initialize. std::vector<Link> links_after_add( - {Link{GURL(kTestCase1[0].url), kTestCase1[0].title, true}, - Link{GURL(kTestUrl), kTestTitle16, false}}); + {Link{GURL(kTestCase1[0].url), base::UTF8ToUTF16(kTestCase1[0].title), + true}, + Link{GURL(kTestUrl), base::UTF8ToUTF16(kTestTitle), false}}); ASSERT_TRUE(custom_links_->Initialize(FillTestTiles(kTestCase1))); ASSERT_EQ(FillTestLinks(kTestCase1), custom_links_->GetLinks()); // Add link. - ASSERT_TRUE(custom_links_->AddLink(GURL(kTestUrl), kTestTitle16)); + ASSERT_TRUE( + custom_links_->AddLink(GURL(kTestUrl), base::UTF8ToUTF16(kTestTitle))); ASSERT_EQ(links_after_add, custom_links_->GetLinks()); // Try to delete the added link. This should fail and not modify the list. @@ -537,7 +563,8 @@ /*expired=*/false, history::URLRows(), /*favicon_urls=*/std::set<GURL>(), /*restrict_urls=*/base::nullopt)); - EXPECT_EQ(std::vector<Link>({Link{GURL(kTestUrl), kTestTitle16, false}}), + EXPECT_EQ(std::vector<Link>( + {Link{GURL(kTestUrl), base::UTF8ToUTF16(kTestTitle), false}}), custom_links_->GetLinks()); task_environment_.RunUntilIdle(); @@ -609,9 +636,11 @@ ASSERT_EQ(FillTestLinks(kTestCase1), custom_links_->GetLinks()); // Add link. std::vector<Link> links_after_add( - {Link{GURL(kTestCase1[0].url), kTestCase1[0].title, true}, - Link{GURL(kTestUrl), kTestTitle16, false}}); - ASSERT_TRUE(custom_links_->AddLink(GURL(kTestUrl), kTestTitle16)); + {Link{GURL(kTestCase1[0].url), base::UTF8ToUTF16(kTestCase1[0].title), + true}, + Link{GURL(kTestUrl), base::UTF8ToUTF16(kTestTitle), false}}); + ASSERT_TRUE( + custom_links_->AddLink(GURL(kTestUrl), base::UTF8ToUTF16(kTestTitle))); ASSERT_EQ(links_after_add, custom_links_->GetLinks()); // Try an empty history deletion. This should do nothing. @@ -640,11 +669,12 @@ // Modifying ourselves should not notify. EXPECT_CALL(callback, Run()).Times(0); - EXPECT_TRUE( - custom_links_->AddLink(GURL(kTestCase1[0].url), kTestCase1[0].title)); - EXPECT_EQ(std::vector<Link>( - {Link{GURL(kTestCase1[0].url), kTestCase1[0].title, false}}), - custom_links_->GetLinks()); + EXPECT_TRUE(custom_links_->AddLink(GURL(kTestCase1[0].url), + base::UTF8ToUTF16(kTestCase1[0].title))); + EXPECT_EQ( + std::vector<Link>({Link{GURL(kTestCase1[0].url), + base::UTF8ToUTF16(kTestCase1[0].title), false}}), + custom_links_->GetLinks()); // Modify the preference. This should notify and update the current list of // links. @@ -652,7 +682,8 @@ prefs_.SetUserPref(prefs::kCustomLinksList, std::make_unique<base::Value>( FillTestListStorage(kTestUrl, kTestTitle, true))); - EXPECT_EQ(std::vector<Link>({Link{GURL(kTestUrl), kTestTitle16, true}}), + EXPECT_EQ(std::vector<Link>( + {Link{GURL(kTestUrl), base::UTF8ToUTF16(kTestTitle), true}}), custom_links_->GetLinks()); } @@ -672,7 +703,8 @@ std::make_unique<base::Value>( FillTestListStorage(kTestUrl, kTestTitle, false))); EXPECT_TRUE(custom_links_->IsInitialized()); - EXPECT_EQ(std::vector<Link>({Link{GURL(kTestUrl), kTestTitle16, false}}), + EXPECT_EQ(std::vector<Link>( + {Link{GURL(kTestUrl), base::UTF8ToUTF16(kTestTitle), false}}), custom_links_->GetLinks()); }
diff --git a/components/ntp_tiles/custom_links_store_unittest.cc b/components/ntp_tiles/custom_links_store_unittest.cc index 36aa913..efa4cfa 100644 --- a/components/ntp_tiles/custom_links_store_unittest.cc +++ b/components/ntp_tiles/custom_links_store_unittest.cc
@@ -19,8 +19,8 @@ namespace { -const char16_t kTestTitle1[] = u"Foo1"; -const char16_t kTestTitle2[] = u"Foo2"; +const char kTestTitle1[] = "Foo1"; +const char kTestTitle2[] = "Foo2"; const char kTestUrl1[] = "http://foo1.com/"; const char kTestUrl2[] = "http://foo2.com/"; @@ -41,8 +41,8 @@ }; TEST_F(CustomLinksStoreTest, StoreAndRetrieveLinks) { - std::vector<CustomLinksManager::Link> initial_links( - {CustomLinksManager::Link{GURL(kTestUrl1), kTestTitle1, true}}); + std::vector<CustomLinksManager::Link> initial_links({CustomLinksManager::Link{ + GURL(kTestUrl1), base::UTF8ToUTF16(kTestTitle1), true}}); custom_links_store_->StoreLinks(initial_links); std::vector<CustomLinksManager::Link> retrieved_links = @@ -52,8 +52,10 @@ TEST_F(CustomLinksStoreTest, StoreEmptyList) { std::vector<CustomLinksManager::Link> populated_links( - {CustomLinksManager::Link{GURL(kTestUrl1), kTestTitle1, false}, - CustomLinksManager::Link{GURL(kTestUrl2), kTestTitle2, true}}); + {CustomLinksManager::Link{GURL(kTestUrl1), base::UTF8ToUTF16(kTestTitle1), + false}, + CustomLinksManager::Link{GURL(kTestUrl2), base::UTF8ToUTF16(kTestTitle2), + true}}); custom_links_store_->StoreLinks(populated_links); std::vector<CustomLinksManager::Link> retrieved_links = @@ -66,8 +68,8 @@ } TEST_F(CustomLinksStoreTest, ClearLinks) { - std::vector<CustomLinksManager::Link> initial_links( - {CustomLinksManager::Link{GURL(kTestUrl1), kTestTitle1}}); + std::vector<CustomLinksManager::Link> initial_links({CustomLinksManager::Link{ + GURL(kTestUrl1), base::UTF8ToUTF16(kTestTitle1)}}); custom_links_store_->StoreLinks(initial_links); std::vector<CustomLinksManager::Link> retrieved_links = @@ -81,8 +83,10 @@ TEST_F(CustomLinksStoreTest, LinksSavedAfterShutdown) { std::vector<CustomLinksManager::Link> initial_links( - {CustomLinksManager::Link{GURL(kTestUrl1), kTestTitle1, false}, - CustomLinksManager::Link{GURL(kTestUrl2), kTestTitle2, true}}); + {CustomLinksManager::Link{GURL(kTestUrl1), base::UTF8ToUTF16(kTestTitle1), + false}, + CustomLinksManager::Link{GURL(kTestUrl2), base::UTF8ToUTF16(kTestTitle2), + true}}); custom_links_store_->StoreLinks(initial_links); std::vector<CustomLinksManager::Link> retrieved_links =
diff --git a/components/omnibox/browser/autocomplete_match_type_unittest.cc b/components/omnibox/browser/autocomplete_match_type_unittest.cc index 5cae4c0..cef395a6 100644 --- a/components/omnibox/browser/autocomplete_match_type_unittest.cc +++ b/components/omnibox/browser/autocomplete_match_type_unittest.cc
@@ -74,6 +74,7 @@ ASSERT_TRUE(ParseAnswer(answer_json, &answer)); match.answer = answer; - EXPECT_EQ(kSearch + u", answer, sunny with a chance of hail, 4 of 6", + EXPECT_EQ(kSearch + base::UTF8ToUTF16( + ", answer, sunny with a chance of hail, 4 of 6"), AutocompleteMatchType::ToAccessibilityLabel(match, kSearch, 3, 6)); }
diff --git a/components/omnibox/browser/clipboard_provider_unittest.cc b/components/omnibox/browser/clipboard_provider_unittest.cc index 8a5fb0c..f7c01fda 100644 --- a/components/omnibox/browser/clipboard_provider_unittest.cc +++ b/components/omnibox/browser/clipboard_provider_unittest.cc
@@ -36,8 +36,8 @@ const char kCurrentURL[] = "http://example.com/current"; const char kClipboardURL[] = "http://example.com/clipboard"; -const char16_t kClipboardText[] = u"Search for me"; -const char16_t kClipboardTitleText[] = u"\"Search for me\""; +const char kClipboardText[] = "Search for me"; +const char kClipboardTitleText[] = "\"Search for me\""; class CreateMatchWithContentCallbackWaiter { public: @@ -185,11 +185,13 @@ auto template_url_service = std::make_unique<TemplateURLService>( /*initializers=*/nullptr, /*count=*/0); client_->set_template_url_service(std::move(template_url_service)); - SetClipboardText(kClipboardText); + SetClipboardText(base::UTF8ToUTF16(kClipboardText)); provider_->Start(CreateAutocompleteInput(OmniboxFocusType::ON_FOCUS), false); ASSERT_GE(provider_->matches().size(), 1U); - EXPECT_EQ(kClipboardTitleText, provider_->matches().back().contents); - EXPECT_EQ(kClipboardText, provider_->matches().back().fill_into_edit); + EXPECT_EQ(base::UTF8ToUTF16(kClipboardTitleText), + provider_->matches().back().contents); + EXPECT_EQ(base::UTF8ToUTF16(kClipboardText), + provider_->matches().back().fill_into_edit); EXPECT_EQ(AutocompleteMatchType::CLIPBOARD_TEXT, provider_->matches().back().type); } @@ -216,7 +218,7 @@ auto template_url_service = std::make_unique<TemplateURLService>( /*initializers=*/nullptr, /*count=*/0); client_->set_template_url_service(std::move(template_url_service)); - SetClipboardText(kClipboardText); + SetClipboardText(base::UTF8ToUTF16(kClipboardText)); provider_->Start(CreateAutocompleteInput(OmniboxFocusType::ON_FOCUS), false); ASSERT_EQ(provider_->matches().size(), 1U); @@ -251,7 +253,7 @@ auto template_url_service = std::make_unique<TemplateURLService>( /*initializers=*/nullptr, /*count=*/0); client_->set_template_url_service(std::move(template_url_service)); - SetClipboardText(kClipboardText); + SetClipboardText(base::UTF8ToUTF16(kClipboardText)); provider_->Start(CreateAutocompleteInput(OmniboxFocusType::ON_FOCUS), false); ASSERT_GE(provider_->matches().size(), 1U); EXPECT_EQ(AutocompleteMatchType::CLIPBOARD_TEXT, @@ -297,7 +299,7 @@ } TEST_F(ClipboardProviderTest, CreateTextMatchWithContent) { - SetClipboardText(kClipboardText); + SetClipboardText(base::UTF8ToUTF16(kClipboardText)); auto template_url_service = std::make_unique<TemplateURLService>( /*initializers=*/nullptr, /*count=*/0); client_->set_template_url_service(std::move(template_url_service)); @@ -305,8 +307,8 @@ CreateMatchWithContentCallbackWaiter waiter(provider_, &match); waiter.WaitForMatchUpdated(); - EXPECT_EQ(kClipboardTitleText, match.contents); - EXPECT_EQ(kClipboardText, match.fill_into_edit); + EXPECT_EQ(base::UTF8ToUTF16(kClipboardTitleText), match.contents); + EXPECT_EQ(base::UTF8ToUTF16(kClipboardText), match.fill_into_edit); EXPECT_EQ(AutocompleteMatchType::CLIPBOARD_TEXT, match.type); }
diff --git a/components/omnibox/browser/history_quick_provider_unittest.cc b/components/omnibox/browser/history_quick_provider_unittest.cc index b7610a3..26ee153 100644 --- a/components/omnibox/browser/history_quick_provider_unittest.cc +++ b/components/omnibox/browser/history_quick_provider_unittest.cc
@@ -559,9 +559,9 @@ "%95%8C%E5%A4%A7%E6%88%A6#.E3.83.B4.E3.82.A7.E3.83.AB.E3.82.B5.E3.82." "A4.E3.83.A6.E4.BD.93.E5.88.B6"); RunTest(u"第二 e3", false, expected_urls, false, - u"ja.wikipedia.org/wiki/第二次世界大戦#.E3.83.B4.E3." - u"82.A7.E3.83.AB.E3.82.B5.E3.82.A4.E3.83.A6.E4.BD." - u"93.E5.88.B6", + base::UTF8ToUTF16("ja.wikipedia.org/wiki/第二次世界大戦#.E3.83.B4.E3." + "82.A7.E3.83.AB.E3.82.B5.E3.82.A4.E3.83.A6.E4.BD." + "93.E5.88.B6"), std::u16string()); #if DCHECK_IS_ON() ac_matches()[0].Validate(); @@ -813,9 +813,10 @@ } ScoredHistoryMatch BuildScoredHistoryMatch(const std::string& url_text, - const std::u16string& input_term) { + const std::string& input_term) { return ScoredHistoryMatch(history::URLRow(GURL(url_text)), VisitInfoVector(), - input_term, String16Vector(1, input_term), + base::UTF8ToUTF16(input_term), + String16Vector(1, base::UTF8ToUTF16(input_term)), WordStarts(1, 0), RowWordStarts(), false, 0, base::Time()); } @@ -826,7 +827,7 @@ TestSchemeClassifier()); provider().Start(input, false); ScoredHistoryMatch history_match = - BuildScoredHistoryMatch("http://www.facebook.com", u"face"); + BuildScoredHistoryMatch("http://www.facebook.com", "face"); AutocompleteMatch match = provider().QuickMatchToACMatch(history_match, 100); EXPECT_EQ(u"facebook.com", match.contents); @@ -839,7 +840,7 @@ TestSchemeClassifier()); provider().Start(input, false); ScoredHistoryMatch history_match = - BuildScoredHistoryMatch("http://www.facebook.com", u"http://face"); + BuildScoredHistoryMatch("http://www.facebook.com", "http://face"); AutocompleteMatch match = provider().QuickMatchToACMatch(history_match, 100); EXPECT_EQ(u"http://facebook.com", match.contents); @@ -852,7 +853,7 @@ TestSchemeClassifier()); provider().Start(input, false); ScoredHistoryMatch history_match = - BuildScoredHistoryMatch("http://www.facebook.com", u"ht"); + BuildScoredHistoryMatch("http://www.facebook.com", "ht"); history_match.match_in_scheme = true; AutocompleteMatch match = provider().QuickMatchToACMatch(history_match, 100); @@ -866,7 +867,7 @@ TestSchemeClassifier()); provider().Start(input, false); ScoredHistoryMatch history_match = - BuildScoredHistoryMatch("https://www.facebook.com", u"https://face"); + BuildScoredHistoryMatch("https://www.facebook.com", "https://face"); AutocompleteMatch match = provider().QuickMatchToACMatch(history_match, 100); EXPECT_EQ(u"https://facebook.com", match.contents); @@ -878,7 +879,7 @@ TestSchemeClassifier()); provider().Start(input, false); ScoredHistoryMatch history_match = - BuildScoredHistoryMatch("https://www.facebook.com", u"face"); + BuildScoredHistoryMatch("https://www.facebook.com", "face"); AutocompleteMatch match = provider().QuickMatchToACMatch(history_match, 100); EXPECT_EQ(u"facebook.com", match.contents);
diff --git a/components/page_info/page_info_ui.cc b/components/page_info/page_info_ui.cc index 96a800c..d34cecf 100644 --- a/components/page_info/page_info_ui.cc +++ b/components/page_info/page_info_ui.cc
@@ -794,13 +794,21 @@ } // static -const ui::ImageModel PageInfoUI::GetCertificateIcon() { +const ui::ImageModel PageInfoUI::GetValidCertificateIcon() { return ui::ImageModel::FromVectorIcon( vector_icons::kCertificateIcon, ui::NativeTheme::kColorId_DefaultIconColor, kVectorIconSize); } // static +const ui::ImageModel PageInfoUI::GetInvalidCertificateIcon() { + return ui::ImageModel::FromVectorIcon( + vector_icons::kCertificateIcon, + ui::NativeTheme::kColorId_DefaultIconColor, kVectorIconSize, + &vector_icons::kBlockedBadgeIcon); +} + +// static const ui::ImageModel PageInfoUI::GetSiteSettingsIcon() { return ui::ImageModel::FromVectorIcon( vector_icons::kSettingsIcon, ui::NativeTheme::kColorId_DefaultIconColor,
diff --git a/components/page_info/page_info_ui.h b/components/page_info/page_info_ui.h index b24df33..524b90d 100644 --- a/components/page_info/page_info_ui.h +++ b/components/page_info/page_info_ui.h
@@ -205,8 +205,11 @@ static const ui::ImageModel GetChosenObjectIcon(const ChosenObjectInfo& info, bool deleted); - // Returns the icon for the page Certificate. - static const ui::ImageModel GetCertificateIcon(); + // Returns the icon for the page's certificate when it's valid. + static const ui::ImageModel GetValidCertificateIcon(); + + // Returns the icon for the page's certificate when it's invalid. + static const ui::ImageModel GetInvalidCertificateIcon(); // Returns the icon for the button / link to Site settings. static const ui::ImageModel GetSiteSettingsIcon();
diff --git a/components/page_info_strings.grdp b/components/page_info_strings.grdp index 9932ad1..2565e96 100644 --- a/components/page_info_strings.grdp +++ b/components/page_info_strings.grdp
@@ -249,6 +249,12 @@ <message name="IDS_PAGE_INFO_CERTIFICATE_INVALID_PARENTHESIZED" desc="Button text used as part of IDS_PAGE_INFO_CERTIFICATE_BUTTON_TEXT when the Page Information bubble has been opened for a site with an invalid certificate."> (Invalid) </message> + <message name="IDS_PAGE_INFO_CERTIFICATE_IS_VALID" desc="Title of the certificate area in the Page Info bubble, shown when a HTTPS site is loaded with a valid certificate."> + Certificate is valid + </message> + <message name="IDS_PAGE_INFO_CERTIFICATE_IS_NOT_VALID" desc="Title of the certificate area in the Page Info bubble, shown when a HTTPS site is loaded with an invalid certificate."> + Certificate is not valid + </message> <message name="IDS_PAGE_INFO_CERTIFICATE_VALID_LINK_TOOLTIP" desc="The text of the tooltip on IDS_PAGE_INFO_CERTIFICATE_VALID_LINK."> Show certificate (issued by <ph name="ISSUER">$1<ex>Let's Encrypt X3</ex></ph>) </message>
diff --git a/components/page_info_strings_grdp/IDS_PAGE_INFO_CERTIFICATE_IS_NOT_VALID.png.sha1 b/components/page_info_strings_grdp/IDS_PAGE_INFO_CERTIFICATE_IS_NOT_VALID.png.sha1 new file mode 100644 index 0000000..8d059c7 --- /dev/null +++ b/components/page_info_strings_grdp/IDS_PAGE_INFO_CERTIFICATE_IS_NOT_VALID.png.sha1
@@ -0,0 +1 @@ +6431f60ed41e4c11d919631d458a7a5692437e98 \ No newline at end of file
diff --git a/components/page_info_strings_grdp/IDS_PAGE_INFO_CERTIFICATE_IS_VALID.png.sha1 b/components/page_info_strings_grdp/IDS_PAGE_INFO_CERTIFICATE_IS_VALID.png.sha1 new file mode 100644 index 0000000..66b3c2a --- /dev/null +++ b/components/page_info_strings_grdp/IDS_PAGE_INFO_CERTIFICATE_IS_VALID.png.sha1
@@ -0,0 +1 @@ +3c1bec2a0db5e79f8855fd4db9b4cdb4b5a5aa8a \ No newline at end of file
diff --git a/components/password_manager/core/browser/biometric_authenticator.h b/components/password_manager/core/browser/biometric_authenticator.h index 807512a2..93faf63f 100644 --- a/components/password_manager/core/browser/biometric_authenticator.h +++ b/components/password_manager/core/browser/biometric_authenticator.h
@@ -20,6 +20,8 @@ kAvailable = 0, kNoHardware = 1, kNotEnrolled = 2, + kAndroidVersionNotSupported = 3, + kAvailableNoFallback = 4, }; // This interface encapsulates operations related to biometric authentication.
diff --git a/components/password_manager/core/browser/form_parsing/form_parser.cc b/components/password_manager/core/browser/form_parsing/form_parser.cc index d78c194c..a93855f 100644 --- a/components/password_manager/core/browser/form_parsing/form_parser.cc +++ b/components/password_manager/core/browser/form_parsing/form_parser.cc
@@ -427,8 +427,11 @@ // fields have the "username" attribute. // If any assumption is violated, the autocomplete attribute is ignored. void ParseUsingAutocomplete(const std::vector<ProcessedField>& processed_fields, + FormDataParser::Mode mode, SignificantFields* result) { bool new_password_found_by_server = result->new_password; + bool new_password_found_by_autocomplete = false; + bool should_ignore_new_password_autocomplete = false; const FormFieldData* field_marked_as_username = nullptr; int username_fields_found = 0; for (const ProcessedField& processed_field : processed_fields) { @@ -452,14 +455,27 @@ break; case AutocompleteFlag::kNewPassword: if (!processed_field.is_password || new_password_found_by_server || - processed_field.server_hints_not_password) + processed_field.server_hints_not_password || + should_ignore_new_password_autocomplete) continue; // The first field with autocomplete=new-password is considered to be // new_password and the second is confirmation_password. - if (!result->new_password) + if (!result->new_password) { result->new_password = processed_field.field; - else if (!result->confirmation_password) + new_password_found_by_autocomplete = true; + } else if (!result->confirmation_password) { + // Ignore kNewPassword autocomplete feature if fields that have it + // have different values in saving mode. + if (mode == FormDataParser::Mode::kSaving && + new_password_found_by_autocomplete && + GetFieldValue(*result->new_password) != + GetFieldValue(*processed_field.field)) { + should_ignore_new_password_autocomplete = true; + result->new_password = nullptr; + continue; + } result->confirmation_password = processed_field.field; + } break; case AutocompleteFlag::kNonPassword: case AutocompleteFlag::kNone: @@ -995,7 +1011,7 @@ // (2) If that failed, try to parse with autocomplete attributes. if (!significant_fields.is_single_username) { - ParseUsingAutocomplete(processed_fields, &significant_fields); + ParseUsingAutocomplete(processed_fields, mode, &significant_fields); if (method == UsernameDetectionMethod::kNoUsernameDetected && significant_fields.username) { method = UsernameDetectionMethod::kAutocompleteAttribute;
diff --git a/components/password_manager/core/browser/form_parsing/form_parser_unittest.cc b/components/password_manager/core/browser/form_parsing/form_parser_unittest.cc index 5cbb89c..de6eae86 100644 --- a/components/password_manager/core/browser/form_parsing/form_parser_unittest.cc +++ b/components/password_manager/core/browser/form_parsing/form_parser_unittest.cc
@@ -1087,14 +1087,17 @@ {.role = ElementRole::NEW_PASSWORD, .is_readonly = true, .autocomplete_attribute = "new-password", + .value = u"newpass", .form_control_type = "password"}, {.role = ElementRole::CONFIRMATION_PASSWORD, .is_readonly = true, .autocomplete_attribute = "new-password", + .value = u"newpass", .form_control_type = "password"}, {.role = ElementRole::CURRENT_PASSWORD, .is_readonly = true, .autocomplete_attribute = "current-password", + .value = u"oldpass", .form_control_type = "password"}, }, .is_new_password_reliable = true, @@ -2775,6 +2778,55 @@ } } +// Tests that 'new-password' autocomplete attribute is ignored when two +// or more fields that have it have different values. +TEST(FormParserTest, AutocompleteAttributesError) { + CheckTestData( + {{ + .description_for_logging = + "Wrong autocomplete attributes, 2 fields.", + .fields = + { + {.role_filling = ElementRole::NEW_PASSWORD, + .role_saving = ElementRole::CURRENT_PASSWORD, + .autocomplete_attribute = "new-password", + .value = u"oldpass", + .name = u"password1", + .form_control_type = "password"}, + {.role_filling = ElementRole::CONFIRMATION_PASSWORD, + .role_saving = ElementRole::NEW_PASSWORD, + .autocomplete_attribute = "new-password", + .value = u"newpass", + .name = u"password2", + .form_control_type = "password"}, + }, + }, + { + .description_for_logging = + "Wrong autocomplete attributes, 3 fields.", + .fields = + { + {.role_filling = ElementRole::NEW_PASSWORD, + .role_saving = ElementRole::CURRENT_PASSWORD, + .autocomplete_attribute = "new-password", + .value = u"oldpass", + .name = u"password1", + .form_control_type = "password"}, + {.role_filling = ElementRole::CONFIRMATION_PASSWORD, + .role_saving = ElementRole::NEW_PASSWORD, + .autocomplete_attribute = "new-password", + .value = u"newpass", + .name = u"password2", + .form_control_type = "password"}, + {.role_saving = ElementRole::CONFIRMATION_PASSWORD, + .autocomplete_attribute = "new-password", + .value = u"newpass", + .name = u"password3", + .form_control_type = "password"}, + }, + }}); +} + } // namespace } // namespace password_manager
diff --git a/components/password_manager/core/browser/votes_uploader_unittest.cc b/components/password_manager/core/browser/votes_uploader_unittest.cc index 9475312..3b29f72 100644 --- a/components/password_manager/core/browser/votes_uploader_unittest.cc +++ b/components/password_manager/core/browser/votes_uploader_unittest.cc
@@ -374,8 +374,8 @@ FormStructure form_structure(form); VotesUploader votes_uploader(&client_, true); votes_uploader.GeneratePasswordAttributesVote( - u"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqr" - u"stuvwxyz!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~", + base::UTF8ToUTF16("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqr" + "stuvwxyz!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"), &form_structure); base::Optional<std::pair<PasswordAttribute, bool>> vote = form_structure.get_password_attributes_vote(); @@ -386,13 +386,14 @@ // Checks that password attributes vote is not generated if the password has // non-ascii characters. for (const auto* password : - {u"пароль1", u"パスワード", u"münchen", u"סיסמה-A", u"Σ-12345", - u"գաղտնաբառըTTT", u"Slaptažodis", u"密碼", u"كلمهالسر", u"mậtkhẩu!", - u"ລະຫັດຜ່ານ-l", u"စကားဝှက်ကို3", u"პაროლი", u"पारण शब्द"}) { + {"пароль1", "パスワード", "münchen", "סיסמה-A", "Σ-12345", + "գաղտնաբառըTTT", "Slaptažodis", "密碼", "كلمهالسر", "mậtkhẩu!", + "ລະຫັດຜ່ານ-l", "စကားဝှက်ကို3", "პაროლი", "पारण शब्द"}) { FormData form; FormStructure form_structure(form); VotesUploader votes_uploader(&client_, true); - votes_uploader.GeneratePasswordAttributesVote(password, &form_structure); + votes_uploader.GeneratePasswordAttributesVote(base::UTF8ToUTF16(password), + &form_structure); base::Optional<std::pair<PasswordAttribute, bool>> vote = form_structure.get_password_attributes_vote();
diff --git a/components/payments/content/android/java/src/org/chromium/components/payments/AndroidPaymentAppFinder.java b/components/payments/content/android/java/src/org/chromium/components/payments/AndroidPaymentAppFinder.java index 6cf489d..8b105b9 100644 --- a/components/payments/content/android/java/src/org/chromium/components/payments/AndroidPaymentAppFinder.java +++ b/components/payments/content/android/java/src/org/chromium/components/payments/AndroidPaymentAppFinder.java
@@ -64,7 +64,6 @@ public static final String META_DATA_NAME_OF_SUPPORTED_DELEGATIONS = "org.chromium.payment_supported_delegations"; - private final Set<String> mNonUriPaymentMethods = new HashSet<>(); private final Set<GURL> mUrlPaymentMethods = new HashSet<>(); private final PaymentManifestDownloader mDownloader; private final PaymentManifestWebDataService mWebDataService; @@ -242,23 +241,12 @@ */ public void findAndroidPaymentApps() { if (mFactoryDelegate.getParams().hasClosed()) return; - // For non-URL payment method names, only names published by W3C should be supported. Keep - // this in sync with manifest_verifier.cc. - Set<String> supportedNonUriPaymentMethods = new HashSet<>(); - supportedNonUriPaymentMethods.add(MethodStrings.BASIC_CARD); - supportedNonUriPaymentMethods.add(MethodStrings.INTERLEDGER); - supportedNonUriPaymentMethods.add(MethodStrings.PAYEE_CREDIT_TRANSFER); - supportedNonUriPaymentMethods.add(MethodStrings.PAYER_CREDIT_TRANSFER); - supportedNonUriPaymentMethods.add(MethodStrings.TOKENIZED_CARD); - for (String method : mFactoryDelegate.getParams().getMethodData().keySet()) { assert !TextUtils.isEmpty(method); - if (mAppStores.containsValue(new GURL(method))) continue; - if (supportedNonUriPaymentMethods.contains(method)) { - mNonUriPaymentMethods.add(method); - } else { - GURL url = new GURL(method); - if (UrlUtil.isURLValid(url)) mUrlPaymentMethods.add(url); + GURL url = new GURL(method); // Only URL payment method names are supported. + if (mAppStores.containsValue(url)) continue; + if (UrlUtil.isValidUrlBasedPaymentMethodIdentifier(url)) { + mUrlPaymentMethods.add(url); } } @@ -433,16 +421,6 @@ } } - for (String nonUriMethodName : mNonUriPaymentMethods) { - if (methodToAppsMapping.containsKey(nonUriMethodName)) { - Set<ResolveInfo> supportedApps = methodToAppsMapping.get(nonUriMethodName); - for (ResolveInfo supportedApp : supportedApps) { - // Chrome does not verify app manifests for non-URL payment method support. - onValidPaymentAppForPaymentMethodName(supportedApp, nonUriMethodName); - } - } - } - if (manifestVerifiers.isEmpty()) { onAllAppsFoundAndValidated(); return;
diff --git a/components/payments/content/android/java/src/org/chromium/components/payments/UrlUtil.java b/components/payments/content/android/java/src/org/chromium/components/payments/UrlUtil.java index 9fe2b65..43082226 100644 --- a/components/payments/content/android/java/src/org/chromium/components/payments/UrlUtil.java +++ b/components/payments/content/android/java/src/org/chromium/components/payments/UrlUtil.java
@@ -34,6 +34,15 @@ } /** + * Checks whether the given URL is a valid payment method identifier. + * @param url The URL to check. + * @return Whether the given URL is a valid payment method identifier. + */ + public static boolean isValidUrlBasedPaymentMethodIdentifier(GURL url) { + return UrlUtilJni.get().isValidUrlBasedPaymentMethodIdentifier(url); + } + + /** * Checks whether the page at the given URL would typically be used for local development, e.g., * localhost. * @param url The URL to check. @@ -47,6 +56,7 @@ @NativeMethods /* package */ interface Natives { boolean isOriginAllowedToUseWebPaymentApis(GURL url); + boolean isValidUrlBasedPaymentMethodIdentifier(GURL url); boolean isLocalDevelopmentUrl(GURL url); } }
diff --git a/components/payments/content/android/url_util.cc b/components/payments/content/android/url_util.cc index 66dc734..69cbbe11 100644 --- a/components/payments/content/android/url_util.cc +++ b/components/payments/content/android/url_util.cc
@@ -17,7 +17,15 @@ JNIEnv* env, const base::android::JavaParamRef<jobject>& j_url) { std::unique_ptr<GURL> url = url::GURLAndroid::ToNativeGURL(env, j_url); - return UrlUtil::IsOriginAllowedToUseWebPaymentApis(*url); + return url && UrlUtil::IsOriginAllowedToUseWebPaymentApis(*url); +} + +// static +jboolean JNI_UrlUtil_IsValidUrlBasedPaymentMethodIdentifier( + JNIEnv* env, + const base::android::JavaParamRef<jobject>& j_url) { + std::unique_ptr<GURL> url = url::GURLAndroid::ToNativeGURL(env, j_url); + return url && UrlUtil::IsValidUrlBasedPaymentMethodIdentifier(*url); } // static @@ -25,7 +33,7 @@ JNIEnv* env, const base::android::JavaParamRef<jobject>& j_url) { std::unique_ptr<GURL> url = url::GURLAndroid::ToNativeGURL(env, j_url); - return UrlUtil::IsLocalDevelopmentUrl(*url); + return url && UrlUtil::IsLocalDevelopmentUrl(*url); } } // namespace android
diff --git a/components/payments/content/manifest_verifier.cc b/components/payments/content/manifest_verifier.cc index e07e8eb4..ab80efa0 100644 --- a/components/payments/content/manifest_verifier.cc +++ b/components/payments/content/manifest_verifier.cc
@@ -84,16 +84,6 @@ for (auto& app : apps_) { std::vector<std::string> verified_method_names; for (const auto& method : app.second->enabled_methods) { - // For non-URL payment method names, only names published by W3C should be - // supported. Keep this in sync with AndroidPaymentAppFinder.java. - if (method == methods::kBasicCard || method == methods::kInterledger || - method == methods::kPayeeCreditTransfer || - method == methods::kPayerCreditTransfer || - method == methods::kTokenizedCard) { - verified_method_names.emplace_back(method); - continue; - } - // GURL constructor may crash with some invalid unicode strings. if (!base::IsStringUTF8(method)) { log_.Warn("Payment method name \"" + method + @@ -102,6 +92,7 @@ continue; } + // Only URL payment method names are supported. GURL method_manifest_url = GURL(method); if (!UrlUtil::IsValidUrlBasedPaymentMethodIdentifier( method_manifest_url)) {
diff --git a/components/payments/content/payment_credential_enrollment_model_unittest.cc b/components/payments/content/payment_credential_enrollment_model_unittest.cc index d113285..1a56b4c4 100644 --- a/components/payments/content/payment_credential_enrollment_model_unittest.cc +++ b/components/payments/content/payment_credential_enrollment_model_unittest.cc
@@ -15,10 +15,9 @@ PaymentCredentialEnrollmentModel model; std::u16string title(u"Use Touch ID to verify and complete your purchase?"); - std::u16string description( - u"Save payment information to this device and skip bank verification " - u"next " - u"time when you use Touch ID to verify your payment with Visa ••••4444."); + std::u16string description(base::UTF8ToUTF16( + "Save payment information to this device and skip bank verification next " + "time when you use Touch ID to verify your payment with Visa ••••4444.")); std::u16string accept_button_label(u"Use Touch ID"); std::u16string cancel_button_label(u"No thanks");
diff --git a/components/payments/core/method_strings.cc b/components/payments/core/method_strings.cc index bcd0248..818f4d79 100644 --- a/components/payments/core/method_strings.cc +++ b/components/payments/core/method_strings.cc
@@ -8,18 +8,12 @@ namespace methods { // Please keep the list alphabetized. -// Each string must be on a single line to correctly generate -// MethodStrings.java. const char kAndroidPay[] = "https://android.com/pay"; const char kBasicCard[] = "basic-card"; const char kGooglePay[] = "https://google.com/pay"; const char kGooglePlayBilling[] = "https://play.google.com/billing"; -const char kInterledger[] = "interledger"; -const char kPayeeCreditTransfer[] = "payee-credit-transfer"; -const char kPayerCreditTransfer[] = "payer-credit-transfer"; const char kSecurePaymentConfirmation[] = "secure-payment-confirmation"; -const char kTokenizedCard[] = "tokenized-card"; } // namespace methods } // namespace payments
diff --git a/components/payments/core/method_strings.h b/components/payments/core/method_strings.h index 90a199f..6558a05 100644 --- a/components/payments/core/method_strings.h +++ b/components/payments/core/method_strings.h
@@ -28,26 +28,10 @@ // Google Play Billing method name. extern const char kGooglePlayBilling[]; -// Interledger method name. -// https://w3c.github.io/webpayments/proposals/interledger/ -extern const char kInterledger[]; - -// Credit Transfer method name. -// https://w3c.github.io/payment-method-credit-transfer/ -extern const char kPayeeCreditTransfer[]; - -// Credit Transfer method name. -// https://w3c.github.io/payment-method-credit-transfer/ -extern const char kPayerCreditTransfer[]; - // Secure Payment Confirmation method name. // https://github.com/rsolomakhin/secure-payment-confirmation/ extern const char kSecurePaymentConfirmation[]; -// Tokenized Card method name. -// https://w3c.github.io/webpayments-methods-tokenization/ -extern const char kTokenizedCard[]; - } // namespace methods } // namespace payments
diff --git a/components/policy/core/common/policy_map_unittest.cc b/components/policy/core/common/policy_map_unittest.cc index 484e4de..68ebdee 100644 --- a/components/policy/core/common/policy_map_unittest.cc +++ b/components/policy/core/common/policy_map_unittest.cc
@@ -36,7 +36,7 @@ const char kTestPolicyName8[] = "policy.test.8"; // Dummy error message. -const char16_t kTestError[] = u"Test error message"; +const char kTestError[] = "Test error message"; // Utility functions for the tests. void SetPolicy(PolicyMap* map, const char* name, base::Value value) { @@ -83,19 +83,20 @@ EXPECT_TRUE(expected_b.Equals(map.GetValue(kTestPolicyName1))); SetPolicy(&map, kTestPolicyName1, CreateExternalDataFetcher("dummy")); map.AddMessage(kTestPolicyName1, PolicyMap::MessageType::kError, - IDS_POLICY_STORE_STATUS_VALIDATION_ERROR, {kTestError}); + IDS_POLICY_STORE_STATUS_VALIDATION_ERROR, + {base::UTF8ToUTF16(kTestError)}); EXPECT_FALSE(map.GetValue(kTestPolicyName1)); const PolicyMap::Entry* entry = map.Get(kTestPolicyName1); ASSERT_TRUE(entry != nullptr); EXPECT_EQ(POLICY_LEVEL_MANDATORY, entry->level); EXPECT_EQ(POLICY_SCOPE_USER, entry->scope); EXPECT_EQ(POLICY_SOURCE_CLOUD, entry->source); - std::u16string error_string = - base::StrCat({u"Validation error: ", kTestError}); + std::string error_string = base::StrCat({"Validation error: ", kTestError}); PolicyMap::Entry::L10nLookupFunction lookup = base::BindRepeating( static_cast<std::u16string (*)(int)>(&base::NumberToString16)); - EXPECT_EQ(error_string, entry->GetLocalizedMessages( - PolicyMap::MessageType::kError, lookup)); + EXPECT_EQ( + base::UTF8ToUTF16(error_string), + entry->GetLocalizedMessages(PolicyMap::MessageType::kError, lookup)); EXPECT_TRUE( ExternalDataFetcher::Equals(entry->external_data_fetcher.get(), CreateExternalDataFetcher("dummy").get())); @@ -136,27 +137,28 @@ EXPECT_EQ(u"1234\n5678", entry1->GetLocalizedMessages( PolicyMap::MessageType::kError, lookup)); EXPECT_EQ( - u"This policy is deprecated. You should use the " - u"SomeNewPolicy policy instead.", + base::UTF8ToUTF16("This policy is deprecated. You should use the " + "SomeNewPolicy policy instead."), entry2->GetLocalizedMessages(PolicyMap::MessageType::kError, lookup)); map.AddMessage(kTestPolicyName2, PolicyMap::MessageType::kError, 1357); EXPECT_EQ(u"1234\n5678", entry1->GetLocalizedMessages( PolicyMap::MessageType::kError, lookup)); EXPECT_EQ( - u"1357\nThis policy is deprecated. You should use " - u"the SomeNewPolicy policy instead.", + base::UTF8ToUTF16("1357\nThis policy is deprecated. You should use " + "the SomeNewPolicy policy instead."), entry2->GetLocalizedMessages(PolicyMap::MessageType::kError, lookup)); // Test adding Error message with placeholder replacement (two args) map.AddMessage(kTestPolicyName1, PolicyMap::MessageType::kError, IDS_POLICY_DLP_CLIPBOARD_BLOCKED_ON_COPY_VM, {u"SomeSource", u"SomeDestination"}); EXPECT_EQ( - u"1234\n5678\nSharing from SomeSource to SomeDestination has " - u"been blocked by administrator policy", + base::UTF8ToUTF16( + "1234\n5678\nSharing from SomeSource to SomeDestination has " + "been blocked by administrator policy"), entry1->GetLocalizedMessages(PolicyMap::MessageType::kError, lookup)); EXPECT_EQ( - u"1357\nThis policy is deprecated. You should use " - u"the SomeNewPolicy policy instead.", + base::UTF8ToUTF16("1357\nThis policy is deprecated. You should use " + "the SomeNewPolicy policy instead."), entry2->GetLocalizedMessages(PolicyMap::MessageType::kError, lookup)); // Ensure other message types are empty @@ -190,27 +192,28 @@ EXPECT_EQ(u"1234\n5678", entry1->GetLocalizedMessages( PolicyMap::MessageType::kWarning, lookup)); EXPECT_EQ( - u"This policy is deprecated. You should use the " - u"SomeNewPolicy policy instead.", + base::UTF8ToUTF16("This policy is deprecated. You should use the " + "SomeNewPolicy policy instead."), entry2->GetLocalizedMessages(PolicyMap::MessageType::kWarning, lookup)); entry2->AddMessage(PolicyMap::MessageType::kWarning, 1357); EXPECT_EQ(u"1234\n5678", entry1->GetLocalizedMessages( PolicyMap::MessageType::kWarning, lookup)); EXPECT_EQ( - u"1357\nThis policy is deprecated. You should use " - u"the SomeNewPolicy policy instead.", + base::UTF8ToUTF16("1357\nThis policy is deprecated. You should use " + "the SomeNewPolicy policy instead."), entry2->GetLocalizedMessages(PolicyMap::MessageType::kWarning, lookup)); // Test adding Warning message with placeholder replacement (two args) entry1->AddMessage(PolicyMap::MessageType::kWarning, IDS_POLICY_DLP_CLIPBOARD_BLOCKED_ON_COPY_VM, {u"SomeSource", u"SomeDestination"}); EXPECT_EQ( - u"1234\n5678\nSharing from SomeSource to SomeDestination has " - u"been blocked by administrator policy", + base::UTF8ToUTF16( + "1234\n5678\nSharing from SomeSource to SomeDestination has " + "been blocked by administrator policy"), entry1->GetLocalizedMessages(PolicyMap::MessageType::kWarning, lookup)); EXPECT_EQ( - u"1357\nThis policy is deprecated. You should use " - u"the SomeNewPolicy policy instead.", + base::UTF8ToUTF16("1357\nThis policy is deprecated. You should use " + "the SomeNewPolicy policy instead."), entry2->GetLocalizedMessages(PolicyMap::MessageType::kWarning, lookup)); // Ensure other message types are empty @@ -244,27 +247,28 @@ EXPECT_EQ(u"1234\n5678", entry1->GetLocalizedMessages( PolicyMap::MessageType::kInfo, lookup)); EXPECT_EQ( - u"This policy is deprecated. You should use the " - u"SomeNewPolicy policy instead.", + base::UTF8ToUTF16("This policy is deprecated. You should use the " + "SomeNewPolicy policy instead."), entry2->GetLocalizedMessages(PolicyMap::MessageType::kInfo, lookup)); entry2->AddMessage(PolicyMap::MessageType::kInfo, 1357); EXPECT_EQ(u"1234\n5678", entry1->GetLocalizedMessages( PolicyMap::MessageType::kInfo, lookup)); EXPECT_EQ( - u"1357\nThis policy is deprecated. You should use " - u"the SomeNewPolicy policy instead.", + base::UTF8ToUTF16("1357\nThis policy is deprecated. You should use " + "the SomeNewPolicy policy instead."), entry2->GetLocalizedMessages(PolicyMap::MessageType::kInfo, lookup)); // Test adding Info message with placeholder replacement (two args) entry1->AddMessage(PolicyMap::MessageType::kInfo, IDS_POLICY_DLP_CLIPBOARD_BLOCKED_ON_COPY_VM, {u"SomeSource", u"SomeDestination"}); EXPECT_EQ( - u"1234\n5678\nSharing from SomeSource to SomeDestination has " - u"been blocked by administrator policy", + base::UTF8ToUTF16( + "1234\n5678\nSharing from SomeSource to SomeDestination has " + "been blocked by administrator policy"), entry1->GetLocalizedMessages(PolicyMap::MessageType::kInfo, lookup)); EXPECT_EQ( - u"1357\nThis policy is deprecated. You should use " - u"the SomeNewPolicy policy instead.", + base::UTF8ToUTF16("1357\nThis policy is deprecated. You should use " + "the SomeNewPolicy policy instead."), entry2->GetLocalizedMessages(PolicyMap::MessageType::kInfo, lookup)); // Ensure other message types are empty
diff --git a/components/policy/resources/webui/policy.html b/components/policy/resources/webui/policy.html index f3cd08c..2211ce06 100644 --- a/components/policy/resources/webui/policy.html +++ b/components/policy/resources/webui/policy.html
@@ -119,6 +119,10 @@ <div class="label">$i18n{labelVersion}</div> <div class="version"></div> </div> + <div class="status-entry" hidden> + <div class="label">$i18n{labelLastCloudReportSentTimestamp}</div> + <div class="last-cloud-report-sent-timestamp"></div> + </div> </fieldset> <div class="policy-table" id="policy-table-template" role="table"
diff --git a/components/policy/resources/webui/policy_base.js b/components/policy/resources/webui/policy_base.js index af0c8bc..b4861660 100644 --- a/components/policy/resources/webui/policy_base.js +++ b/components/policy/resources/webui/policy_base.js
@@ -199,6 +199,13 @@ status.policiesPushAvailable ? 'policiesPushOn' : 'policiesPushOff')); } + + if (status.lastCloudReportSentTimestamp) { + this.setLabelAndShow_( + '.last-cloud-report-sent-timestamp', + status.lastCloudReportSentTimestamp + ' (' + + status.timeSinceLastCloudReportSent + ')'); + } }, };
diff --git a/components/policy_strings.grdp b/components/policy_strings.grdp index 41fff5f..fc4d1bdd 100644 --- a/components/policy_strings.grdp +++ b/components/policy_strings.grdp
@@ -356,6 +356,9 @@ <message name="IDS_POLICY_LABEL_TIME_SINCE_LAST_REFRESH" desc="Label for the time since the last refresh in the policy status boxes."> Last fetched: </message> + <message name="IDS_POLICY_LABEL_LAST_CLOUD_REPORT_SENT_TIMESTAMP" desc="Label for the time when the last cloud report is sent successfully."> + Report sent: + </message> <message name="IDS_POLICY_NOT_SPECIFIED" desc="Indicates if that device attribute has not specified yet."> Not Specified </message>
diff --git a/components/policy_strings_grdp/IDS_POLICY_LABEL_LAST_CLOUD_REPORT_SENT_TIMESTAMP.png.sha1 b/components/policy_strings_grdp/IDS_POLICY_LABEL_LAST_CLOUD_REPORT_SENT_TIMESTAMP.png.sha1 new file mode 100644 index 0000000..020a3db --- /dev/null +++ b/components/policy_strings_grdp/IDS_POLICY_LABEL_LAST_CLOUD_REPORT_SENT_TIMESTAMP.png.sha1
@@ -0,0 +1 @@ +d2d18086f6ff06ae6750195cc5c18e2a6a95480a \ No newline at end of file
diff --git a/components/power_scheduler/power_mode_arbiter.cc b/components/power_scheduler/power_mode_arbiter.cc index bc0fb94..bb429f2 100644 --- a/components/power_scheduler/power_mode_arbiter.cc +++ b/components/power_scheduler/power_mode_arbiter.cc
@@ -209,12 +209,14 @@ bool should_post_update_task = false; int sequence_number = 0; scoped_refptr<base::TaskRunner> task_runner; + base::TimeTicks now = base::TimeTicks::Now(); + base::TimeTicks scheduled_time = now + timeout; + // Align to the reset task's resolution. + scheduled_time = scheduled_time.SnappedToNextTick(base::TimeTicks(), + kResetVoteTimeResolution); + { base::AutoLock lock(lock_); - base::TimeTicks scheduled_time = base::TimeTicks::Now() + timeout; - // Align to the reset task's resolution. - scheduled_time = scheduled_time.SnappedToNextTick(base::TimeTicks(), - kResetVoteTimeResolution); pending_resets_[voter] = scheduled_time; // Only post a new task if there isn't one scheduled to run earlier yet. // This reduces the number of posted callbacks in situations where the @@ -235,7 +237,7 @@ FROM_HERE, base::BindOnce(&PowerModeArbiter::UpdatePendingResets, base::Unretained(this), sequence_number), - timeout); + scheduled_time - now); } }
diff --git a/components/prefs/scoped_user_pref_update_unittest.cc b/components/prefs/scoped_user_pref_update_unittest.cc index fa1dc71..431fad1 100644 --- a/components/prefs/scoped_user_pref_update_unittest.cc +++ b/components/prefs/scoped_user_pref_update_unittest.cc
@@ -102,9 +102,9 @@ std::string pref_name = "mypref"; prefs_.registry()->RegisterDictionaryPref(pref_name, std::move(defaults)); - EXPECT_EQ(2u, prefs_.GetDictionary(pref_name)->size()); + EXPECT_EQ(2u, prefs_.GetDictionary(pref_name)->DictSize()); DictionaryPrefUpdate update(&prefs_, pref_name); update->SetKey("thirdkey", base::Value("value")); - EXPECT_EQ(3u, prefs_.GetDictionary(pref_name)->size()); + EXPECT_EQ(3u, prefs_.GetDictionary(pref_name)->DictSize()); }
diff --git a/components/safe_browsing/content/renderer/phishing_classifier/phishing_term_feature_extractor_unittest.cc b/components/safe_browsing/content/renderer/phishing_classifier/phishing_term_feature_extractor_unittest.cc index 1df89d98..f647c176 100644 --- a/components/safe_browsing/content/renderer/phishing_classifier/phishing_term_feature_extractor_unittest.cc +++ b/components/safe_browsing/content/renderer/phishing_classifier/phishing_term_feature_extractor_unittest.cc
@@ -263,15 +263,19 @@ // Chinese translation of the phrase "hello goodbye hello goodbye". This tests // that we can correctly separate terms in languages that don't use spaces. - page_text = u"你好再见你好再见"; + page_text = base::UTF8ToUTF16( + "\xe4\xbd\xa0\xe5\xa5\xbd\xe5\x86\x8d\xe8\xa7\x81" + "\xe4\xbd\xa0\xe5\xa5\xbd\xe5\x86\x8d\xe8\xa7\x81"); expected_features.Clear(); expected_features.AddBooleanFeature(features::kPageTerm + - std::string("你好")); + std::string("\xe4\xbd\xa0\xe5\xa5\xbd")); expected_features.AddBooleanFeature(features::kPageTerm + - std::string("再见")); + std::string("\xe5\x86\x8d\xe8\xa7\x81")); expected_shingle_hashes.clear(); expected_shingle_hashes.insert( - MurmurHash3String("你好 再见 你好 再见 ", kMurmurHash3Seed)); + MurmurHash3String("\xe4\xbd\xa0\xe5\xa5\xbd \xe5\x86\x8d\xe8\xa7\x81 " + "\xe4\xbd\xa0\xe5\xa5\xbd \xe5\x86\x8d\xe8\xa7\x81 ", + kMurmurHash3Seed)); features.Clear(); shingle_hashes.clear();
diff --git a/components/search_engines/template_url_unittest.cc b/components/search_engines/template_url_unittest.cc index 2cbb292..79ec26e 100644 --- a/components/search_engines/template_url_unittest.cc +++ b/components/search_engines/template_url_unittest.cc
@@ -522,14 +522,14 @@ const std::string url; const std::string expected_result; } test_data[] = { - {"BIG5", u"悽", "http://foo/?{searchTerms}{inputEncoding}", + {"BIG5", u"\x60BD", "http://foo/?{searchTerms}{inputEncoding}", "http://foo/?%B1~BIG5"}, {"UTF-8", u"blah", "http://foo/?{searchTerms}{inputEncoding}", "http://foo/?blahUTF-8"}, - {"Shift_JIS", u"あ", "http://foo/{searchTerms}/bar", - "http://foo/%82%A0/bar"}, - {"Shift_JIS", u"あ い", "http://foo/{searchTerms}/bar", - "http://foo/%82%A0%20%82%A2/bar"}, + {"Shift_JIS", base::UTF8ToUTF16("\xe3\x81\x82"), + "http://foo/{searchTerms}/bar", "http://foo/%82%A0/bar"}, + {"Shift_JIS", base::UTF8ToUTF16("\xe3\x81\x82 \xe3\x81\x84"), + "http://foo/{searchTerms}/bar", "http://foo/%82%A0%20%82%A2/bar"}, }; TemplateURLData data; for (size_t i = 0; i < base::size(test_data); ++i) { @@ -558,27 +558,27 @@ } test_data[] = { // First and third encodings are valid. First is used. {{"windows-1251", "cp-866", "UTF-8"}, - u"я", + base::UTF8ToUTF16("\xD1\x8F"), "http://foo/?{searchTerms}{inputEncoding}", "http://foo/?%FFwindows-1251"}, // Second and third encodings are valid, second is used. {{"cp-866", "GB2312", "UTF-8"}, - u"狗", + base::UTF8ToUTF16("\xE7\x8B\x97"), "http://foo/?{searchTerms}{inputEncoding}", "http://foo/?%B9%B7GB2312"}, // Second and third encodings are valid in another order, second is used. {{"cp-866", "UTF-8", "GB2312"}, - u"狗", + base::UTF8ToUTF16("\xE7\x8B\x97"), "http://foo/?{searchTerms}{inputEncoding}", "http://foo/?%E7%8B%97UTF-8"}, // Both encodings are invalid, fallback to UTF-8. {{"cp-866", "windows-1251"}, - u"狗", + base::UTF8ToUTF16("\xE7\x8B\x97"), "http://foo/?{searchTerms}{inputEncoding}", "http://foo/?%E7%8B%97UTF-8"}, // No encodings are given, fallback to UTF-8. {{}, - u"狗", + base::UTF8ToUTF16("\xE7\x8B\x97"), "http://foo/?{searchTerms}{inputEncoding}", "http://foo/?%E7%8B%97UTF-8"}, }; @@ -1854,7 +1854,9 @@ ASSERT_EQ(u"blah", TemplateURL::GenerateKeyword(GURL("http://blah/"))); // Don't generate the empty string. ASSERT_EQ(u"www.", TemplateURL::GenerateKeyword(GURL("http://www."))); - ASSERT_EQ(u"абв", TemplateURL::GenerateKeyword(GURL("http://xn--80acd"))); + ASSERT_EQ( + base::UTF8ToUTF16("\xd0\xb0\xd0\xb1\xd0\xb2"), + TemplateURL::GenerateKeyword(GURL("http://xn--80acd"))); // Generated keywords must always be in lowercase, because TemplateURLs always // converts keywords to lowercase in its constructor and TemplateURLService
diff --git a/components/signin/core/browser/account_reconcilor.cc b/components/signin/core/browser/account_reconcilor.cc index 19af650..57bb3635 100644 --- a/components/signin/core/browser/account_reconcilor.cc +++ b/components/signin/core/browser/account_reconcilor.cc
@@ -398,19 +398,8 @@ identity_manager_->GetAccountsCookieMutator()->TriggerCookieJarUpdate(); } -void AccountReconcilor::PerformMergeAction(const CoreAccountId& account_id) { - DCHECK(!IsMultiloginEndpointEnabled()); - reconcile_is_noop_ = false; - VLOG(1) << "AccountReconcilor::PerformMergeAction: " << account_id; - identity_manager_->GetAccountsCookieMutator()->AddAccountToCookie( - account_id, delegate_->GetGaiaApiSource(), - base::BindOnce(&AccountReconcilor::OnAddAccountToCookieCompleted, - weak_factory_.GetWeakPtr())); -} - void AccountReconcilor::PerformSetCookiesAction( const signin::MultiloginParameters& parameters) { - DCHECK(IsMultiloginEndpointEnabled()); reconcile_is_noop_ = false; VLOG(1) << "AccountReconcilor::PerformSetCookiesAction: " << base::JoinString(ToStringList(parameters.accounts_to_send), " "); @@ -468,7 +457,6 @@ // Begin reconciliation. Reset initial states. SetState(AccountReconcilorState::ACCOUNT_RECONCILOR_RUNNING); - add_to_cookie_.clear(); reconcile_start_time_ = base::Time::Now(); is_reconcile_started_ = true; error_during_last_reconcile_ = GoogleServiceAuthError::AuthErrorNone(); @@ -509,7 +497,6 @@ const CoreAccountId& primary_account, const std::vector<CoreAccountId>& chrome_accounts, std::vector<gaia::ListedAccount>&& gaia_accounts) { - DCHECK(IsMultiloginEndpointEnabled()); DCHECK(!set_accounts_in_progress_); DCHECK(!log_out_in_progress_); DCHECK_EQ(AccountReconcilorState::ACCOUNT_RECONCILOR_RUNNING, state_); @@ -611,13 +598,10 @@ // let it complete. Adding accounts to the cookie will trigger new // notifications anyway, and these will be handled in a new reconciliation // cycle. See https://crbug.com/923716 - if (IsMultiloginEndpointEnabled()) { - if (set_accounts_in_progress_) - return; - } else { - if (!add_to_cookie_.empty()) - return; - } + // + // TODO(droger): Should we also check if |logout_in_progress_|? + if (set_accounts_in_progress_) + return; if (!is_reconcile_started_) { StartReconcile(Trigger::kCookieChange); @@ -678,13 +662,8 @@ return; } - if (IsMultiloginEndpointEnabled()) { - FinishReconcileWithMultiloginEndpoint(primary_account, chrome_accounts, - std::move(verified_gaia_accounts)); - } else { - FinishReconcile(primary_account, chrome_accounts, - std::move(verified_gaia_accounts)); - } + FinishReconcileWithMultiloginEndpoint(primary_account, chrome_accounts, + std::move(verified_gaia_accounts)); } void AccountReconcilor::OnAccountsCookieDeletedByUserAction() { @@ -752,149 +731,15 @@ } } -void AccountReconcilor::FinishReconcile( - const CoreAccountId& primary_account, - const std::vector<CoreAccountId>& chrome_accounts, - std::vector<gaia::ListedAccount>&& gaia_accounts) { - DCHECK(!IsMultiloginEndpointEnabled()); - VLOG(1) << "AccountReconcilor::FinishReconcile"; - DCHECK(add_to_cookie_.empty()); - DCHECK(delegate_->IsUnknownInvalidAccountInCookieAllowed()) - << "Only supported in UPDATE mode"; - - size_t number_gaia_accounts = gaia_accounts.size(); - // If there are any accounts in the gaia cookie but not in chrome, then - // those accounts need to be removed from the cookie. This means we need - // to blow the cookie away. - int removed_from_cookie = 0; - for (size_t i = 0; i < number_gaia_accounts; ++i) { - if (gaia_accounts[i].valid && - !base::Contains(chrome_accounts, gaia_accounts[i].id)) { - ++removed_from_cookie; - } - } - - CoreAccountId first_account = delegate_->GetFirstGaiaAccountForReconcile( - chrome_accounts, gaia_accounts, primary_account, first_execution_, - removed_from_cookie > 0); - bool first_account_mismatch = - (number_gaia_accounts > 0) && (first_account != gaia_accounts[0].id); - - bool rebuild_cookie = first_account_mismatch || (removed_from_cookie > 0); - std::vector<gaia::ListedAccount> original_gaia_accounts = gaia_accounts; - if (rebuild_cookie) { - VLOG(1) << "AccountReconcilor::FinishReconcile: rebuild cookie"; - // Really messed up state. Blow away the gaia cookie completely and - // rebuild it, making sure the primary account as specified by the - // IdentityManager is the first session in the gaia cookie. - log_out_in_progress_ = true; - PerformLogoutAllAccountsAction(); - gaia_accounts.clear(); - } - - if (first_account.empty()) { - DCHECK(!delegate_->ShouldAbortReconcileIfPrimaryHasError()); - auto revoke_option = - delegate_->ShouldRevokeTokensIfNoPrimaryAccount() - ? AccountReconcilorDelegate::RevokeTokenOption::kRevoke - : AccountReconcilorDelegate::RevokeTokenOption::kDoNotRevoke; - reconcile_is_noop_ = !RevokeAllSecondaryTokens( - identity_manager_, revoke_option, primary_account, - signin_metrics::SourceForRefreshTokenOperation:: - kAccountReconcilor_Reconcile); - } else { - // Create a list of accounts that need to be added to the Gaia cookie. - if (base::Contains(chrome_accounts, first_account)) { - add_to_cookie_.push_back(first_account); - } else { - // If the first account is not empty and not in chrome_accounts, it is - // impossible to rebuild it. It must be already the current default - // account, and no logout can happen. - DCHECK_EQ(gaia_accounts[0].id, first_account); - DCHECK(!rebuild_cookie); - } - for (size_t i = 0; i < chrome_accounts.size(); ++i) { - if (chrome_accounts[i] != first_account) - add_to_cookie_.push_back(chrome_accounts[i]); - } - } - - // For each account known to chrome, PerformMergeAction() if the account is - // not already in the cookie jar or its state is invalid, or signal merge - // completed otherwise. Make a copy of |add_to_cookie_| since calls - // to OnAddAccountToCookieCompleted() will change the array. - std::vector<CoreAccountId> add_to_cookie_copy = add_to_cookie_; - int added_to_cookie = 0; - for (size_t i = 0; i < add_to_cookie_copy.size(); ++i) { - if (ContainsGaiaAccount(gaia_accounts, add_to_cookie_copy[i])) { - OnAddAccountToCookieCompleted(add_to_cookie_copy[i], - GoogleServiceAuthError::AuthErrorNone()); - } else { - PerformMergeAction(add_to_cookie_copy[i]); - if (!ContainsGaiaAccount(original_gaia_accounts, add_to_cookie_copy[i])) { - added_to_cookie++; - } - } - } - - signin_metrics::LogSigninAccountReconciliation( - chrome_accounts.size(), added_to_cookie, removed_from_cookie, - !first_account_mismatch, first_execution_, number_gaia_accounts); - first_execution_ = false; - CalculateIfMergeSessionReconcileIsDone(); - if (!is_reconcile_started_) - delegate_->OnReconcileFinished(first_account); - ScheduleStartReconcileIfChromeAccountsChanged(); -} - void AccountReconcilor::AbortReconcile() { VLOG(1) << "AccountReconcilor::AbortReconcile: try again later"; log_out_in_progress_ = false; - if (IsMultiloginEndpointEnabled()) { - set_accounts_in_progress_ = false; - CalculateIfMultiloginReconcileIsDone(); - } else { - add_to_cookie_.clear(); - CalculateIfMergeSessionReconcileIsDone(); - } - + set_accounts_in_progress_ = false; + CalculateIfMultiloginReconcileIsDone(); DCHECK(!is_reconcile_started_); DCHECK(!timer_->IsRunning()); } -void AccountReconcilor::CalculateIfMergeSessionReconcileIsDone() { - DCHECK(!IsMultiloginEndpointEnabled()); - base::TimeDelta duration = base::Time::Now() - reconcile_start_time_; - // Record the duration if reconciliation was underway and now it is over. - if (is_reconcile_started_ && add_to_cookie_.empty() && - !log_out_in_progress_) { - bool was_last_reconcile_successful = - (error_during_last_reconcile_.state() == - GoogleServiceAuthError::State::NONE); - signin_metrics::LogSigninAccountReconciliationDuration( - duration, was_last_reconcile_successful); - - // Reconciliation has actually finished (and hence stop the timer), but it - // may have ended in some failures. Pass this information to the - // |delegate_|. - timer_->Stop(); - if (!was_last_reconcile_successful) { - // Note: This is the only call to |OnReconcileError| in this file. We MUST - // make sure that we do not call |OnReconcileError| multiple times in the - // same reconciliation batch. - // The enclosing if-condition |is_reconcile_started_ && - // add_to_cookie_.empty()| represents the halting condition for one batch - // of reconciliation. - delegate_->OnReconcileError(error_during_last_reconcile_); - } - } - - is_reconcile_started_ = !add_to_cookie_.empty() || log_out_in_progress_; - if (!is_reconcile_started_) - VLOG(1) - << "AccountReconcilor::CalculateIfMergeSessionReconcileIsDone: done"; -} - void AccountReconcilor::ScheduleStartReconcileIfChromeAccountsChanged() { if (is_reconcile_started_) return; @@ -919,25 +764,12 @@ } } -// Remove the account from the list that is being merged. -bool AccountReconcilor::MarkAccountAsAddedToCookie( - const CoreAccountId& account_id) { - for (auto i = add_to_cookie_.begin(); i != add_to_cookie_.end(); ++i) { - if (account_id == *i) { - add_to_cookie_.erase(i); - return true; - } - } - return false; -} - bool AccountReconcilor::IsIdentityManagerReady() { return identity_manager_->AreRefreshTokensLoaded(); } void AccountReconcilor::OnSetAccountsInCookieCompleted( signin::SetAccountsInCookieResult result) { - DCHECK(IsMultiloginEndpointEnabled()); VLOG(1) << "AccountReconcilor::OnSetAccountsInCookieCompleted: " << "Error was " << static_cast<int>(result); @@ -963,7 +795,6 @@ } void AccountReconcilor::CalculateIfMultiloginReconcileIsDone() { - DCHECK(IsMultiloginEndpointEnabled()); DCHECK(!set_accounts_in_progress_); DCHECK(!log_out_in_progress_); VLOG(1) << "AccountReconcilor::CalculateIfMultiloginReconcileIsDone: " @@ -985,27 +816,6 @@ duration, was_last_reconcile_successful); } -void AccountReconcilor::OnAddAccountToCookieCompleted( - const CoreAccountId& account_id, - const GoogleServiceAuthError& error) { - DCHECK(!IsMultiloginEndpointEnabled()); - VLOG(1) << "AccountReconcilor::OnAddAccountToCookieCompleted: " - << "Account added: " << account_id << ", " - << "Error was " << error.ToString(); - // Always listens to GaiaCookieManagerService. Only proceed if reconciling. - if (is_reconcile_started_ && MarkAccountAsAddedToCookie(account_id)) { - // We may have seen a series of errors during reconciliation. Delegates may - // rely on the severity of the last seen error (see |OnReconcileError|) and - // hence do not override a persistent error, if we have seen one. - if (error.state() != GoogleServiceAuthError::State::NONE && - !error_during_last_reconcile_.IsPersistentError()) { - error_during_last_reconcile_ = error; - } - CalculateIfMergeSessionReconcileIsDone(); - ScheduleStartReconcileIfChromeAccountsChanged(); - } -} - void AccountReconcilor::OnLogOutFromCookieCompleted( const GoogleServiceAuthError& error) { VLOG(1) << "AccountReconcilor::OnLogOutFromCookieCompleted: " @@ -1022,13 +832,8 @@ !error_during_last_reconcile_.IsPersistentError()) { error_during_last_reconcile_ = error; } - if (IsMultiloginEndpointEnabled()) { - CalculateIfMultiloginReconcileIsDone(); - ScheduleStartReconcileIfChromeAccountsChanged(); - } else { - CalculateIfMergeSessionReconcileIsDone(); - ScheduleStartReconcileIfChromeAccountsChanged(); - } + CalculateIfMultiloginReconcileIsDone(); + ScheduleStartReconcileIfChromeAccountsChanged(); } } @@ -1091,15 +896,11 @@ // Will stop reconciliation and inform |delegate_| about // |error_during_last_reconcile_|, through - // |CalculateIfMergeSessionReconcileIsDone|. + // |CalculateIfReconcileIsDone|. AbortReconcile(); DCHECK(!timer_->IsRunning()); } -bool AccountReconcilor::IsMultiloginEndpointEnabled() const { - return delegate_->IsMultiloginEndpointEnabled(); -} - bool AccountReconcilor::CookieNeedsUpdate( const signin::MultiloginParameters& parameters, const std::vector<gaia::ListedAccount>& existing_accounts) {
diff --git a/components/signin/core/browser/account_reconcilor.h b/components/signin/core/browser/account_reconcilor.h index e34e410..0052728 100644 --- a/components/signin/core/browser/account_reconcilor.h +++ b/components/signin/core/browser/account_reconcilor.h
@@ -127,8 +127,6 @@ bool IsReconcileBlocked() const; protected: - void OnAddAccountToCookieCompleted(const CoreAccountId& account_id, - const GoogleServiceAuthError& error); void OnSetAccountsInCookieCompleted(signin::SetAccountsInCookieResult result); void OnLogOutFromCookieCompleted(const GoogleServiceAuthError& error); @@ -137,6 +135,7 @@ friend class DiceBrowserTest; friend class BaseAccountReconcilorTestTable; friend class AccountReconcilorThrottlerTest; + friend class AccountReconcilorTestForceDiceMigration; FRIEND_TEST_ALL_PREFIXES(AccountReconcilorTestForceDiceMigration, TableRowTestCheckNoOp); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorMirrorTest, @@ -152,21 +151,18 @@ FRIEND_TEST_ALL_PREFIXES(AccountReconcilorTestMiceMultilogin, TableRowTest); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorMiceTest, AccountReconcilorStateScheduled); - FRIEND_TEST_ALL_PREFIXES(AccountReconcilorDiceEndpointParamTest, + FRIEND_TEST_ALL_PREFIXES(AccountReconcilorDiceTest, DiceTokenServiceRegistration); - FRIEND_TEST_ALL_PREFIXES(AccountReconcilorDiceEndpointParamTest, + FRIEND_TEST_ALL_PREFIXES(AccountReconcilorDiceTest, DiceReconcileWithoutSignin); - FRIEND_TEST_ALL_PREFIXES(AccountReconcilorDiceEndpointParamTest, - DiceReconcileNoop); - FRIEND_TEST_ALL_PREFIXES(AccountReconcilorDiceEndpointParamTest, + FRIEND_TEST_ALL_PREFIXES(AccountReconcilorDiceTest, DiceReconcileNoop); + FRIEND_TEST_ALL_PREFIXES(AccountReconcilorDiceTest, DiceLastKnownFirstAccount); - FRIEND_TEST_ALL_PREFIXES(AccountReconcilorDiceEndpointParamTest, - UnverifiedAccountNoop); - FRIEND_TEST_ALL_PREFIXES(AccountReconcilorDiceEndpointParamTest, - UnverifiedAccountMerge); - FRIEND_TEST_ALL_PREFIXES(AccountReconcilorDiceEndpointParamTest, + FRIEND_TEST_ALL_PREFIXES(AccountReconcilorDiceTest, UnverifiedAccountNoop); + FRIEND_TEST_ALL_PREFIXES(AccountReconcilorDiceTest, UnverifiedAccountMerge); + FRIEND_TEST_ALL_PREFIXES(AccountReconcilorDiceTest, HandleSigninDuringReconcile); - FRIEND_TEST_ALL_PREFIXES(AccountReconcilorDiceEndpointParamTest, + FRIEND_TEST_ALL_PREFIXES(AccountReconcilorDiceTest, DiceReconcileReuseGaiaFirstAccount); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorTest, DiceDeleteCookie); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorMirrorTest, TokensNotLoaded); @@ -280,7 +276,6 @@ // All actions with side effects, only doing meaningful work if account // consistency is enabled. Virtual so that they can be overridden in tests. - virtual void PerformMergeAction(const CoreAccountId& account_id); virtual void PerformLogoutAllAccountsAction(); virtual void PerformSetCookiesAction( const signin::MultiloginParameters& parameters); @@ -292,15 +287,11 @@ const std::vector<CoreAccountId>& chrome_accounts, std::vector<gaia::ListedAccount>&& gaia_accounts); void AbortReconcile(); - void CalculateIfMergeSessionReconcileIsDone(); void ScheduleStartReconcileIfChromeAccountsChanged(); // Returns the list of valid accounts from the TokenService. std::vector<CoreAccountId> LoadValidAccountsFromTokenService() const; - // Note internally that this |account_id| is added to the cookie jar. - bool MarkAccountAsAddedToCookie(const CoreAccountId& account_id); - // The reconcilor only starts when the token service is ready. bool IsIdentityManagerReady(); @@ -334,9 +325,6 @@ void HandleReconcileTimeout(); - // Returns true is multilogin endpoint can be enabled. - bool IsMultiloginEndpointEnabled() const; - // Returns true if current array of existing accounts in cookie is different // from the desired one. If this returns false, the multilogin call would be a // no-op. @@ -396,7 +384,6 @@ bool reconcile_is_noop_ = true; // Used during reconcile action. - std::vector<CoreAccountId> add_to_cookie_; // Progress of AddAccount calls. bool set_accounts_in_progress_ = false; // Progress of SetAccounts calls. bool log_out_in_progress_ = false; // Progress of LogOut calls. bool chrome_accounts_changed_ = false;
diff --git a/components/signin/core/browser/account_reconcilor_delegate.cc b/components/signin/core/browser/account_reconcilor_delegate.cc index a16384a0..4c64dbd 100644 --- a/components/signin/core/browser/account_reconcilor_delegate.cc +++ b/components/signin/core/browser/account_reconcilor_delegate.cc
@@ -17,10 +17,6 @@ return false; } -bool AccountReconcilorDelegate::IsMultiloginEndpointEnabled() const { - return true; -} - gaia::GaiaSource AccountReconcilorDelegate::GetGaiaApiSource() const { NOTREACHED() << "Reconcile is not enabled, no Gaia API calls should be made."; return gaia::GaiaSource::kChrome;
diff --git a/components/signin/core/browser/account_reconcilor_delegate.h b/components/signin/core/browser/account_reconcilor_delegate.h index 7a6ecd7..e6ad19f 100644 --- a/components/signin/core/browser/account_reconcilor_delegate.h +++ b/components/signin/core/browser/account_reconcilor_delegate.h
@@ -40,11 +40,6 @@ // false. virtual bool IsReconcileEnabled() const; - // Returns whether the OAuth multilogin endpoint can be used to build the Gaia - // cookies. - // Default implementation returns true. - virtual bool IsMultiloginEndpointEnabled() const; - // Returns the value to set in the "source" parameter for Gaia API calls. virtual gaia::GaiaSource GetGaiaApiSource() const;
diff --git a/components/signin/core/browser/account_reconcilor_unittest.cc b/components/signin/core/browser/account_reconcilor_unittest.cc index ed53b53e..4933f0b 100644 --- a/components/signin/core/browser/account_reconcilor_unittest.cc +++ b/components/signin/core/browser/account_reconcilor_unittest.cc
@@ -175,7 +175,6 @@ SigninClient* client, std::unique_ptr<signin::AccountReconcilorDelegate> delegate); - MOCK_METHOD1(PerformMergeAction, void(const CoreAccountId& account_id)); MOCK_METHOD0(PerformLogoutAllAccountsAction, void()); MOCK_METHOD1(PerformSetCookiesAction, void(const signin::MultiloginParameters& parameters)); @@ -252,10 +251,6 @@ CoreAccountId PickAccountIdForAccount(const std::string& gaia_id, const std::string& username); - void SimulateAddAccountToCookieCompleted(AccountReconcilor* reconcilor, - const CoreAccountId& account_id, - const GoogleServiceAuthError& error); - void SimulateSetAccountsInCookieCompleted( AccountReconcilor* reconcilor, signin::SetAccountsInCookieResult result); @@ -379,13 +374,6 @@ gaia_id, username); } -void AccountReconcilorTest::SimulateAddAccountToCookieCompleted( - AccountReconcilor* reconcilor, - const CoreAccountId& account_id, - const GoogleServiceAuthError& error) { - reconcilor->OnAddAccountToCookieCompleted(account_id, error); -} - void AccountReconcilorTest::SimulateSetAccountsInCookieCompleted( AccountReconcilor* reconcilor, signin::SetAccountsInCookieResult result) { @@ -437,9 +425,6 @@ const char* gaia_api_calls; const char* tokens_after_reconcile; const char* cookies_after_reconcile; - const char* gaia_api_calls_multilogin; - const char* tokens_after_reconcile_multilogin; - const char* cookies_after_reconcile_multilogin; // Int represents AccountReconcilorDelegate::InconsistencyReason. const int inconsistency_reason; }; @@ -480,26 +465,7 @@ class BaseAccountReconcilorTestTable : public AccountReconcilorTest { protected: - BaseAccountReconcilorTestTable(const AccountReconcilorTestTableParam& param) - : BaseAccountReconcilorTestTable(param.tokens, - param.cookies, - param.is_first_reconcile, - param.gaia_api_calls, - param.tokens_after_reconcile, - param.cookies_after_reconcile) {} - - BaseAccountReconcilorTestTable(const char* tokens, - const char* cookies, - IsFirstReconcile is_first_reconcile, - const char* gaia_api_calls, - const char* tokens_after_reconcile, - const char* cookies_after_reconcile) - : tokens_(tokens), - cookies_(cookies), - is_first_reconcile_(is_first_reconcile), - gaia_api_calls_(gaia_api_calls), - tokens_after_reconcile_(tokens_after_reconcile), - cookies_after_reconcile_(cookies_after_reconcile) { + BaseAccountReconcilorTestTable() { accounts_['A'] = {"a@gmail.com", signin::GetTestGaiaIdForEmail("a@gmail.com")}; accounts_['B'] = {"b@gmail.com", @@ -634,111 +600,11 @@ identity_test_env()->SetFreshnessOfAccountsInGaiaCookie(false); } -#if BUILDFLAG(ENABLE_DICE_SUPPORT) - void RunReconcile() { - // Setup cookies. - std::vector<Cookie> cookies = ParseCookieString(cookies_); - ConfigureCookieManagerService(cookies); - - // Call list accounts now so that the next call completes synchronously. - identity_test_env()->identity_manager()->GetAccountsInCookieJar(); - base::RunLoop().RunUntilIdle(); - - // Setup tokens. This triggers listing cookies so we need to setup cookies - // before that. - SetupTokens(tokens_); - - // Setup expectations. - testing::InSequence mock_sequence; - bool logout_action = false; - for (int i = 0; gaia_api_calls_[i] != '\0'; ++i) { - if (gaia_api_calls_[i] == 'X') { - logout_action = true; - EXPECT_CALL(*GetMockReconcilor(), PerformLogoutAllAccountsAction()) - .Times(1); - cookies.clear(); - continue; - } - std::string cookie(1, gaia_api_calls_[i]); - CoreAccountId account_id_for_cookie = PickAccountIdForAccount( - accounts_[cookie[0]].gaia_id, accounts_[cookie[0]].email); - EXPECT_CALL(*GetMockReconcilor(), - PerformMergeAction(account_id_for_cookie)) - .Times(1); - // MergeSession fixes an existing cookie or appends it at the end. - auto it = - std::find(cookies.begin(), cookies.end(), - Cookie{accounts_[cookie[0]].gaia_id, false /* is_valid */}); - if (it == cookies.end()) - cookies.push_back({accounts_[cookie[0]].gaia_id, true}); - else - it->is_valid = true; - } - if (!logout_action) { - EXPECT_CALL(*GetMockReconcilor(), PerformLogoutAllAccountsAction()) - .Times(0); - } - - // Check the expected cookies after reconcile. - std::vector<Cookie> expected_cookies = - ParseCookieString(cookies_after_reconcile_); - ASSERT_EQ(expected_cookies, cookies); - - // Reconcile. - AccountReconcilor* reconcilor = GetMockReconcilor(); - ASSERT_TRUE(reconcilor->first_execution_); - reconcilor->first_execution_ = - is_first_reconcile_ == IsFirstReconcile::kFirst; - reconcilor->StartReconcile(AccountReconcilor::Trigger::kCookieChange); - for (int i = 0; gaia_api_calls_[i] != '\0'; ++i) { - if (gaia_api_calls_[i] == 'X') { - SimulateLogOutFromCookieCompleted( - reconcilor, GoogleServiceAuthError::AuthErrorNone()); - continue; - } - CoreAccountId account_id = - PickAccountIdForAccount(accounts_[gaia_api_calls_[i]].gaia_id, - accounts_[gaia_api_calls_[i]].email); - SimulateAddAccountToCookieCompleted( - reconcilor, account_id, GoogleServiceAuthError::AuthErrorNone()); - } - ASSERT_FALSE(reconcilor->is_reconcile_started_); - - if (tokens_ == tokens_after_reconcile_) { - EXPECT_EQ(signin_metrics::ACCOUNT_RECONCILOR_OK, reconcilor->GetState()); - } else { - // If the tokens were changed by the reconcile, a new reconcile should be - // scheduled. - EXPECT_EQ(signin_metrics::ACCOUNT_RECONCILOR_SCHEDULED, - reconcilor->GetState()); - } - - VerifyCurrentTokens(ParseTokenString(tokens_after_reconcile_)); - - testing::Mock::VerifyAndClearExpectations(GetMockReconcilor()); - - // Another reconcile is sometimes triggered if Chrome accounts have changed. - // Allow it to finish. - EXPECT_CALL(*GetMockReconcilor(), PerformMergeAction(testing::_)) - .WillRepeatedly(testing::Return()); - EXPECT_CALL(*GetMockReconcilor(), PerformLogoutAllAccountsAction()) - .WillRepeatedly(testing::Return()); - ConfigureCookieManagerService({}); - base::RunLoop().RunUntilIdle(); - } -#endif // BUILDFLAG(ENABLE_DICE_SUPPORT) - std::string GaiaIdForAccountKey(char account_key) { return accounts_[account_key].gaia_id; } std::map<char, Account> accounts_; - const char* tokens_; - const char* cookies_; - IsFirstReconcile is_first_reconcile_; - const char* gaia_api_calls_; - const char* tokens_after_reconcile_; - const char* cookies_after_reconcile_; }; // Parameterized version of AccountReconcilorTest. @@ -746,35 +612,24 @@ : public BaseAccountReconcilorTestTable, public ::testing::WithParamInterface<AccountReconcilorTestTableParam> { protected: - AccountReconcilorTestTable() : BaseAccountReconcilorTestTable(GetParam()) {} + AccountReconcilorTestTable() = default; // Checks that reconcile is idempotent. void CheckReconcileIdempotent( const std::vector<AccountReconcilorTestTableParam>& params, - const AccountReconcilorTestTableParam& param, - bool multilogin) { + const AccountReconcilorTestTableParam& param) { // Simulate another reconcile based on the results of this one: find the // corresponding row in the table and check that it does nothing. for (const AccountReconcilorTestTableParam& row : params) { if (row.is_first_reconcile == IsFirstReconcile::kFirst) continue; - if (!((strcmp(row.tokens, param.tokens_after_reconcile) == 0 && - strcmp(row.cookies, param.cookies_after_reconcile) == 0 && - !multilogin) || - (strcmp(row.tokens, param.tokens_after_reconcile_multilogin) == 0 && - strcmp(row.cookies, param.cookies_after_reconcile_multilogin) == - 0 && - multilogin))) { + if (!(strcmp(row.tokens, param.tokens_after_reconcile) == 0 && + strcmp(row.cookies, param.cookies_after_reconcile) == 0)) { continue; } - if (multilogin) { - EXPECT_STREQ(row.tokens, row.tokens_after_reconcile_multilogin); - EXPECT_STREQ(row.cookies, row.cookies_after_reconcile_multilogin); - } else { - EXPECT_STREQ(row.tokens, row.tokens_after_reconcile); - EXPECT_STREQ(row.cookies, row.cookies_after_reconcile); - } + EXPECT_STREQ(row.tokens, row.tokens_after_reconcile); + EXPECT_STREQ(row.cookies, row.cookies_after_reconcile); return; } @@ -879,248 +734,285 @@ // x: The next cookie is marked "invalid". // - First Run: true if this is the first reconcile (i.e. Chrome startup). // ------------------------------------------------------------------------- - // Tokens|Cookies|First Run|Gaia calls|Tokens aft.|Cookies aft.|M.calls| M.Tokens aft.| M.Cookies aft.| AccountReconcilorDelegate::InconsistencyReason | + // Tokens|Cookies|First Run|Gaia calls|Tokens aft.|Cookies aft.|AccountReconcilorDelegate::InconsistencyReason | // ------------------------------------------------------------------------- // First reconcile (Chrome restart): Rebuild the Gaia cookie to match the // tokens. Make the Sync account the default account in the Gaia cookie. // Sync enabled. - { "", "A", IsFirstReconcile::kBoth, "X", "", "", "U", "", "", 3}, - { "*AB", "AB", IsFirstReconcile::kBoth, "", "*AB", "AB", "", "*AB", "AB", 0}, - { "*A", "A", IsFirstReconcile::kBoth, "", "*A", "A", "", "*A" , "A", 0}, - { "*A", "", IsFirstReconcile::kBoth, "A", "*A", "A", "PA", "*A" , "A", 1}, - { "*A", "B", IsFirstReconcile::kBoth, "XA", "*A", "A", "UA", "*A" , "A", 1}, - { "*A", "AB", IsFirstReconcile::kBoth, "XA", "*A", "A", "UA", "*A" , "A", 5}, - { "*AB", "BA", IsFirstReconcile::kFirst, "XAB", "*AB", "AB", "UAB", "*AB", "AB", 7}, - { "*AB", "BA", IsFirstReconcile::kNotFirst, "", "*AB", "BA", "", "*AB", "BA", 0}, + { "", "A", IsFirstReconcile::kBoth, "U", "", "", 3}, + { "*AB", "AB", IsFirstReconcile::kBoth, "", "*AB", "AB", 0}, + { "*A", "A", IsFirstReconcile::kBoth, "", "*A" , "A", 0}, + { "*A", "", IsFirstReconcile::kBoth, "PA", "*A" , "A", 1}, + { "*A", "B", IsFirstReconcile::kBoth, "UA", "*A" , "A", 1}, + { "*A", "AB", IsFirstReconcile::kBoth, "UA", "*A" , "A", 5}, + { "*AB", "BA", IsFirstReconcile::kFirst, "UAB", "*AB", "AB", 7}, + { "*AB", "BA", IsFirstReconcile::kNotFirst,"", "*AB", "BA", 0}, - { "*AB", "A", IsFirstReconcile::kBoth, "B", "*AB", "AB", "PAB", "*AB", "AB", 4}, + { "*AB", "A", IsFirstReconcile::kBoth, "PAB", "*AB", "AB", 4}, - { "*AB", "B", IsFirstReconcile::kFirst, "XAB", "*AB", "AB", "UAB", "*AB", "AB", 1}, - { "*AB", "B", IsFirstReconcile::kNotFirst, "A", "*AB", "BA", "PBA", "*AB", "BA", 1}, + { "*AB", "B", IsFirstReconcile::kFirst, "UAB", "*AB", "AB", 1}, + { "*AB", "B", IsFirstReconcile::kNotFirst,"PBA", "*AB", "BA", 1}, - { "*AB", "", IsFirstReconcile::kBoth, "AB", "*AB", "AB", "PAB", "*AB", "AB", 1}, + { "*AB", "", IsFirstReconcile::kBoth, "PAB", "*AB", "AB", 1}, // Sync enabled, token error on primary. - { "*xAB", "AB", IsFirstReconcile::kBoth, "X", "*xA", "" , "U", "*xA", "", 2}, - { "*xAB", "BA", IsFirstReconcile::kBoth, "XB", "*xAB", "B", "UB", "*xAB", "B", 2}, - { "*xAB", "A", IsFirstReconcile::kBoth, "X", "*xA", "" , "U", "*xA", "", 2}, - { "*xAB", "B", IsFirstReconcile::kBoth, "", "*xAB", "B", "", "*xAB", "B", 0}, - { "*xAB", "", IsFirstReconcile::kBoth, "B", "*xAB", "B", "PB", "*xAB", "B", 0}, + { "*xAB", "AB", IsFirstReconcile::kBoth, "U", "*xA", "", 2}, + { "*xAB", "BA", IsFirstReconcile::kBoth, "UB", "*xAB", "B", 2}, + { "*xAB", "A", IsFirstReconcile::kBoth, "U", "*xA", "", 2}, + { "*xAB", "B", IsFirstReconcile::kBoth, "", "*xAB", "B", 0}, + { "*xAB", "", IsFirstReconcile::kBoth, "PB", "*xAB", "B", 0}, // Sync enabled, token error on secondary. - { "*AxB", "AB", IsFirstReconcile::kBoth, "XA", "*A", "A", "UA", "*A", "A", 5}, - { "*AxB", "A", IsFirstReconcile::kBoth, "", "*A", "A", "", "*A", "A", 0}, - { "*AxB", "", IsFirstReconcile::kBoth, "A", "*A", "A", "PA", "*A", "A", 1}, + { "*AxB", "AB", IsFirstReconcile::kBoth, "UA", "*A", "A", 5}, + { "*AxB", "A", IsFirstReconcile::kBoth, "", "*A", "A", 0}, + { "*AxB", "", IsFirstReconcile::kBoth, "PA", "*A", "A", 1}, // The first account in cookies is swapped even when Chrome is running. // The swap would happen at next startup anyway and doing it earlier avoids signing the user out. - { "*AxB", "BA", IsFirstReconcile::kBoth, "XA", "*A", "A", "UA", "*A", "A", 5}, - { "*AxB", "B", IsFirstReconcile::kBoth, "XA", "*A", "A", "UA", "*A", "A", 1}, + { "*AxB", "BA", IsFirstReconcile::kBoth, "UA", "*A", "A", 5}, + { "*AxB", "B", IsFirstReconcile::kBoth, "UA", "*A", "A", 1}, // Sync enabled, token error on both accounts. - { "*xAxB", "AB", IsFirstReconcile::kBoth, "X", "*xA", "", "U", "*xA", "", 2}, - { "*xAxB", "BA", IsFirstReconcile::kBoth, "X", "*xA", "", "U", "*xA", "", 2}, - { "*xAxB", "A", IsFirstReconcile::kBoth, "X", "*xA", "", "U", "*xA", "", 2}, - { "*xAxB", "B", IsFirstReconcile::kBoth, "X", "*xA", "", "U", "*xA", "", 5}, - { "*xAxB", "", IsFirstReconcile::kBoth, "", "*xA", "", "", "*xA", "", 0}, + { "*xAxB", "AB", IsFirstReconcile::kBoth, "U", "*xA", "", 2}, + { "*xAxB", "BA", IsFirstReconcile::kBoth, "U", "*xA", "", 2}, + { "*xAxB", "A", IsFirstReconcile::kBoth, "U", "*xA", "", 2}, + { "*xAxB", "B", IsFirstReconcile::kBoth, "U", "*xA", "", 5}, + { "*xAxB", "", IsFirstReconcile::kBoth, "", "*xA", "", 0}, // Sync disabled. - { "AB", "AB", IsFirstReconcile::kBoth, "", "AB", "AB", "", "AB", "AB", 0}, - { "AB", "BA", IsFirstReconcile::kBoth, "", "AB", "BA", "", "AB", "BA", 0}, - { "AB", "A", IsFirstReconcile::kBoth, "B", "AB", "AB", "PAB", "AB", "AB", 4}, - { "AB", "B", IsFirstReconcile::kBoth, "A", "AB", "BA", "PBA", "AB", "BA", 4}, - { "AB", "", IsFirstReconcile::kBoth, "AB", "AB", "AB", "PAB", "AB", "AB", 0}, + { "AB", "AB", IsFirstReconcile::kBoth, "", "AB", "AB", 0}, + { "AB", "BA", IsFirstReconcile::kBoth, "", "AB", "BA", 0}, + { "AB", "A", IsFirstReconcile::kBoth, "PAB", "AB", "AB", 4}, + { "AB", "B", IsFirstReconcile::kBoth, "PBA", "AB", "BA", 4}, + { "AB", "", IsFirstReconcile::kBoth, "PAB", "AB", "AB", 0}, // Sync disabled, token error on first account. - { "xAB", "AB", IsFirstReconcile::kFirst, "XB", "B", "B", "UB", "B", "B", 3}, - { "xAB", "AB", IsFirstReconcile::kNotFirst, "X", "", "" , "U", "", "", 3}, + { "xAB", "AB", IsFirstReconcile::kFirst, "UB", "B", "B", 3}, + { "xAB", "AB", IsFirstReconcile::kNotFirst, "U", "", "", 3}, - { "xAB", "BA", IsFirstReconcile::kBoth, "XB", "B", "B", "UB", "B", "B", 5}, + { "xAB", "BA", IsFirstReconcile::kBoth, "UB", "B", "B", 5}, - { "xAB", "A", IsFirstReconcile::kFirst, "XB", "B", "B", "UB", "B", "B", 3}, - { "xAB", "A", IsFirstReconcile::kNotFirst, "X", "", "" , "U", "", "", 3}, + { "xAB", "A", IsFirstReconcile::kFirst, "UB", "B", "B", 3}, + { "xAB", "A", IsFirstReconcile::kNotFirst, "U", "", "", 3}, - { "xAB", "B", IsFirstReconcile::kBoth, "", "B", "B", "", "B", "B", 0}, + { "xAB", "B", IsFirstReconcile::kBoth, "", "B", "B", 0}, - { "xAB", "", IsFirstReconcile::kBoth, "B", "B", "B", "PB", "B", "B", 0}, - // Sync disabled, token error on second account . - { "AxB", "AB", IsFirstReconcile::kBoth, "XA", "A", "A", "UA", "A", "A", 5}, + { "xAB", "", IsFirstReconcile::kBoth, "PB", "B", "B", 0}, + // Sync disabled, token error on second account + { "AxB", "AB", IsFirstReconcile::kBoth, "UA", "A", "A", 5}, - { "AxB", "BA", IsFirstReconcile::kFirst, "XA", "A", "A", "UA", "A", "A", 3}, - { "AxB", "BA", IsFirstReconcile::kNotFirst, "X", "", "" , "U", "", "", 3}, + { "AxB", "BA", IsFirstReconcile::kFirst, "UA", "A", "A", 3}, + { "AxB", "BA", IsFirstReconcile::kNotFirst, "U", "", "", 3}, - { "AxB", "A", IsFirstReconcile::kBoth, "", "A", "A", "", "A", "A", 0}, + { "AxB", "A", IsFirstReconcile::kBoth, "", "A", "A", 0}, - { "AxB", "B", IsFirstReconcile::kFirst, "XA", "A", "A", "UA", "A", "A", 3}, - { "AxB", "B", IsFirstReconcile::kNotFirst, "X", "", "" , "U", "", "", 3}, + { "AxB", "B", IsFirstReconcile::kFirst, "UA", "A", "A", 3}, + { "AxB", "B", IsFirstReconcile::kNotFirst, "U", "", "", 3}, - { "AxB", "", IsFirstReconcile::kBoth, "A", "A", "A", "PA", "A", "A", 0}, + { "AxB", "", IsFirstReconcile::kBoth, "PA", "A", "A", 0}, // Sync disabled, token error on both accounts. - { "xAxB", "AB", IsFirstReconcile::kBoth, "X", "", "", "U", "", "", 3}, - { "xAxB", "BA", IsFirstReconcile::kBoth, "X", "", "", "U", "", "", 3}, - { "xAxB", "A", IsFirstReconcile::kBoth, "X", "", "", "U", "", "", 3}, - { "xAxB", "B", IsFirstReconcile::kBoth, "X", "", "", "U", "", "", 3}, - { "xAxB", "", IsFirstReconcile::kBoth, "", "", "", "", "", "", 0}, + { "xAxB", "AB", IsFirstReconcile::kBoth, "U", "", "", 3}, + { "xAxB", "BA", IsFirstReconcile::kBoth, "U", "", "", 3}, + { "xAxB", "A", IsFirstReconcile::kBoth, "U", "", "", 3}, + { "xAxB", "B", IsFirstReconcile::kBoth, "U", "", "", 3}, + { "xAxB", "", IsFirstReconcile::kBoth, "", "", "", 0}, // Account marked as invalid in cookies. // No difference between cookies and tokens, do not do do anything. // Do not logout. Regression tests for http://crbug.com/854799 - { "", "xA", IsFirstReconcile::kBoth, "", "", "xA", "", "", "xA", 0}, - { "", "xAxB", IsFirstReconcile::kBoth, "", "", "xAxB", "", "", "xAxB", 0}, - { "xA", "xA", IsFirstReconcile::kBoth, "", "", "xA", "", "", "xA", 0}, - { "xAB", "xAB", IsFirstReconcile::kBoth, "", "B", "xAB", "", "B", "xAB", 0}, - { "AxB", "AxC", IsFirstReconcile::kBoth, "", "A", "AxC", "", "A", "AxC", 0}, - { "B", "xAB", IsFirstReconcile::kBoth, "", "B", "xAB", "", "B", "xAB", 0}, - { "*xA", "xA", IsFirstReconcile::kBoth, "", "*xA", "xA", "", "*xA", "xA", 0}, - { "*xA", "xB", IsFirstReconcile::kBoth, "", "*xA", "xB", "", "*xA", "xB", 0}, - { "*xAB", "xAB", IsFirstReconcile::kBoth, "", "*xAB", "xAB", "", "*xAB", "xAB", 0}, - { "*AxB", "xBA", IsFirstReconcile::kNotFirst, "", "*A", "xBA", "", "*A", "xBA", 0}, + { "", "xA", IsFirstReconcile::kBoth, "", "", "xA", 0}, + { "", "xAxB", IsFirstReconcile::kBoth, "", "", "xAxB", 0}, + { "xA", "xA", IsFirstReconcile::kBoth, "", "", "xA", 0}, + { "xAB", "xAB", IsFirstReconcile::kBoth, "", "B", "xAB", 0}, + { "AxB", "AxC", IsFirstReconcile::kBoth, "", "A", "AxC", 0}, + { "B", "xAB", IsFirstReconcile::kBoth, "", "B", "xAB", 0}, + { "*xA", "xA", IsFirstReconcile::kBoth, "", "*xA", "xA", 0}, + { "*xA", "xB", IsFirstReconcile::kBoth, "", "*xA", "xB", 0}, + { "*xAB", "xAB", IsFirstReconcile::kBoth, "", "*xAB", "xAB", 0}, + { "*AxB", "xBA", IsFirstReconcile::kNotFirst, "", "*A", "xBA", 0}, // Appending a new cookie after the invalid one. - { "B", "xA", IsFirstReconcile::kBoth, "B", "B", "xAB", "PB", "B", "xAB", 4}, - { "xAB", "xA", IsFirstReconcile::kBoth, "B", "B", "xAB", "PB", "B", "xAB", 4}, + { "B", "xA", IsFirstReconcile::kBoth, "PB", "B", "xAB", 4}, + { "xAB", "xA", IsFirstReconcile::kBoth, "PB", "B", "xAB", 4}, // Refresh existing cookies. - { "AB", "xAB", IsFirstReconcile::kBoth, "A", "AB", "AB", "PAB", "AB", "AB", 4}, - { "*AB", "xBxA", IsFirstReconcile::kNotFirst, "BA", "*AB", "BA", "PBA", "*AB", "BA", 1}, + { "AB", "xAB", IsFirstReconcile::kBoth, "PAB", "AB", "AB", 4}, + { "*AB", "xBxA", IsFirstReconcile::kNotFirst, "PBA", "*AB", "BA", 1}, // Appending and invalidating cookies at the same time. - { "xAB", "xAC", IsFirstReconcile::kFirst, "XB", "B", "B", "UB", "B", "B", 6}, - { "xAB", "xAC", IsFirstReconcile::kNotFirst, "X", "", "", "U", "", "", 6}, + { "xAB", "xAC", IsFirstReconcile::kFirst, "UB", "B", "B", 6}, + { "xAB", "xAC", IsFirstReconcile::kNotFirst, "U", "", "", 6}, - { "xAB", "AxC", IsFirstReconcile::kFirst, "XB", "B", "B", "UB", "B", "B", 3}, - { "xAB", "AxC", IsFirstReconcile::kNotFirst, "X", "", "", "U", "", "", 3}, + { "xAB", "AxC", IsFirstReconcile::kFirst, "UB", "B", "B", 3}, + { "xAB", "AxC", IsFirstReconcile::kNotFirst, "U", "", "", 3}, - { "*xAB", "xABC", IsFirstReconcile::kFirst, "XB", "*xAB", "B", "UB", "*xAB", "B", 5}, - { "*xAB", "xABC", IsFirstReconcile::kNotFirst, "X", "*xA", "", "U", "*xA", "", 5}, + { "*xAB", "xABC", IsFirstReconcile::kFirst, "UB", "*xAB", "B", 5}, + { "*xAB", "xABC", IsFirstReconcile::kNotFirst, "U", "*xA", "", 5}, - { "xAB", "xABC", IsFirstReconcile::kFirst, "XB", "B", "B", "UB", "B", "B", 5}, - { "xAB", "xABC", IsFirstReconcile::kNotFirst, "X", "", "", "U", "", "", 5}, + { "xAB", "xABC", IsFirstReconcile::kFirst, "UB", "B", "B", 5}, + { "xAB", "xABC", IsFirstReconcile::kNotFirst, "U", "", "", 5}, // Miscellaneous cases. - // Check that unknown Gaia accounts are signed out. - { "*A", "AB", IsFirstReconcile::kBoth, "XA", "*A", "A", "UA", "*A", "A", 5}, + // Check that unknown Gaia accounts are signed o. + { "*A", "AB", IsFirstReconcile::kBoth, "UA", "*A", "A", 5}, // Check that Gaia default account is kept in first position. - { "AB", "BC", IsFirstReconcile::kBoth, "XBA", "AB", "BA", "UBA", "AB", "BA", 6}, + { "AB", "BC", IsFirstReconcile::kBoth, "UBA", "AB", "BA", 6}, // Check that Gaia cookie order is preserved for B. - { "*ABC", "CB", IsFirstReconcile::kFirst, "XABC", "*ABC", "ABC", "UABC", "*ABC", "ABC", 1}, + { "*ABC", "CB", IsFirstReconcile::kFirst, "UABC", "*ABC", "ABC", 1}, // TODO(https://crbug.com/1129931): Merge session should do XCB instead. - { "xABC", "ABC", IsFirstReconcile::kFirst, "XBC", "BC", "BC", "UCB", "BC", "CB", 1}, + { "xABC", "ABC", IsFirstReconcile::kFirst, "UCB", "BC", "CB", 1}, // Check that order in the chrome_accounts is not important. - { "A*B", "", IsFirstReconcile::kBoth, "BA", "A*B", "BA", "PBA", "A*B", "BA", 7}, - { "*xBA", "BA", IsFirstReconcile::kFirst, "X", "*xB", "" , "U", "*xB", "", 2}, + { "A*B", "", IsFirstReconcile::kBoth, "PBA", "A*B", "BA", 7}, + { "*xBA", "BA", IsFirstReconcile::kFirst, "U", "*xB", "", 2}, // Required for idempotency check. - { "", "", IsFirstReconcile::kNotFirst, "", "", "", "", "", "", 0}, - { "", "xA", IsFirstReconcile::kNotFirst, "", "", "xA", "", "", "xA", 0}, - { "", "xB", IsFirstReconcile::kNotFirst, "", "", "xB", "", "", "xB", 0}, - { "", "xAxB", IsFirstReconcile::kNotFirst, "", "", "xAxB", "", "", "xAxB", 0}, - { "", "xBxA", IsFirstReconcile::kNotFirst, "", "", "xBxA", "", "", "xBxA", 0}, - { "*A", "A", IsFirstReconcile::kNotFirst, "", "*A", "A", "", "*A", "A", 0}, - { "*A", "xBA", IsFirstReconcile::kNotFirst, "", "*A", "xBA", "", "*A", "xBA", 0}, - { "*A", "AxB", IsFirstReconcile::kNotFirst, "", "*A", "AxB", "", "*A", "AxB", 0}, - { "A", "A", IsFirstReconcile::kNotFirst, "", "A", "A", "", "A", "A", 0}, - { "A", "xBA", IsFirstReconcile::kNotFirst, "", "A", "xBA", "", "A", "xBA", 0}, - { "A", "AxB", IsFirstReconcile::kNotFirst, "", "A", "AxB", "", "A", "AxB", 0}, - { "B", "B", IsFirstReconcile::kNotFirst, "", "B", "B", "", "B", "B", 0}, - { "B", "xAB", IsFirstReconcile::kNotFirst, "", "B", "xAB", "", "B", "xAB", 0}, - { "B", "BxA", IsFirstReconcile::kNotFirst, "", "B", "BxA", "", "B", "BxA", 0}, - { "*xA", "", IsFirstReconcile::kNotFirst, "", "*xA", "", "", "*xA", "", 0}, - { "*xA", "xAxB", IsFirstReconcile::kNotFirst, "", "*xA", "xAxB", "", "*xA", "xAxB", 0}, - { "*xA", "xBxA", IsFirstReconcile::kNotFirst, "", "*xA", "xBxA", "", "*xA", "xBxA", 0}, - { "*xA", "xA", IsFirstReconcile::kNotFirst, "", "*xA", "xA", "", "*xA", "xA", 0}, - { "*xA", "xB", IsFirstReconcile::kNotFirst, "", "*xA", "xB", "", "*xA", "xB", 0}, - { "*xAB", "B", IsFirstReconcile::kNotFirst, "", "*xAB", "B", "", "*xAB", "B", 0}, - { "*xAB", "BxA", IsFirstReconcile::kNotFirst, "", "*xAB", "BxA", "", "*xAB", "BxA", 0}, - { "*xAB", "xAB", IsFirstReconcile::kNotFirst, "", "*xAB", "xAB", "", "*xAB", "xAB", 0}, - { "*xAB", "xABxC",IsFirstReconcile::kNotFirst, "", "*xAB", "xABxC", "", "*xAB", "xABxC", 0}, - { "*xB", "", IsFirstReconcile::kNotFirst, "", "*xB", "", "", "*xB", "", 0}, - { "A*B", "BA", IsFirstReconcile::kNotFirst, "", "A*B", "BA", "", "A*B", "BA", 0}, - { "A*B", "AB", IsFirstReconcile::kNotFirst, "", "A*B", "AB", "", "A*B", "AB", 0}, - { "A", "AxC", IsFirstReconcile::kNotFirst, "", "A", "AxC", "", "A", "AxC", 0}, - { "AB", "BxCA", IsFirstReconcile::kNotFirst, "", "AB", "BxCA", "", "AB", "BxCA", 0}, - { "B", "xABxC",IsFirstReconcile::kNotFirst, "", "B", "xABxC", "", "B", "xABxC", 0}, - { "B", "xAxCB",IsFirstReconcile::kNotFirst, "", "B", "xAxCB", "", "B", "xAxCB", 0}, - { "*ABC", "ACB", IsFirstReconcile::kNotFirst, "", "*ABC", "ACB", "", "*ABC", "ACB", 0}, - { "*ABC", "ABC", IsFirstReconcile::kNotFirst, "", "*ABC", "ABC", "", "*ABC", "ABC", 0}, - { "BC", "BC", IsFirstReconcile::kNotFirst, "", "BC", "BC", "", "BC", "BC", 0}, - { "BC", "CB", IsFirstReconcile::kNotFirst, "", "BC", "CB", "", "BC", "CB", 0}, + { "", "", IsFirstReconcile::kNotFirst, "", "", "", 0}, + { "", "xA", IsFirstReconcile::kNotFirst, "", "", "xA", 0}, + { "", "xB", IsFirstReconcile::kNotFirst, "", "", "xB", 0}, + { "", "xAxB", IsFirstReconcile::kNotFirst, "", "", "xAxB", 0}, + { "", "xBxA", IsFirstReconcile::kNotFirst, "", "", "xBxA", 0}, + { "*A", "A", IsFirstReconcile::kNotFirst, "", "*A", "A", 0}, + { "*A", "xBA", IsFirstReconcile::kNotFirst, "", "*A", "xBA", 0}, + { "*A", "AxB", IsFirstReconcile::kNotFirst, "", "*A", "AxB", 0}, + { "A", "A", IsFirstReconcile::kNotFirst, "", "A", "A", 0}, + { "A", "xBA", IsFirstReconcile::kNotFirst, "", "A", "xBA", 0}, + { "A", "AxB", IsFirstReconcile::kNotFirst, "", "A", "AxB", 0}, + { "B", "B", IsFirstReconcile::kNotFirst, "", "B", "B", 0}, + { "B", "xAB", IsFirstReconcile::kNotFirst, "", "B", "xAB", 0}, + { "B", "BxA", IsFirstReconcile::kNotFirst, "", "B", "BxA", 0}, + { "*xA", "", IsFirstReconcile::kNotFirst, "", "*xA", "", 0}, + { "*xA", "xAxB", IsFirstReconcile::kNotFirst, "", "*xA", "xAxB", 0}, + { "*xA", "xBxA", IsFirstReconcile::kNotFirst, "", "*xA", "xBxA", 0}, + { "*xA", "xA", IsFirstReconcile::kNotFirst, "", "*xA", "xA", 0}, + { "*xA", "xB", IsFirstReconcile::kNotFirst, "", "*xA", "xB", 0}, + { "*xAB", "B", IsFirstReconcile::kNotFirst, "", "*xAB", "B", 0}, + { "*xAB", "BxA", IsFirstReconcile::kNotFirst, "", "*xAB", "BxA", 0}, + { "*xAB", "xAB", IsFirstReconcile::kNotFirst, "", "*xAB", "xAB", 0}, + { "*xAB", "xABxC",IsFirstReconcile::kNotFirst, "", "*xAB", "xABxC", 0}, + { "*xB", "", IsFirstReconcile::kNotFirst, "", "*xB", "", 0}, + { "A*B", "BA", IsFirstReconcile::kNotFirst, "", "A*B", "BA", 0}, + { "A*B", "AB", IsFirstReconcile::kNotFirst, "", "A*B", "AB", 0}, + { "A", "AxC", IsFirstReconcile::kNotFirst, "", "A", "AxC", 0}, + { "AB", "BxCA", IsFirstReconcile::kNotFirst, "", "AB", "BxCA", 0}, + { "B", "xABxC",IsFirstReconcile::kNotFirst, "", "B", "xABxC", 0}, + { "B", "xAxCB",IsFirstReconcile::kNotFirst, "", "B", "xAxCB", 0}, + { "*ABC", "ACB", IsFirstReconcile::kNotFirst, "", "*ABC", "ACB", 0}, + { "*ABC", "ABC", IsFirstReconcile::kNotFirst, "", "*ABC", "ABC", 0}, + { "BC", "BC", IsFirstReconcile::kNotFirst, "", "BC", "BC", 0}, + { "BC", "CB", IsFirstReconcile::kNotFirst, "", "BC", "CB", 0}, }; // clang-format on -// Parameterized version of AccountReconcilorTest that tests Dice -// implementation with MergeSession endpoint. -class AccountReconcilorTestDiceMergeSession - : public AccountReconcilorTestTable { - public: - AccountReconcilorTestDiceMergeSession() = default; - - protected: - base::test::ScopedFeatureList scoped_feature_list_; - - private: - DISALLOW_COPY_AND_ASSIGN(AccountReconcilorTestDiceMergeSession); -}; - -// Checks one row of the kDiceParams table above. -TEST_P(AccountReconcilorTestDiceMergeSession, TableRowTest) { - SetAccountConsistency(signin::AccountConsistencyMethod::kDice); - scoped_feature_list_.InitAndDisableFeature(kUseMultiloginEndpoint); - - // Enable Dice. - SetAccountConsistency(signin::AccountConsistencyMethod::kDice); - - // Check that reconcile is idempotent: when called twice in a row it should do - // nothing on the second call. - CheckReconcileIdempotent(kDiceParams, GetParam(), /*multilogin=*/false); - RunReconcile(); -} - -INSTANTIATE_TEST_SUITE_P( - DiceTable, - AccountReconcilorTestDiceMergeSession, - ::testing::ValuesIn(GenerateTestCasesFromParams(kDiceParams))); - class AccountReconcilorTestForceDiceMigration : public BaseAccountReconcilorTestTable, public ::testing::WithParamInterface<ForceDiceMigrationTestTableParam> { public: - AccountReconcilorTestForceDiceMigration() - : BaseAccountReconcilorTestTable(GetParam().tokens, - GetParam().cookies, - IsFirstReconcile::kFirst, - GetParam().gaia_api_calls, - GetParam().tokens_after_reconcile, - GetParam().cookies_after_reconcile) { - // ForceDiceMigration is temporary and the migration was enabled in in - // Q1 2020. It is expected to be removed in 2021 Q2. - // Simply disable the OAuthmultilogin endpoint instead of migrating the - // tests. - scoped_feature_list_.InitAndDisableFeature(kUseMultiloginEndpoint); + AccountReconcilorTestForceDiceMigration() = default; + + void RunReconcile() { + // Setup cookies. + std::vector<Cookie> cookies = ParseCookieString(GetParam().cookies); + ConfigureCookieManagerService(cookies); + std::vector<Cookie> cookies_after_reconcile = cookies; + + // Call list accounts now so that the next call completes synchronously. + identity_test_env()->identity_manager()->GetAccountsInCookieJar(); + base::RunLoop().RunUntilIdle(); + + // Setup tokens. This triggers listing cookies so we need to setup cookies + // before that. + SetupTokens(GetParam().tokens); + + // Setup expectations. + testing::InSequence mock_sequence; + bool should_logout; + if (GetParam().gaia_api_calls[0] != '\0') { + gaia::MultiloginMode mode = + GetParam().gaia_api_calls[0] == 'U' + ? gaia::MultiloginMode::MULTILOGIN_UPDATE_COOKIE_ACCOUNTS_ORDER + : gaia::MultiloginMode::MULTILOGIN_PRESERVE_COOKIE_ACCOUNTS_ORDER; + // Generate expected array of accounts in cookies and set fake gaia + // response. + std::vector<CoreAccountId> accounts_to_send; + for (int i = 1; GetParam().gaia_api_calls[i] != '\0'; ++i) { + accounts_to_send.push_back( + CoreAccountId(accounts_[GetParam().gaia_api_calls[i]].gaia_id)); + } + const signin::MultiloginParameters params(mode, accounts_to_send); + cookies_after_reconcile = FakeSetAccountsInCookie(params, cookies); + should_logout = + accounts_to_send.empty() && + (mode == + gaia::MultiloginMode::MULTILOGIN_UPDATE_COOKIE_ACCOUNTS_ORDER); + if (should_logout) { + EXPECT_CALL(*GetMockReconcilor(), PerformLogoutAllAccountsAction()) + .Times(1); + } else { + EXPECT_CALL(*GetMockReconcilor(), PerformSetCookiesAction(params)) + .Times(1); + } + } + // Reconcile. + AccountReconcilor* reconcilor = GetMockReconcilor(); + ASSERT_TRUE(reconcilor); + ASSERT_TRUE(reconcilor->first_execution_); + reconcilor->first_execution_ = true; + reconcilor->StartReconcile(AccountReconcilor::Trigger::kCookieChange); + if (GetParam().gaia_api_calls[0] != '\0') { + if (should_logout) { + SimulateLogOutFromCookieCompleted( + reconcilor, GoogleServiceAuthError::AuthErrorNone()); + } else { + SimulateSetAccountsInCookieCompleted( + reconcilor, signin::SetAccountsInCookieResult::kSuccess); + } + } + + ASSERT_FALSE(reconcilor->is_reconcile_started_); + if (GetParam().tokens == GetParam().tokens_after_reconcile) { + EXPECT_EQ(signin_metrics::ACCOUNT_RECONCILOR_OK, reconcilor->GetState()); + } else { + // If the tokens were changed by the reconcile, a new reconcile should be + // scheduled. + EXPECT_EQ(signin_metrics::ACCOUNT_RECONCILOR_SCHEDULED, + reconcilor->GetState()); + } + VerifyCurrentTokens(ParseTokenString(GetParam().tokens_after_reconcile)); + + std::vector<Cookie> cookies_after = + ParseCookieString(GetParam().cookies_after_reconcile); + EXPECT_EQ(cookies_after, cookies_after_reconcile); + + testing::Mock::VerifyAndClearExpectations(GetMockReconcilor()); + + // Another reconcile is sometimes triggered if Chrome accounts have + // changed. Allow it to finish. + EXPECT_CALL(*GetMockReconcilor(), PerformSetCookiesAction(testing::_)) + .WillRepeatedly(testing::Return()); + ConfigureCookieManagerService({}); + base::RunLoop().RunUntilIdle(); } private: - base::test::ScopedFeatureList scoped_feature_list_; - DISALLOW_COPY_AND_ASSIGN(AccountReconcilorTestForceDiceMigration); }; // clang-format off const std::vector<ForceDiceMigrationTestTableParam> kForceDiceParams = { - {"*A", "AB", "XA", "*A", "A" }, - {"*AxB", "AB", "XA", "*A", "A" }, - {"AxB", "AB", "XA", "A", "A" }, - {"xAxB", "AB", "X", "", "" }, + {"*A", "AB", "UA", "*A", "A" }, + {"*AxB", "AB", "UA", "*A", "A" }, + {"AxB", "AB", "UA", "A", "A" }, + {"xAxB", "AB", "U", "", "" }, {"*A", "", "", "*xA", "" }, - {"*A", "B", "X", "*xA", "" }, + {"*A", "B", "U", "*xA", "" }, {"*AB", "B", "", "*xAB", "B" }, - {"*AxB", "B", "X", "*xA", "" }, + {"*AxB", "B", "U", "*xA", "" }, {"*ABC", "CB", "", "*xABC", "CB" }, {"*AB", "A", "", "*A", "A" }, {"AB", "A", "", "A", "A" }, {"AB", "", "", "", "" }, {"xAB", "", "", "", "" }, - {"xAB", "A", "X", "", "" }, + {"xAB", "A", "U", "", "" }, {"xAB", "xA", "", "", "xA" }, {"xAB", "B", "", "B", "B" }, - {"AxB", "B", "X", "", "" }, + {"AxB", "B", "U", "", "" }, {"AxB", "", "", "", "" }, {"xAxB", "", "", "", "" }, {"B", "xA", "", "", "xA" }, {"AB", "xAB", "", "B", "xAB" }, - {"xAB", "xAC", "X", "", "" }, - {"xAB", "AxC", "X", "", "" }, - {"AB", "BC", "XB", "B", "B" }, + {"xAB", "xAC", "U", "", "" }, + {"xAB", "AxC", "U", "", "" }, + {"AB", "BC", "UB", "B", "B" }, {"*AB", "", "", "*xA", "" }, {"*xAB", "", "", "*xA", "" }, {"*AxB", "", "", "*xA", "" }, @@ -1128,7 +1020,6 @@ }; // clang-format on -// Checks one row of the kForceDiceParams table above. TEST_P(AccountReconcilorTestForceDiceMigration, TableRowTest) { SetAccountConsistency(signin::AccountConsistencyMethod::kDice); EXPECT_FALSE(test_signin_client()->is_dice_migration_completed()); @@ -1144,7 +1035,8 @@ TEST_P(AccountReconcilorTestForceDiceMigration, TableRowTestCheckNoOp) { SetAccountConsistency(signin::AccountConsistencyMethod::kDice); // Setup cookies. - std::vector<Cookie> cookies = ParseCookieString(cookies_after_reconcile_); + std::vector<Cookie> cookies = + ParseCookieString(GetParam().cookies_after_reconcile); ConfigureCookieManagerService(cookies); // Call list accounts now so that the next call completes synchronously. @@ -1153,9 +1045,8 @@ // Setup tokens. This triggers listing cookies so we need to setup cookies // before that. - SetupTokens(tokens_after_reconcile_); + SetupTokens(GetParam().tokens_after_reconcile); - EXPECT_CALL(*GetMockReconcilor(), PerformMergeAction(testing::_)).Times(0); EXPECT_CALL(*GetMockReconcilor(), PerformLogoutAllAccountsAction()).Times(0); EXPECT_CALL(*GetMockReconcilor(), PerformSetCookiesAction(testing::_)) .Times(0); @@ -1178,9 +1069,6 @@ public: AccountReconcilorTestDiceMultilogin() = default; - protected: - base::test::ScopedFeatureList scoped_feature_list_; - private: DISALLOW_COPY_AND_ASSIGN(AccountReconcilorTestDiceMultilogin); }; @@ -1188,9 +1076,8 @@ // Checks one row of the kDiceParams table above. TEST_P(AccountReconcilorTestDiceMultilogin, TableRowTest) { SetAccountConsistency(signin::AccountConsistencyMethod::kDice); - scoped_feature_list_.InitAndEnableFeature(kUseMultiloginEndpoint); - CheckReconcileIdempotent(kDiceParams, GetParam(), /*multilogin=*/true); + CheckReconcileIdempotent(kDiceParams, GetParam()); // Setup cookies. std::vector<Cookie> cookies = ParseCookieString(GetParam().cookies); @@ -1208,17 +1095,17 @@ // Setup expectations. testing::InSequence mock_sequence; bool should_logout = false; - if (GetParam().gaia_api_calls_multilogin[0] != '\0') { + if (GetParam().gaia_api_calls[0] != '\0') { gaia::MultiloginMode mode = - GetParam().gaia_api_calls_multilogin[0] == 'U' + GetParam().gaia_api_calls[0] == 'U' ? gaia::MultiloginMode::MULTILOGIN_UPDATE_COOKIE_ACCOUNTS_ORDER : gaia::MultiloginMode::MULTILOGIN_PRESERVE_COOKIE_ACCOUNTS_ORDER; // Generate expected array of accounts in cookies and set fake gaia // response. std::vector<CoreAccountId> accounts_to_send; - for (int i = 1; GetParam().gaia_api_calls_multilogin[i] != '\0'; ++i) { - accounts_to_send.push_back(CoreAccountId( - accounts_[GetParam().gaia_api_calls_multilogin[i]].gaia_id)); + for (int i = 1; GetParam().gaia_api_calls[i] != '\0'; ++i) { + accounts_to_send.push_back( + CoreAccountId(accounts_[GetParam().gaia_api_calls[i]].gaia_id)); } const signin::MultiloginParameters params(mode, accounts_to_send); cookies_after_reconcile = FakeSetAccountsInCookie(params, cookies); @@ -1240,7 +1127,7 @@ reconcilor->first_execution_ = GetParam().is_first_reconcile == IsFirstReconcile::kFirst ? true : false; reconcilor->StartReconcile(AccountReconcilor::Trigger::kCookieChange); - if (GetParam().gaia_api_calls_multilogin[0] != '\0') { + if (GetParam().gaia_api_calls[0] != '\0') { if (should_logout) { SimulateLogOutFromCookieCompleted( reconcilor, GoogleServiceAuthError::AuthErrorNone()); @@ -1251,7 +1138,7 @@ } ASSERT_FALSE(reconcilor->is_reconcile_started_); - if (GetParam().tokens == GetParam().tokens_after_reconcile_multilogin) { + if (GetParam().tokens == GetParam().tokens_after_reconcile) { EXPECT_EQ(signin_metrics::ACCOUNT_RECONCILOR_OK, reconcilor->GetState()); } else { // If the tokens were changed by the reconcile, a new reconcile should be @@ -1259,11 +1146,10 @@ EXPECT_EQ(signin_metrics::ACCOUNT_RECONCILOR_SCHEDULED, reconcilor->GetState()); } - VerifyCurrentTokens( - ParseTokenString(GetParam().tokens_after_reconcile_multilogin)); + VerifyCurrentTokens(ParseTokenString(GetParam().tokens_after_reconcile)); std::vector<Cookie> cookies_after = - ParseCookieString(GetParam().cookies_after_reconcile_multilogin); + ParseCookieString(GetParam().cookies_after_reconcile); EXPECT_EQ(cookies_after, cookies_after_reconcile); testing::Mock::VerifyAndClearExpectations(GetMockReconcilor()); @@ -1281,28 +1167,18 @@ AccountReconcilorTestDiceMultilogin, ::testing::ValuesIn(GenerateTestCasesFromParams(kDiceParams))); -class AccountReconcilorDiceEndpointParamTest - : public AccountReconcilorTest, - public ::testing::WithParamInterface<bool> { +class AccountReconcilorDiceTest : public AccountReconcilorTest { public: - AccountReconcilorDiceEndpointParamTest() { + AccountReconcilorDiceTest() { SetAccountConsistency(signin::AccountConsistencyMethod::kDice); - if (IsMultiloginEnabled()) - scoped_feature_list_.InitAndEnableFeature(kUseMultiloginEndpoint); - else - scoped_feature_list_.InitAndDisableFeature(kUseMultiloginEndpoint); } - bool IsMultiloginEnabled() { return GetParam(); } - - protected: - base::test::ScopedFeatureList scoped_feature_list_; private: - DISALLOW_COPY_AND_ASSIGN(AccountReconcilorDiceEndpointParamTest); + DISALLOW_COPY_AND_ASSIGN(AccountReconcilorDiceTest); }; // Tests that the AccountReconcilor is always registered. -TEST_P(AccountReconcilorDiceEndpointParamTest, DiceTokenServiceRegistration) { +TEST_F(AccountReconcilorDiceTest, DiceTokenServiceRegistration) { AccountReconcilor* reconcilor = GetMockReconcilor(); ASSERT_TRUE(reconcilor); ASSERT_TRUE(reconcilor->IsRegisteredWithIdentityManager()); @@ -1321,7 +1197,7 @@ } // Tests that reconcile starts even when Sync is not enabled. -TEST_P(AccountReconcilorDiceEndpointParamTest, DiceReconcileWithoutSignin) { +TEST_F(AccountReconcilorDiceTest, DiceReconcileWithoutSignin) { // Add a token in Chrome but do not sign in. Making account available (setting // a refresh token) triggers listing cookies so we need to setup cookies // before that. @@ -1329,38 +1205,28 @@ const CoreAccountId account_id = identity_test_env()->MakeAccountAvailable("user@gmail.com").account_id; - if (!IsMultiloginEnabled()) { - EXPECT_CALL(*GetMockReconcilor(), PerformMergeAction(account_id)); - } else { std::vector<CoreAccountId> accounts_to_send = {account_id}; const signin::MultiloginParameters params( gaia::MultiloginMode::MULTILOGIN_PRESERVE_COOKIE_ACCOUNTS_ORDER, accounts_to_send); EXPECT_CALL(*GetMockReconcilor(), PerformSetCookiesAction(params)); - } AccountReconcilor* reconcilor = GetMockReconcilor(); reconcilor->StartReconcile(AccountReconcilor::Trigger::kCookieChange); base::RunLoop().RunUntilIdle(); ASSERT_TRUE(reconcilor->is_reconcile_started_); - if (!IsMultiloginEnabled()) { - SimulateAddAccountToCookieCompleted( - reconcilor, account_id, GoogleServiceAuthError::AuthErrorNone()); - } else { - SimulateSetAccountsInCookieCompleted( - reconcilor, signin::SetAccountsInCookieResult::kSuccess); - } + SimulateSetAccountsInCookieCompleted( + reconcilor, signin::SetAccountsInCookieResult::kSuccess); ASSERT_FALSE(reconcilor->is_reconcile_started_); ASSERT_EQ(signin_metrics::ACCOUNT_RECONCILOR_OK, reconcilor->GetState()); } // Checks that nothing happens when there is no Chrome account and no Gaia // cookie. -TEST_P(AccountReconcilorDiceEndpointParamTest, DiceReconcileNoop) { +TEST_F(AccountReconcilorDiceTest, DiceReconcileNoop) { // No Chrome account and no cookie. signin::SetListAccountsResponseNoAccounts(&test_url_loader_factory_); - EXPECT_CALL(*GetMockReconcilor(), PerformMergeAction(testing::_)).Times(0); EXPECT_CALL(*GetMockReconcilor(), PerformLogoutAllAccountsAction()).Times(0); EXPECT_CALL(*GetMockReconcilor(), PerformSetCookiesAction(testing::_)) .Times(0); @@ -1374,8 +1240,7 @@ } // Tests that the first Gaia account is re-used when possible. -TEST_P(AccountReconcilorDiceEndpointParamTest, - DiceReconcileReuseGaiaFirstAccount) { +TEST_F(AccountReconcilorDiceTest, DiceReconcileReuseGaiaFirstAccount) { // Add account "other" to the Gaia cookie. signin::SetListAccountsResponseTwoAccounts( "other@gmail.com", signin::GetTestGaiaIdForEmail("other@gmail.com"), @@ -1396,13 +1261,6 @@ ASSERT_TRUE(identity_manager->HasAccountWithRefreshToken(account_id_1)); ASSERT_TRUE(identity_manager->HasAccountWithRefreshToken(account_id_2)); - if (!IsMultiloginEnabled()) { - testing::InSequence mock_sequence; - EXPECT_CALL(*GetMockReconcilor(), PerformLogoutAllAccountsAction()); - // Account 2 is added first. - EXPECT_CALL(*GetMockReconcilor(), PerformMergeAction(account_id_2)); - EXPECT_CALL(*GetMockReconcilor(), PerformMergeAction(account_id_1)); - } else { std::vector<CoreAccountId> accounts_to_send = {account_id_2, account_id_1}; // Send accounts to Gaia in order of chrome accounts. Account 2 is added // first. @@ -1410,30 +1268,20 @@ gaia::MultiloginMode::MULTILOGIN_UPDATE_COOKIE_ACCOUNTS_ORDER, accounts_to_send); EXPECT_CALL(*GetMockReconcilor(), PerformSetCookiesAction(params)); - } AccountReconcilor* reconcilor = GetMockReconcilor(); reconcilor->StartReconcile(AccountReconcilor::Trigger::kCookieChange); ASSERT_TRUE(reconcilor->is_reconcile_started_); base::RunLoop().RunUntilIdle(); - if (!IsMultiloginEnabled()) { - SimulateLogOutFromCookieCompleted(reconcilor, - GoogleServiceAuthError::AuthErrorNone()); - SimulateAddAccountToCookieCompleted( - reconcilor, account_id_1, GoogleServiceAuthError::AuthErrorNone()); - SimulateAddAccountToCookieCompleted( - reconcilor, account_id_2, GoogleServiceAuthError::AuthErrorNone()); - } else { SimulateSetAccountsInCookieCompleted( reconcilor, signin::SetAccountsInCookieResult::kSuccess); - } ASSERT_FALSE(reconcilor->is_reconcile_started_); ASSERT_EQ(signin_metrics::ACCOUNT_RECONCILOR_OK, reconcilor->GetState()); } // Tests that the first account is kept in cache and reused when cookies are // lost. -TEST_P(AccountReconcilorDiceEndpointParamTest, DiceLastKnownFirstAccount) { +TEST_F(AccountReconcilorDiceTest, DiceLastKnownFirstAccount) { // Add accounts to the token service and the Gaia cookie in a different order. // Making account available (setting a refresh token) triggers listing cookies // so we need to setup cookies before that. @@ -1460,7 +1308,6 @@ // Do one reconcile. It should do nothing but to populating the last known // account. { - EXPECT_CALL(*GetMockReconcilor(), PerformMergeAction(testing::_)).Times(0); EXPECT_CALL(*GetMockReconcilor(), PerformLogoutAllAccountsAction()) .Times(0); EXPECT_CALL(*GetMockReconcilor(), PerformSetCookiesAction(testing::_)) @@ -1478,17 +1325,6 @@ signin::SetListAccountsResponseNoAccounts(&test_url_loader_factory_); identity_test_env()->SetFreshnessOfAccountsInGaiaCookie(false); - if (!IsMultiloginEnabled()) { - // Reconcile again and check that account_id_2 is added first. - testing::InSequence mock_sequence; - - EXPECT_CALL(*GetMockReconcilor(), PerformMergeAction(account_id_2)) - .Times(1); - EXPECT_CALL(*GetMockReconcilor(), PerformMergeAction(account_id_1)) - .Times(1); - EXPECT_CALL(*GetMockReconcilor(), PerformLogoutAllAccountsAction()) - .Times(0); - } else { // Since Gaia can't know about cached account, make sure that we reorder // chrome accounts accordingly even in PRESERVE mode. std::vector<CoreAccountId> accounts_to_send = {account_id_2, account_id_1}; @@ -1496,27 +1332,19 @@ gaia::MultiloginMode::MULTILOGIN_PRESERVE_COOKIE_ACCOUNTS_ORDER, accounts_to_send); EXPECT_CALL(*GetMockReconcilor(), PerformSetCookiesAction(params)); - } AccountReconcilor* reconcilor = GetMockReconcilor(); reconcilor->StartReconcile(AccountReconcilor::Trigger::kCookieChange); ASSERT_TRUE(reconcilor->is_reconcile_started_); base::RunLoop().RunUntilIdle(); - if (!IsMultiloginEnabled()) { - SimulateAddAccountToCookieCompleted( - reconcilor, account_id_2, GoogleServiceAuthError::AuthErrorNone()); - SimulateAddAccountToCookieCompleted( - reconcilor, account_id_1, GoogleServiceAuthError::AuthErrorNone()); - } else { SimulateSetAccountsInCookieCompleted( reconcilor, signin::SetAccountsInCookieResult::kSuccess); - } ASSERT_FALSE(reconcilor->is_reconcile_started_); ASSERT_EQ(signin_metrics::ACCOUNT_RECONCILOR_OK, reconcilor->GetState()); } // Checks that the reconcilor does not log out unverified accounts. -TEST_P(AccountReconcilorDiceEndpointParamTest, UnverifiedAccountNoop) { +TEST_F(AccountReconcilorDiceTest, UnverifiedAccountNoop) { // Add a unverified account to the Gaia cookie. signin::SetListAccountsResponseOneAccountWithParams( {"user@gmail.com", "12345", true /* valid */, false /* signed_out */, @@ -1524,7 +1352,6 @@ &test_url_loader_factory_); // Check that nothing happens. - EXPECT_CALL(*GetMockReconcilor(), PerformMergeAction(testing::_)).Times(0); EXPECT_CALL(*GetMockReconcilor(), PerformLogoutAllAccountsAction()).Times(0); EXPECT_CALL(*GetMockReconcilor(), PerformSetCookiesAction(testing::_)) .Times(0); @@ -1539,7 +1366,7 @@ // Checks that the reconcilor does not log out unverified accounts when adding // a new account to the Gaia cookie. -TEST_P(AccountReconcilorDiceEndpointParamTest, UnverifiedAccountMerge) { +TEST_F(AccountReconcilorDiceTest, UnverifiedAccountMerge) { // Add a unverified account to the Gaia cookie. signin::SetListAccountsResponseOneAccountWithParams( {"user@gmail.com", "12345", true /* valid */, false /* signed_out */, @@ -1550,14 +1377,6 @@ const CoreAccountId chrome_account_id = identity_test_env()->MakeAccountAvailable("other@gmail.com").account_id; - if (!IsMultiloginEnabled()) { - // Check that the Chrome account is merged and the unverified account is not - // logged out. - EXPECT_CALL(*GetMockReconcilor(), PerformMergeAction(chrome_account_id)) - .Times(1); - EXPECT_CALL(*GetMockReconcilor(), PerformLogoutAllAccountsAction()) - .Times(0); - } else { // In PRESERVE mode it is up to Gaia to not delete existing accounts in // cookies and not sign out unveridied accounts. std::vector<CoreAccountId> accounts_to_send = {chrome_account_id}; @@ -1565,27 +1384,17 @@ gaia::MultiloginMode::MULTILOGIN_PRESERVE_COOKIE_ACCOUNTS_ORDER, accounts_to_send); EXPECT_CALL(*GetMockReconcilor(), PerformSetCookiesAction(params)); - } AccountReconcilor* reconcilor = GetMockReconcilor(); reconcilor->StartReconcile(AccountReconcilor::Trigger::kCookieChange); ASSERT_TRUE(reconcilor->is_reconcile_started_); base::RunLoop().RunUntilIdle(); - if (!IsMultiloginEnabled()) { - SimulateAddAccountToCookieCompleted( - reconcilor, chrome_account_id, GoogleServiceAuthError::AuthErrorNone()); - } else { SimulateSetAccountsInCookieCompleted( reconcilor, signin::SetAccountsInCookieResult::kSuccess); - } ASSERT_FALSE(reconcilor->is_reconcile_started_); ASSERT_EQ(signin_metrics::ACCOUNT_RECONCILOR_OK, reconcilor->GetState()); } -INSTANTIATE_TEST_SUITE_P(TestDiceEndpoint, - AccountReconcilorDiceEndpointParamTest, - ::testing::ValuesIn({false, true})); - TEST_F(AccountReconcilorTest, DiceDeleteCookie) { SetAccountConsistency(signin::AccountConsistencyMethod::kDice); @@ -2617,9 +2426,6 @@ AccountReconcilor* reconcilor = GetMockReconcilor(); ASSERT_TRUE(reconcilor); - if (!reconcilor->IsMultiloginEndpointEnabled()) { - EXPECT_CALL(*GetMockReconcilor(), PerformMergeAction(account_id)); - } else { switch (account_consistency) { case signin::AccountConsistencyMethod::kMirror: { signin::MultiloginParameters params( @@ -2639,20 +2445,14 @@ NOTREACHED(); break; } - } ASSERT_FALSE(reconcilor->is_reconcile_started_); reconcilor->StartReconcile(AccountReconcilor::Trigger::kCookieChange); ASSERT_TRUE(reconcilor->is_reconcile_started_); base::RunLoop().RunUntilIdle(); - if (!reconcilor->IsMultiloginEndpointEnabled()) { - SimulateAddAccountToCookieCompleted( - reconcilor, account_id, GoogleServiceAuthError::AuthErrorNone()); - } else { SimulateSetAccountsInCookieCompleted( reconcilor, signin::SetAccountsInCookieResult::kSuccess); - } ASSERT_FALSE(reconcilor->is_reconcile_started_); }
diff --git a/components/signin/core/browser/dice_account_reconcilor_delegate.cc b/components/signin/core/browser/dice_account_reconcilor_delegate.cc index 08dd3c8..ee59bfb 100644 --- a/components/signin/core/browser/dice_account_reconcilor_delegate.cc +++ b/components/signin/core/browser/dice_account_reconcilor_delegate.cc
@@ -14,9 +14,6 @@ #include "components/signin/public/base/signin_client.h" #include "components/signin/public/base/signin_pref_names.h" -const base::Feature kUseMultiloginEndpoint{"UseMultiloginEndpoint", - base::FEATURE_ENABLED_BY_DEFAULT}; - namespace signin { DiceAccountReconcilorDelegate::DiceAccountReconcilorDelegate( @@ -31,10 +28,6 @@ return true; } -bool DiceAccountReconcilorDelegate::IsMultiloginEndpointEnabled() const { - return base::FeatureList::IsEnabled(kUseMultiloginEndpoint); -} - DiceAccountReconcilorDelegate::InconsistencyReason DiceAccountReconcilorDelegate::GetInconsistencyReason( const CoreAccountId& primary_account,
diff --git a/components/signin/core/browser/dice_account_reconcilor_delegate.h b/components/signin/core/browser/dice_account_reconcilor_delegate.h index 534a2be..1cb43ab 100644 --- a/components/signin/core/browser/dice_account_reconcilor_delegate.h +++ b/components/signin/core/browser/dice_account_reconcilor_delegate.h
@@ -13,9 +13,6 @@ class SigninClient; -// Enables usage of Gaia Auth Multilogin endpoint for identity consistency. -extern const base::Feature kUseMultiloginEndpoint; - namespace signin { // AccountReconcilorDelegate specialized for Dice. @@ -27,7 +24,6 @@ // AccountReconcilorDelegate: bool IsReconcileEnabled() const override; - bool IsMultiloginEndpointEnabled() const override; gaia::GaiaSource GetGaiaApiSource() const override; CoreAccountId GetFirstGaiaAccountForReconcile( const std::vector<CoreAccountId>& chrome_accounts,
diff --git a/components/spellcheck/renderer/spellcheck_unittest.cc b/components/spellcheck/renderer/spellcheck_unittest.cc index 387fb378..c2d149a 100644 --- a/components/spellcheck/renderer/spellcheck_unittest.cc +++ b/components/spellcheck/renderer/spellcheck_unittest.cc
@@ -1065,12 +1065,12 @@ TEST_F(SpellCheckTest, SpellCheckParagraphLongSentence) { std::vector<SpellCheckResult> expected; // The text is taken from US constitution preamble. - const std::u16string text = - u"We the people of the United States, in order to form a more perfect " - u"union, establish justice, insure domestic tranquility, provide for " - u"the common defense, promote the general welfare, and secure the " - u"blessings of liberty to ourselves and our posterity, do ordain and " - u"establish this Constitution for the United States of America."; + const std::u16string text = base::UTF8ToUTF16( + "We the people of the United States, in order to form a more perfect " + "union, establish justice, insure domestic tranquility, provide for " + "the common defense, promote the general welfare, and secure the " + "blessings of liberty to ourselves and our posterity, do ordain and " + "establish this Constitution for the United States of America."); TestSpellCheckParagraph(text, expected); } @@ -1080,12 +1080,12 @@ std::vector<SpellCheckResult> expected; // All 'the' are converted to 'hte' in US consitition preamble. - const std::u16string text = - u"We hte people of hte United States, in order to form a more perfect " - u"union, establish justice, insure domestic tranquility, provide for " - u"hte common defense, promote hte general welfare, and secure hte " - u"blessings of liberty to ourselves and our posterity, do ordain and " - u"establish this Constitution for hte United States of America."; + const std::u16string text = base::UTF8ToUTF16( + "We hte people of hte United States, in order to form a more perfect " + "union, establish justice, insure domestic tranquility, provide for " + "hte common defense, promote hte general welfare, and secure hte " + "blessings of liberty to ourselves and our posterity, do ordain and " + "establish this Constitution for hte United States of America."); expected.push_back(SpellCheckResult( SpellCheckResult::SPELLING, 3, 3));
diff --git a/components/sync/driver/sync_session_durations_metrics_recorder.cc b/components/sync/driver/sync_session_durations_metrics_recorder.cc index cfc30e4c..fc69abef 100644 --- a/components/sync/driver/sync_session_durations_metrics_recorder.cc +++ b/components/sync/driver/sync_session_durations_metrics_recorder.cc
@@ -186,6 +186,10 @@ void SyncSessionDurationsMetricsRecorder::UpdateSyncAndAccountStatus( FeatureState new_sync_status, FeatureState new_account_status) { + DVLOG(1) << "UpdateSyncAndAccountStatus:" + << " new_sync_status: " << static_cast<int>(new_sync_status) + << " new_account_status: " << static_cast<int>(new_account_status); + // |new_sync_status| may be unknown when there is a primary account, but // the sync engine has not yet started. DCHECK_NE(FeatureState::UNKNOWN, new_account_status); @@ -198,28 +202,8 @@ } void SyncSessionDurationsMetricsRecorder::HandleSyncAndAccountChange() { - if (!sync_service_ || !sync_service_->CanSyncFeatureStart()) { - // Only the account status needs to be updated when sync is off. - UpdateSyncAndAccountStatus(FeatureState::OFF, - DeterminePrimaryAccountStatus()); - return; - } - - // Sync has potential to turn on, or get into account error state. - if (sync_service_->GetAuthError().state() == - GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS) { - // Sync is enabled, but we have an account issue. - UpdateSyncAndAccountStatus(FeatureState::ON, FeatureState::OFF); - } else if (sync_service_->IsSyncFeatureActive() && - sync_service_->HasCompletedSyncCycle()) { - // Sync is on and running, we must have an account too. - UpdateSyncAndAccountStatus(FeatureState::ON, FeatureState::ON); - } else { - // This branch corresponds to the case when the sync engine is initializing. - // The sync state may already be set to ON/OFF based on the heuristics - // above. Keep the current sync status. - UpdateSyncAndAccountStatus(sync_status_, DeterminePrimaryAccountStatus()); - } + UpdateSyncAndAccountStatus(DetermineSyncStatus(), + DeterminePrimaryAccountStatus()); } // static @@ -285,8 +269,9 @@ SyncSessionDurationsMetricsRecorder::FeatureState SyncSessionDurationsMetricsRecorder::DeterminePrimaryAccountStatus() const { - if (!identity_manager_->HasPrimaryAccount(signin::ConsentLevel::kSignin)) + if (!identity_manager_->HasPrimaryAccount(signin::ConsentLevel::kSignin)) { return SyncSessionDurationsMetricsRecorder::FeatureState::OFF; + } CoreAccountId primary_account_id = identity_manager_->GetPrimaryAccountId(signin::ConsentLevel::kSignin); @@ -297,4 +282,35 @@ : SyncSessionDurationsMetricsRecorder::FeatureState::OFF; } +SyncSessionDurationsMetricsRecorder::FeatureState +SyncSessionDurationsMetricsRecorder::DetermineSyncStatus() const { + if (!sync_service_ || !sync_service_->CanSyncFeatureStart()) { + return FeatureState::OFF; + } + + if (sync_service_->GetTransportState() == + SyncService::TransportState::PAUSED) { + // Sync is considered to be ON even when paused. + return FeatureState::ON; + } + + if (sync_service_->IsSyncFeatureActive() && + sync_service_->HasCompletedSyncCycle()) { + return FeatureState::ON; + } + + // This branch corresponds to the case when the sync engine is initializing. + // + // The sync state may already be set to ON/OFF if updated previously. Return + // the current sync status. + // + // Note: It is possible for |sync_status_| to be ON/OFF at this point. This + // corresponds to sync state transitions that can happen if a turns sync on + // or off. For example if during browser startup there is no signed-in user, + /// then |sync_state_| is OFF. When the user turns on Sync, the sync state + // is essentially unknown for a while - the current implementation keeps + // previous |sync_state_|. + return sync_status_; +} + } // namespace syncer
diff --git a/components/sync/driver/sync_session_durations_metrics_recorder.h b/components/sync/driver/sync_session_durations_metrics_recorder.h index ab443bd5..a381fd281 100644 --- a/components/sync/driver/sync_session_durations_metrics_recorder.h +++ b/components/sync/driver/sync_session_durations_metrics_recorder.h
@@ -76,6 +76,9 @@ // refresh token in the identity manager. FeatureState DeterminePrimaryAccountStatus() const; + // Determines the syns status.. + FeatureState DetermineSyncStatus() const; + SyncService* const sync_service_; signin::IdentityManager* const identity_manager_;
diff --git a/components/sync/driver/sync_session_durations_metrics_recorder_unittest.cc b/components/sync/driver/sync_session_durations_metrics_recorder_unittest.cc index b2efb404..3bb4f132 100644 --- a/components/sync/driver/sync_session_durations_metrics_recorder_unittest.cc +++ b/components/sync/driver/sync_session_durations_metrics_recorder_unittest.cc
@@ -17,11 +17,12 @@ namespace syncer { namespace { +constexpr base::TimeDelta kSessionTime = base::TimeDelta::FromSeconds(10); + class SyncSessionDurationsMetricsRecorderTest : public testing::Test { public: SyncSessionDurationsMetricsRecorderTest() - : identity_test_env_(&test_url_loader_factory_), - session_time_(base::TimeDelta::FromSeconds(10)) { + : identity_test_env_(&test_url_loader_factory_) { sync_service_.SetIsAuthenticatedAccountPrimary(false); sync_service_.SetDisableReasons(SyncService::DISABLE_REASON_NOT_SIGNED_IN); } @@ -32,6 +33,7 @@ identity_test_env_.MakePrimaryAccountAvailable("foo@gmail.com"); sync_service_.SetIsAuthenticatedAccountPrimary(true); sync_service_.SetDisableReasons(SyncService::DisableReasonSet()); + sync_service_.FireStateChanged(); } void SetInvalidCredentialsAuthError() { @@ -42,17 +44,33 @@ signin::ConsentLevel::kSync), auth_error); sync_service_.SetAuthError(auth_error); + sync_service_.SetTransportState(SyncService::TransportState::PAUSED); + } + + void ClearAuthError() { + identity_test_env_.SetRefreshTokenForPrimaryAccount(); + sync_service_.SetAuthError(GoogleServiceAuthError::AuthErrorNone()); + sync_service_.SetTransportState(SyncService::TransportState::ACTIVE); } std::string GetSessionHistogramName(const std::string& histogram_suffix) { return std::string("Session.TotalDuration.") + histogram_suffix; } + void ExpectOneSessionWithDuration( + const base::HistogramTester& ht, + const std::vector<std::string>& histogram_suffixes, + const base::TimeDelta& expected_session_time) { + for (const auto& histogram_suffix : histogram_suffixes) { + ht.ExpectTimeBucketCount(GetSessionHistogramName(histogram_suffix), + expected_session_time, 1); + } + } + void ExpectOneSession(const base::HistogramTester& ht, const std::vector<std::string>& histogram_suffixes) { for (const auto& histogram_suffix : histogram_suffixes) { - ht.ExpectTimeBucketCount(GetSessionHistogramName(histogram_suffix), - session_time_, 1); + ht.ExpectTotalCount(GetSessionHistogramName(histogram_suffix), 1); } } @@ -63,11 +81,11 @@ } } - void StartAndEndSession() { + void StartAndEndSession(const base::TimeDelta& session_time) { SyncSessionDurationsMetricsRecorder metrics_recorder( &sync_service_, identity_test_env_.identity_manager()); metrics_recorder.OnSessionStarted(base::TimeTicks::Now()); - metrics_recorder.OnSessionEnded(session_time_); + metrics_recorder.OnSessionEnded(session_time); } protected: @@ -75,16 +93,15 @@ network::TestURLLoaderFactory test_url_loader_factory_; signin::IdentityTestEnvironment identity_test_env_; TestSyncService sync_service_; - const base::TimeDelta session_time_; DISALLOW_COPY_AND_ASSIGN(SyncSessionDurationsMetricsRecorderTest); }; TEST_F(SyncSessionDurationsMetricsRecorderTest, WebSignedOut) { base::HistogramTester ht; - StartAndEndSession(); + StartAndEndSession(kSessionTime); - ExpectOneSession(ht, {"WithoutAccount"}); + ExpectOneSessionWithDuration(ht, {"WithoutAccount"}, kSessionTime); ExpectNoSession(ht, {"WithAccount"}); } @@ -92,17 +109,18 @@ identity_test_env_.SetCookieAccounts({{"foo@gmail.com", "foo_gaia_id"}}); base::HistogramTester ht; - StartAndEndSession(); + StartAndEndSession(kSessionTime); - ExpectOneSession(ht, {"WithAccount"}); + ExpectOneSessionWithDuration(ht, {"WithAccount"}, kSessionTime); ExpectNoSession(ht, {"WithoutAccount"}); } TEST_F(SyncSessionDurationsMetricsRecorderTest, NotOptedInToSync) { base::HistogramTester ht; - StartAndEndSession(); + StartAndEndSession(kSessionTime); - ExpectOneSession(ht, {"NotOptedInToSyncWithoutAccount"}); + ExpectOneSessionWithDuration(ht, {"NotOptedInToSyncWithoutAccount"}, + kSessionTime); ExpectNoSession(ht, {"NotOptedInToSyncWithAccount", "OptedInToSyncWithoutAccount", "OptedInToSyncWithAccount"}); @@ -112,9 +130,9 @@ EnableSync(); base::HistogramTester ht; - StartAndEndSession(); + StartAndEndSession(kSessionTime); - ExpectOneSession(ht, {"OptedInToSyncWithAccount"}); + ExpectOneSessionWithDuration(ht, {"OptedInToSyncWithAccount"}, kSessionTime); ExpectNoSession( ht, {"NotOptedInToSyncWithoutAccount", "NotOptedInToSyncWithoutAccount", "OptedInToSyncWithoutAccount"}); @@ -126,12 +144,13 @@ sync_service_.SetDisableReasons(SyncService::DISABLE_REASON_USER_CHOICE); base::HistogramTester ht; - StartAndEndSession(); + StartAndEndSession(kSessionTime); // If the user opted in to sync, but then disabled sync (e.g. via policy or // from the Android OS settings), then they are counted as having opted out // of sync. - ExpectOneSession(ht, {"NotOptedInToSyncWithAccount"}); + ExpectOneSessionWithDuration(ht, {"NotOptedInToSyncWithAccount"}, + kSessionTime); ExpectNoSession( ht, {"NotOptedInToSyncWithoutAccount", "OptedInToSyncWithoutAccount", "OptedInToSyncWithAccount"}); @@ -143,9 +162,10 @@ SetInvalidCredentialsAuthError(); base::HistogramTester ht; - StartAndEndSession(); + StartAndEndSession(kSessionTime); - ExpectOneSession(ht, {"OptedInToSyncWithoutAccount"}); + ExpectOneSessionWithDuration(ht, {"OptedInToSyncWithoutAccount"}, + kSessionTime); ExpectNoSession( ht, {"NotOptedInToSyncWithoutAccount", "NotOptedInToSyncWithoutAccount", "OptedInToSyncWithAccount"}); @@ -158,21 +178,22 @@ sync_service_.SetDisableReasons(SyncService::DISABLE_REASON_USER_CHOICE); base::HistogramTester ht; - StartAndEndSession(); + StartAndEndSession(kSessionTime); // If the user opted in to sync, but then disabled sync (e.g. via policy or // from the Android OS settings), then they are counted as having opted out // of sync. // The account is in auth error, so they are also counted as not having any // browser account. - ExpectOneSession(ht, {"NotOptedInToSyncWithoutAccount"}); + ExpectOneSessionWithDuration(ht, {"NotOptedInToSyncWithoutAccount"}, + kSessionTime); ExpectNoSession(ht, {"NotOptedInToSyncWithAccount", "OptedInToSyncWithoutAccount", "OptedInToSyncWithAccount"}); } TEST_F(SyncSessionDurationsMetricsRecorderTest, - NotOptedInToSync_AccountInAuthError) { + NotOptedInToSync_SecondaryAccountInAuthError) { AccountInfo account = identity_test_env_.MakeAccountAvailable("foo@gmail.com"); identity_test_env_.UpdatePersistentErrorOfRefreshTokenForAccount( @@ -180,15 +201,148 @@ GoogleServiceAuthError(GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS)); base::HistogramTester ht; - StartAndEndSession(); + StartAndEndSession(kSessionTime); // The account is in auth error, so they are counted as not having any browser // account. - ExpectOneSession(ht, {"NotOptedInToSyncWithoutAccount"}); + ExpectOneSessionWithDuration(ht, {"NotOptedInToSyncWithoutAccount"}, + kSessionTime); ExpectNoSession(ht, {"NotOptedInToSyncWithAccount", "OptedInToSyncWithoutAccount", "OptedInToSyncWithAccount"}); } +TEST_F(SyncSessionDurationsMetricsRecorderTest, SyncUnknownOnStartup) { + EnableSync(); + + // Simulate sync initializing (before first connection to the server). + sync_service_.SetLastCycleSnapshot(syncer::SyncCycleSnapshot()); + ASSERT_TRUE(sync_service_.IsSyncFeatureActive()); + ASSERT_FALSE(sync_service_.HasCompletedSyncCycle()); + + base::HistogramTester ht; + StartAndEndSession(kSessionTime); + ExpectOneSessionWithDuration(ht, {"NotOptedInToSyncWithAccount"}, + kSessionTime); + ExpectNoSession( + ht, {"NotOptedInToSyncWithoutAccount", "OptedInToSyncWithoutAccount", + "OptedInToSyncWithoutAccount"}); +} + +TEST_F(SyncSessionDurationsMetricsRecorderTest, + SyncUnknownOnStartupThenStarts) { + EnableSync(); + + // Simulate sync initializing (before first connection to the server). + auto active_sync_snapshot = sync_service_.GetLastCycleSnapshotForDebugging(); + sync_service_.SetLastCycleSnapshot(syncer::SyncCycleSnapshot()); + ASSERT_TRUE(sync_service_.IsSyncFeatureActive()); + ASSERT_FALSE(sync_service_.HasCompletedSyncCycle()); + + SyncSessionDurationsMetricsRecorder metrics_recorder( + &sync_service_, identity_test_env_.identity_manager()); + + { + base::HistogramTester ht; + metrics_recorder.OnSessionStarted(base::TimeTicks::Now()); + + // Activate sync + sync_service_.SetLastCycleSnapshot(active_sync_snapshot); + ASSERT_TRUE(sync_service_.IsSyncFeatureActive() && + sync_service_.HasCompletedSyncCycle()); + metrics_recorder.OnStateChanged(&sync_service_); + // Sync was in unknown state, so histograms should not be logged. + ExpectNoSession( + ht, {"NotOptedInToSyncWithAccount", "NotOptedInToSyncWithoutAccount", + "OptedInToSyncWithoutAccount", "OptedInToSyncWithoutAccount"}); + } + + { + base::HistogramTester ht; + metrics_recorder.OnSessionEnded(kSessionTime); + ExpectOneSession(ht, {"OptedInToSyncWithAccount"}); + ExpectNoSession( + ht, {"NotOptedInToSyncWithAccount", "NotOptedInToSyncWithoutAccount", + "OptedInToSyncWithoutAccount"}); + } +} + +TEST_F(SyncSessionDurationsMetricsRecorderTest, EnableSync) { + SyncSessionDurationsMetricsRecorder metrics_recorder( + &sync_service_, identity_test_env_.identity_manager()); + + { + base::HistogramTester ht; + metrics_recorder.OnSessionStarted(base::TimeTicks::Now()); + EnableSync(); + // The initial state of the record was: sync_status = OFF, acount_status=OFF + // When sync gets initialized, 2 things happen: + // 1. account_status=ON. => Log NotOptedInToSyncWithoutAccount + // 2. sync_status=ON => Log NotOptedInToSyncWithAccount + ExpectOneSession(ht, {"NotOptedInToSyncWithoutAccount"}); + ExpectOneSession(ht, {"NotOptedInToSyncWithAccount"}); + ExpectNoSession( + ht, {"OptedInToSyncWithoutAccount", "OptedInToSyncWithAccount"}); + } + + { + base::HistogramTester ht; + metrics_recorder.OnSessionEnded(kSessionTime); + ExpectOneSession(ht, {"OptedInToSyncWithAccount"}); + ExpectNoSession( + ht, {"NotOptedInToSyncWithoutAccount", "NotOptedInToSyncWithoutAccount", + "OptedInToSyncWithoutAccount"}); + } +} + +TEST_F(SyncSessionDurationsMetricsRecorderTest, EnterAuthError) { + EnableSync(); + SyncSessionDurationsMetricsRecorder metrics_recorder( + &sync_service_, identity_test_env_.identity_manager()); + + { + base::HistogramTester ht; + metrics_recorder.OnSessionStarted(base::TimeTicks::Now()); + SetInvalidCredentialsAuthError(); + ExpectOneSession(ht, {"OptedInToSyncWithAccount"}); + ExpectNoSession( + ht, {"NotOptedInToSyncWithAccount", "NotOptedInToSyncWithoutAccount", + "OptedInToSyncWithoutAccount"}); + } + { + base::HistogramTester ht; + metrics_recorder.OnSessionEnded(kSessionTime); + ExpectOneSession(ht, {"OptedInToSyncWithoutAccount"}); + ExpectNoSession( + ht, {"NotOptedInToSyncWithAccount", "NotOptedInToSyncWithoutAccount", + "OptedInToSyncWithAccount"}); + } +} + +TEST_F(SyncSessionDurationsMetricsRecorderTest, FixedAuthError) { + EnableSync(); + SetInvalidCredentialsAuthError(); + SyncSessionDurationsMetricsRecorder metrics_recorder( + &sync_service_, identity_test_env_.identity_manager()); + + { + base::HistogramTester ht; + metrics_recorder.OnSessionStarted(base::TimeTicks::Now()); + ClearAuthError(); + ExpectOneSession(ht, {"OptedInToSyncWithoutAccount"}); + ExpectNoSession( + ht, {"NotOptedInToSyncWithAccount", "NotOptedInToSyncWithoutAccount", + "OptedInToSyncWithAccount"}); + } + { + base::HistogramTester ht; + metrics_recorder.OnSessionEnded(kSessionTime); + ExpectOneSession(ht, {"OptedInToSyncWithAccount"}); + ExpectNoSession( + ht, {"NotOptedInToSyncWithAccount", "NotOptedInToSyncWithoutAccount", + "OptedInToSyncWithoutAccount"}); + } +} + } // namespace } // namespace syncer
diff --git a/components/test/data/payments/payment_handler_installer.js b/components/test/data/payments/payment_handler_installer.js index c833d2b..0d8a1086 100644 --- a/components/test/data/payments/payment_handler_installer.js +++ b/components/test/data/payments/payment_handler_installer.js
@@ -34,30 +34,6 @@ } /** - * Installs the given payment handler with the given payment method and - * capabilities. - * @param {string} swUrl - The relative URL of the service worker JavaScript - * file to install. - * @param {string} method - The payment method that this service worker - * supports. - * @param {object} capabilities - The capabilities of this payment handler, such - * as 'supportedNetworks': ['visa', 'mastercard', 'amex']. - * @return {Promise<string>} - 'success' or error message on failure. - */ -async function installWithCapabilities(swUrl, method, capabilities) { // eslint-disable-line no-unused-vars, max-len - try { - const registration = await navigator.serviceWorker.register(swUrl); - await activation(registration); - await registration.paymentManager.instruments.set( - 'instrument-for-' + method, - {name: 'Instrument Name', method, capabilities}); - return 'success'; - } catch (e) { - return e.message; - } -} - -/** * Returns a promise that resolves when the service worker of the given * registration has activated. * @param {ServiceWorkerRegistration} registration - A service worker
diff --git a/components/test/data/payments/show_promise/app.js b/components/test/data/payments/show_promise/app.js index cec6d41..55174726 100644 --- a/components/test/data/payments/show_promise/app.js +++ b/components/test/data/payments/show_promise/app.js
@@ -4,6 +4,11 @@ * found in the LICENSE file. */ +self.addEventListener('canmakepayment', (evt) => { + evt.respondWith(true); +}); + self.addEventListener('paymentrequest', (evt) => { - evt.respondWith({methodName: 'basic-card', details: evt.total}); + evt.respondWith( + {methodName: evt.methodData[0].supportedMethods, details: evt.total}); });
diff --git a/components/test/data/payments/show_promise/app_installer.js b/components/test/data/payments/show_promise/app_installer.js index f5c84301..eab7364e 100644 --- a/components/test/data/payments/show_promise/app_installer.js +++ b/components/test/data/payments/show_promise/app_installer.js
@@ -34,11 +34,11 @@ } registration.paymentManager.instruments - .set('123456', {name: 'Echo Pay', method: 'basic-card'}) + .set( + '123456', + {name: 'Echo Pay', method: window.location.href}) .then(() => { - output( - 'instruments.set()', - 'Payment handler installed.'); + output('instruments.set()', 'Payment handler installed.'); }) .catch((error) => { output('instruments.set()', error);
diff --git a/components/test/data/payments/show_promise/digital_goods.js b/components/test/data/payments/show_promise/digital_goods.js index 86434ff..88f58036 100644 --- a/components/test/data/payments/show_promise/digital_goods.js +++ b/components/test/data/payments/show_promise/digital_goods.js
@@ -8,10 +8,15 @@ /** * Create an instance of PaymentRequest. + * @param {DOMString} supportedMethods - The payment method name. If absent, + * then the page URL is used instead. */ -function create() { // eslint-disable-line no-unused-vars +function create(supportedMethods) { // eslint-disable-line no-unused-vars + if (!supportedMethods) { + supportedMethods = window.location.href; + } try { - request = new PaymentRequest([{supportedMethods: 'basic-card'}], { + request = new PaymentRequest([{supportedMethods}], { total: {label: 'PENDING TOTAL', amount: {currency: 'USD', value: '99.99'}}, });
diff --git a/components/test/data/payments/show_promise/invalid_details.html b/components/test/data/payments/show_promise/invalid_details.html index b593264..01b0fd51 100644 --- a/components/test/data/payments/show_promise/invalid_details.html +++ b/components/test/data/payments/show_promise/invalid_details.html
@@ -16,6 +16,7 @@ <div><button onclick="buy()" id="buy">Buy</button></div> <pre id="result"></pre> <script src="../util.js"></script> + <script src="app_installer.js"></script> <script src="invalid_details.js"></script> </body> </html> \ No newline at end of file
diff --git a/components/test/data/payments/show_promise/invalid_details.js b/components/test/data/payments/show_promise/invalid_details.js index 47dc79a..3e2cdb02 100644 --- a/components/test/data/payments/show_promise/invalid_details.js +++ b/components/test/data/payments/show_promise/invalid_details.js
@@ -6,10 +6,17 @@ /** * Launch PaymentRequest with a show promise that resolve with invalid details. + * @param {boolean} useUrlPaymentMethod - Whether URL payment method should be + * used. Useful for payment handlers, which cannot use basic-card payment + * method. By default, basic-card payment method is used. */ -function buy() { // eslint-disable-line no-unused-vars +function buy(useUrlPaymentMethod) { // eslint-disable-line no-unused-vars try { - new PaymentRequest([{supportedMethods: 'basic-card'}], { + let supportedMethods = 'basic-card'; + if (useUrlPaymentMethod) { + supportedMethods = window.location.href; + } + new PaymentRequest([{supportedMethods}], { total: { label: 'PENDING TOTAL', amount: {currency: 'USD', value: '99.99'},
diff --git a/components/test/data/payments/show_promise/reject.html b/components/test/data/payments/show_promise/reject.html index 4ca8eb3..5c9e073 100644 --- a/components/test/data/payments/show_promise/reject.html +++ b/components/test/data/payments/show_promise/reject.html
@@ -16,6 +16,7 @@ <div><button onclick="buy()" id="buy">Buy</button></div> <pre id="result"></pre> <script src="../util.js"></script> + <script src="app_installer.js"></script> <script src="reject.js"></script> </body> </html> \ No newline at end of file
diff --git a/components/test/data/payments/show_promise/reject.js b/components/test/data/payments/show_promise/reject.js index 12ab3b2..5beb189 100644 --- a/components/test/data/payments/show_promise/reject.js +++ b/components/test/data/payments/show_promise/reject.js
@@ -6,11 +6,18 @@ /** * Launch PaymentRequest with a show promise and reject that promise. + * @param {boolean} useUrlPaymentMethod - Whether URL payment method should be + * used. Useful for payment handlers, which cannot use basic-card payment + * method. By default, basic-card payment method is used. */ -function buy() { // eslint-disable-line no-unused-vars +function buy(useUrlPaymentMethod) { // eslint-disable-line no-unused-vars try { + let supportedMethods = 'basic-card'; + if (useUrlPaymentMethod) { + supportedMethods = window.location.href; + } new PaymentRequest( - [{supportedMethods: 'basic-card'}], + [{supportedMethods}], {total: {label: 'Total', amount: {currency: 'USD', value: '1.00'}}}) .show(new Promise(function(resolve, reject) { reject();
diff --git a/components/test/data/payments/show_promise/resolve_with_empty_dictionary.js b/components/test/data/payments/show_promise/resolve_with_empty_dictionary.js index 1aae935..e8e6386 100644 --- a/components/test/data/payments/show_promise/resolve_with_empty_dictionary.js +++ b/components/test/data/payments/show_promise/resolve_with_empty_dictionary.js
@@ -7,11 +7,18 @@ /** * Launch PaymentRequest with a show promise that resolves with an empty * dictionary. + * @param {boolean} useUrlPaymentMethod - Whether URL payment method should be + * used. Useful for payment handlers, which cannot use basic-card payment + * method. By default, basic-card payment method is used. */ -function buy() { // eslint-disable-line no-unused-vars +function buy(useUrlPaymentMethod) { // eslint-disable-line no-unused-vars try { + let supportedMethods = 'basic-card'; + if (useUrlPaymentMethod) { + supportedMethods = window.location.href; + } var request = new PaymentRequest( - [{supportedMethods: 'basic-card'}], { + [{supportedMethods}], { total: { label: 'Total', amount: {currency: 'USD', value: '3.00'}, @@ -21,7 +28,7 @@ amount: {currency: 'USD', value: '1.00'}, }], modifiers: [{ - supportedMethods: 'basic-card', + supportedMethods, additionalDisplayItems: [{ label: 'Modifier', pending: true,
diff --git a/components/test/data/payments/show_promise/resolve_with_empty_lists.js b/components/test/data/payments/show_promise/resolve_with_empty_lists.js index 12a446f3..955cb84 100644 --- a/components/test/data/payments/show_promise/resolve_with_empty_lists.js +++ b/components/test/data/payments/show_promise/resolve_with_empty_lists.js
@@ -7,11 +7,18 @@ /** * Launch PaymentRequest by resolving the promised passed into the shoe() method * with empty lists of display items, modifiers, and shipping options. + * @param {boolean} useUrlPaymentMethod - Whether URL payment method should be + * used. Useful for payment handlers, which cannot use basic-card payment + * method. By default, basic-card payment method is used. */ -function buy() { // eslint-disable-line no-unused-vars +function buy(useUrlPaymentMethod) { // eslint-disable-line no-unused-vars try { + let supportedMethods = 'basic-card'; + if (useUrlPaymentMethod) { + supportedMethods = window.location.href; + } var request = new PaymentRequest( - [{supportedMethods: 'basic-card'}], { + [{supportedMethods}], { total: {label: 'Total', amount: {currency: 'USD', value: '1.00'}}, displayItems: [{ label: 'PENDING DISPLAY ITEM',
diff --git a/components/test/data/payments/show_promise/single_option_shipping.js b/components/test/data/payments/show_promise/single_option_shipping.js index 298597d..3fd7a65 100644 --- a/components/test/data/payments/show_promise/single_option_shipping.js +++ b/components/test/data/payments/show_promise/single_option_shipping.js
@@ -7,11 +7,19 @@ /** * Launch PaymentRequest with a show promise and a single pre-selected option * for shipping worldwide. + * @param {boolean} useUrlPaymentMethod - Whether URL payment method should be + * used. Useful for payment handlers, which cannot use basic-card payment + * method. By default, basic-card payment method is used. */ -function buy() { // eslint-disable-line no-unused-vars +function buy(useUrlPaymentMethod) { // eslint-disable-line no-unused-vars try { + let supportedMethods = 'basic-card'; + if (useUrlPaymentMethod) { + supportedMethods = window.location.href; + } new PaymentRequest( - [{supportedMethods: 'basic-card'}], { + [{supportedMethods}], + { total: { label: 'PENDING TOTAL', amount: {currency: 'USD', value: '99.99'},
diff --git a/components/test/data/payments/show_promise/single_option_shipping_with_update.js b/components/test/data/payments/show_promise/single_option_shipping_with_update.js index 16dd289..b419c1f 100644 --- a/components/test/data/payments/show_promise/single_option_shipping_with_update.js +++ b/components/test/data/payments/show_promise/single_option_shipping_with_update.js
@@ -8,8 +8,15 @@ * Launch PaymentRequest with a show promise and a single pre-selected option * for shipping worldwide and a handler for shipping address change events that * does not change anything. + * @param {DOMString} useUrlPaymentMethod - Whether window.location.href should + * be used as the payment method. Useful for testing service workers, which do + * not support basic-card payment method. */ -function buy() { // eslint-disable-line no-unused-vars +function buy(useUrlPaymentMethod) { // eslint-disable-line no-unused-vars + let paymentMethod = 'basic-card'; + if (useUrlPaymentMethod) { + paymentMethod = window.location.href; + } var finalizedDetails = { total: {label: 'Total', amount: {currency: 'USD', value: '1.00'}}, shippingOptions: [{ @@ -22,7 +29,7 @@ try { var request = new PaymentRequest( - [{supportedMethods: 'basic-card'}], { + [{supportedMethods: paymentMethod}], { total: { label: 'PENDING TOTAL', amount: {currency: 'USD', value: '99.99'},
diff --git a/components/test/data/payments/show_promise/timeout.html b/components/test/data/payments/show_promise/timeout.html index cb7de4c..1371b9c0 100644 --- a/components/test/data/payments/show_promise/timeout.html +++ b/components/test/data/payments/show_promise/timeout.html
@@ -16,6 +16,7 @@ <div><button onclick="buy()" id="buy">Buy</button></div> <pre id="result"></pre> <script src="../util.js"></script> + <script src="app_installer.js"></script> <script src="timeout.js"></script> </body> </html> \ No newline at end of file
diff --git a/components/test/data/payments/show_promise/timeout.js b/components/test/data/payments/show_promise/timeout.js index e536d73..4049451 100644 --- a/components/test/data/payments/show_promise/timeout.js +++ b/components/test/data/payments/show_promise/timeout.js
@@ -10,7 +10,7 @@ function buy() { // eslint-disable-line no-unused-vars try { new PaymentRequest( - [{supportedMethods: 'basic-card'}], + [{supportedMethods: window.location.href}], {total: {label: 'Total', amount: {currency: 'USD', value: '1.00'}}}) .show(new Promise(function(resolve) { /* Intentionally empty. */ })) .catch(function(error) {
diff --git a/components/test/data/payments/show_promise/us_only_shipping.js b/components/test/data/payments/show_promise/us_only_shipping.js index 2fc64da..13cf50b 100644 --- a/components/test/data/payments/show_promise/us_only_shipping.js +++ b/components/test/data/payments/show_promise/us_only_shipping.js
@@ -6,8 +6,14 @@ /** * Launch PaymentRequest with a show promise and US-only shipping. + * @param {bool} useWindowUrlPaymentMethod - Whether the window URL is used as + * the payment method name. If false, then 'basic-card' is used instead. */ -function buy() { // eslint-disable-line no-unused-vars +function buy(useWindowUrlPaymentMethod) { // eslint-disable-line no-unused-vars + supportedMethods = 'basic-card'; + if (useWindowUrlPaymentMethod) { + supportedMethods = window.location.href; + } var detailsForUSAddress = { shippingOptions: [{ id: '1', @@ -21,7 +27,7 @@ try { var request = new PaymentRequest( - [{supportedMethods: 'basic-card'}], { + [{supportedMethods}], { total: { label: 'PENDING TOTAL', amount: {currency: 'USD', value: '99.99'},
diff --git a/components/url_matcher/url_matcher_factory.cc b/components/url_matcher/url_matcher_factory.cc index b6e92847..ae18f6d9 100644 --- a/components/url_matcher/url_matcher_factory.cc +++ b/components/url_matcher/url_matcher_factory.cc
@@ -248,7 +248,7 @@ return nullptr; } - for (const auto& entry : *value_list) { + for (const auto& entry : value_list->GetList()) { const base::ListValue* range = nullptr; if (entry.is_int()) { ranges.push_back(URLMatcherPortFilter::CreateRange(entry.GetInt()));
diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn index c061f4e..f5bca57 100644 --- a/content/browser/BUILD.gn +++ b/content/browser/BUILD.gn
@@ -696,8 +696,6 @@ "cookie_store/cookie_store_host.h", "cookie_store/cookie_store_manager.cc", "cookie_store/cookie_store_manager.h", - "coop_coep_cross_origin_isolated_info.cc", - "coop_coep_cross_origin_isolated_info.h", "data_url_loader_factory.cc", "data_url_loader_factory.h", "device/device_service.cc", @@ -1848,6 +1846,8 @@ "web_contents/web_contents_view_child_frame.h", "web_database/web_database_host_impl.cc", "web_database/web_database_host_impl.h", + "web_exposed_isolation_info.cc", + "web_exposed_isolation_info.h", "web_package/prefetched_signed_exchange_cache.cc", "web_package/prefetched_signed_exchange_cache.h", "web_package/prefetched_signed_exchange_cache_adapter.cc",
diff --git a/content/browser/accessibility/accessibility_action_browsertest.cc b/content/browser/accessibility/accessibility_action_browsertest.cc index a242a88..5922724 100644 --- a/content/browser/accessibility/accessibility_action_browsertest.cc +++ b/content/browser/accessibility/accessibility_action_browsertest.cc
@@ -851,7 +851,7 @@ ax::mojom::ScrollAlignment::kScrollAlignmentClosestEdge); gfx::Rect bounds = target_node->GetUnclippedScreenBoundsRect(); { - testing::Message message; + ::testing::Message message; message << "Expected" << bounds.ToString() << " to be within " << doc_bottom_third.ToString() << " and " << doc_right_third.ToString(); @@ -877,7 +877,7 @@ ax::mojom::ScrollAlignment::kScrollAlignmentTop); bounds = target_node->GetUnclippedScreenBoundsRect(); { - testing::Message message; + ::testing::Message message; message << "Expected" << bounds.ToString() << " to be within " << doc_top_third.ToString() << " and " << doc_left_third.ToString(); EXPECT_TRUE(doc_bounds.Contains(bounds)); @@ -894,7 +894,7 @@ ax::mojom::ScrollAlignment::kScrollAlignmentBottom); bounds = target_node->GetUnclippedScreenBoundsRect(); { - testing::Message message; + ::testing::Message message; message << "Expected" << bounds.ToString() << " to be within " << doc_bottom_third.ToString() << " and " << doc_right_third.ToString(); @@ -938,7 +938,7 @@ ax::mojom::ScrollAlignment::kScrollAlignmentCenter); bounds = target_node->GetUnclippedScreenBoundsRect(); { - testing::Message message; + ::testing::Message message; message << "Expected" << bounds.ToString() << " to not be within " << doc_top_third.ToString() << ", " << doc_bottom_third.ToString() << ", " << doc_left_third.ToString() << ", and "
diff --git a/content/browser/accessibility/accessibility_auralinux_browsertest.cc b/content/browser/accessibility/accessibility_auralinux_browsertest.cc index 4ef27d9..4944591e 100644 --- a/content/browser/accessibility/accessibility_auralinux_browsertest.cc +++ b/content/browser/accessibility/accessibility_auralinux_browsertest.cc
@@ -113,7 +113,7 @@ int expected_start_offset, int expected_end_offset, const char* expected_text) { - testing::Message message; + ::testing::Message message; message << "While checking at index \'" << offset << "\' for \'" << expected_text << "\' at " << expected_start_offset << '-' << expected_end_offset << '.'; @@ -584,7 +584,7 @@ gfx::Rect combined_extents(x, y, width, height); for (int offset = 1; offset < newline_offset; ++offset) { - testing::Message message; + ::testing::Message message; message << "While checking at offset " << offset; SCOPED_TRACE(message); @@ -613,7 +613,7 @@ } { - testing::Message message; + ::testing::Message message; message << "While checking at offset " << newline_offset + 1; SCOPED_TRACE(message); @@ -628,7 +628,7 @@ combined_extents = gfx::Rect(x, y, width, height); for (int offset = newline_offset + 2; offset < n_characters; ++offset) { - testing::Message message; + ::testing::Message message; message << "While checking at offset " << offset; SCOPED_TRACE(message); @@ -679,7 +679,7 @@ // Test that non offscreen characters have increasing x coordinates and a // height that is greater than 1px. { - testing::Message message; + ::testing::Message message; message << "While checking at offset 0"; SCOPED_TRACE(message); @@ -692,7 +692,7 @@ } for (int offset = 1; offset < first_line_end; ++offset) { - testing::Message message; + ::testing::Message message; message << "While checking at offset " << offset; SCOPED_TRACE(message); @@ -709,7 +709,7 @@ } { - testing::Message message; + ::testing::Message message; message << "While checking at offset " << last_line_start; SCOPED_TRACE(message); @@ -722,7 +722,7 @@ } for (int offset = last_line_start + 1; offset < n_characters; ++offset) { - testing::Message message; + ::testing::Message message; message << "While checking at offset " << offset; SCOPED_TRACE(message);
diff --git a/content/browser/accessibility/accessibility_browsertest.cc b/content/browser/accessibility/accessibility_browsertest.cc index 209b8c22..a17673e 100644 --- a/content/browser/accessibility/accessibility_browsertest.cc +++ b/content/browser/accessibility/accessibility_browsertest.cc
@@ -102,15 +102,15 @@ AccessibilityNotificationWaiter selection_waiter( shell()->web_contents(), ui::kAXModeComplete, ax::mojom::Event::kTextSelectionChanged); - ExecuteScript( - u"let selection=document.getSelection();" - u"let range=document.createRange();" - u"let editable=document.querySelector('p[contenteditable=\"true\"]');" - u"editable.focus();" - u"range.setStart(editable.lastChild, 0);" - u"range.setEnd(editable.lastChild, 0);" - u"selection.removeAllRanges();" - u"selection.addRange(range);"); + ExecuteScript(base::UTF8ToUTF16( + "let selection=document.getSelection();" + "let range=document.createRange();" + "let editable=document.querySelector('p[contenteditable=\"true\"]');" + "editable.focus();" + "range.setStart(editable.lastChild, 0);" + "range.setEnd(editable.lastChild, 0);" + "selection.removeAllRanges();" + "selection.addRange(range);")); selection_waiter.WaitForNotification(); }
diff --git a/content/browser/accessibility/accessibility_mode_browsertest.cc b/content/browser/accessibility/accessibility_mode_browsertest.cc index 8922309..32d9eac 100644 --- a/content/browser/accessibility/accessibility_mode_browsertest.cc +++ b/content/browser/accessibility/accessibility_mode_browsertest.cc
@@ -178,7 +178,7 @@ AccessibilityNotificationWaiter waiter2(shell()->web_contents(), ui::AXMode(), ax::mojom::Event::kLoadComplete); - BrowserAccessibilityStateImpl::GetInstance()->AddAccessibilityModeFlags( + content::testing::ScopedContentAXModeSetter ax_mode_setter( ui::AXMode::kScreenReader); waiter2.WaitForNotification();
diff --git a/content/browser/accessibility/accessibility_win_browsertest.cc b/content/browser/accessibility/accessibility_win_browsertest.cc index d2a9a080..b6dfe97 100644 --- a/content/browser/accessibility/accessibility_win_browsertest.cc +++ b/content/browser/accessibility/accessibility_win_browsertest.cc
@@ -583,7 +583,7 @@ LONG expected_start_offset, LONG expected_end_offset, const std::wstring& expected_text) { - testing::Message message; + ::testing::Message message; message << "While checking for \'" << expected_text << "\' at " << expected_start_offset << '-' << expected_end_offset << '.'; SCOPED_TRACE(message); @@ -3683,12 +3683,11 @@ ui::kAXModeComplete, ax::mojom::Event::kValueChanged); // Place an e acute, and two emoticons in the text field. - ExecuteScript( - uR"SCRIPT( + ExecuteScript(base::UTF8ToUTF16(R"SCRIPT( const input = document.querySelector('input'); input.value = 'e\u0301\uD83D\uDC69\u200D\u2764\uFE0F\u200D\uD83D\uDC69\uD83D\uDC36'; - )SCRIPT"); + )SCRIPT")); waiter.WaitForNotification(); LONG n_characters; @@ -4036,11 +4035,10 @@ ui::kAXModeComplete, ax::mojom::Event::kValueChanged); // Add a blank line at the end of the textarea. - ExecuteScript( - uR"SCRIPT( + ExecuteScript(base::UTF8ToUTF16(R"SCRIPT( const textarea = document.querySelector('textarea'); textarea.value += '\n'; - )SCRIPT"); + )SCRIPT")); waiter.WaitForNotification(); // The second last line should have an additional trailing newline. Also,
diff --git a/content/browser/accessibility/ax_platform_node_win_browsertest.cc b/content/browser/accessibility/ax_platform_node_win_browsertest.cc index dc07596..b0f5836 100644 --- a/content/browser/accessibility/ax_platform_node_win_browsertest.cc +++ b/content/browser/accessibility/ax_platform_node_win_browsertest.cc
@@ -140,7 +140,7 @@ std::wstring(V_BSTR(name.ptr()), SysStringLen(V_BSTR(name.ptr()))))); } - ASSERT_THAT(names, testing::UnorderedElementsAreArray(expected_names)); + ASSERT_THAT(names, ::testing::UnorderedElementsAreArray(expected_names)); } void UIAIWindowProviderGetIsModalBrowserTestTemplate(
diff --git a/content/browser/accessibility/browser_accessibility.cc b/content/browser/accessibility/browser_accessibility.cc index bcf39e5a..ac97282 100644 --- a/content/browser/accessibility/browser_accessibility.cc +++ b/content/browser/accessibility/browser_accessibility.cc
@@ -94,9 +94,6 @@ DCHECK(text_container); if (text_container->GetRole() == ax::mojom::Role::kGenericContainer) return text_container; - NOTREACHED() << "The deepest text container in all native text fields should " - "always have the kGenericContainer role.\n" - << const_cast<BrowserAccessibility&>(text_field).ToString(); return nullptr; }
diff --git a/content/browser/accessibility/browser_accessibility_android_unittest.cc b/content/browser/accessibility/browser_accessibility_android_unittest.cc index 1569aa64..eb3a478 100644 --- a/content/browser/accessibility/browser_accessibility_android_unittest.cc +++ b/content/browser/accessibility/browser_accessibility_android_unittest.cc
@@ -55,15 +55,16 @@ void SetUp() override; base::test::TaskEnvironment task_environment_; MockContentClient client_; + ui::testing::ScopedAxModeSetter ax_mode_setter_; DISALLOW_COPY_AND_ASSIGN(BrowserAccessibilityAndroidTest); }; -BrowserAccessibilityAndroidTest::BrowserAccessibilityAndroidTest() = default; +BrowserAccessibilityAndroidTest::BrowserAccessibilityAndroidTest() + : ax_mode_setter_(ui::kAXModeComplete) {} BrowserAccessibilityAndroidTest::~BrowserAccessibilityAndroidTest() = default; void BrowserAccessibilityAndroidTest::SetUp() { - ui::AXPlatformNode::NotifyAddAXModeFlags(ui::kAXModeComplete); test_browser_accessibility_delegate_ = std::make_unique<TestBrowserAccessibilityDelegate>(); SetContentClient(&client_);
diff --git a/content/browser/accessibility/browser_accessibility_auralinux_unittest.cc b/content/browser/accessibility/browser_accessibility_auralinux_unittest.cc index 284a1f2..742e917 100644 --- a/content/browser/accessibility/browser_accessibility_auralinux_unittest.cc +++ b/content/browser/accessibility/browser_accessibility_auralinux_unittest.cc
@@ -30,18 +30,18 @@ void SetUp() override; content::BrowserTaskEnvironment task_environment_; + ui::testing::ScopedAxModeSetter ax_mode_setter_; DISALLOW_COPY_AND_ASSIGN(BrowserAccessibilityAuraLinuxTest); }; -BrowserAccessibilityAuraLinuxTest::BrowserAccessibilityAuraLinuxTest() = - default; +BrowserAccessibilityAuraLinuxTest::BrowserAccessibilityAuraLinuxTest() + : ax_mode_setter_(ui::kAXModeComplete) {} BrowserAccessibilityAuraLinuxTest::~BrowserAccessibilityAuraLinuxTest() = default; void BrowserAccessibilityAuraLinuxTest::SetUp() { - ui::AXPlatformNode::NotifyAddAXModeFlags(ui::kAXModeComplete); test_browser_accessibility_delegate_ = std::make_unique<TestBrowserAccessibilityDelegate>(); }
diff --git a/content/browser/accessibility/browser_accessibility_manager_auralinux_unittest.cc b/content/browser/accessibility/browser_accessibility_manager_auralinux_unittest.cc index 887fdec..da3934e 100644 --- a/content/browser/accessibility/browser_accessibility_manager_auralinux_unittest.cc +++ b/content/browser/accessibility/browser_accessibility_manager_auralinux_unittest.cc
@@ -18,7 +18,8 @@ class BrowserAccessibilityManagerAuraLinuxTest : public testing::Test { public: - BrowserAccessibilityManagerAuraLinuxTest() = default; + BrowserAccessibilityManagerAuraLinuxTest() + : ax_mode_setter_(ui::kAXModeComplete) {} ~BrowserAccessibilityManagerAuraLinuxTest() override = default; protected: @@ -27,12 +28,12 @@ private: void SetUp() override; + ui::testing::ScopedAxModeSetter ax_mode_setter_; DISALLOW_COPY_AND_ASSIGN(BrowserAccessibilityManagerAuraLinuxTest); }; void BrowserAccessibilityManagerAuraLinuxTest::SetUp() { - ui::AXPlatformNode::NotifyAddAXModeFlags(ui::kAXModeComplete); test_browser_accessibility_delegate_ = std::make_unique<TestBrowserAccessibilityDelegate>(); }
diff --git a/content/browser/accessibility/browser_accessibility_state_impl.cc b/content/browser/accessibility/browser_accessibility_state_impl.cc index afd5ef1..5bf9e522 100644 --- a/content/browser/accessibility/browser_accessibility_state_impl.cc +++ b/content/browser/accessibility/browser_accessibility_state_impl.cc
@@ -378,6 +378,9 @@ accessibility_mode_.mode() ^ (mode.mode() & accessibility_mode_.mode()); accessibility_mode_ = raw_flags; + // Proxy the new AXMode to AXPlatformNode. + ui::AXPlatformNode::SetAXMode(accessibility_mode_); + std::vector<WebContentsImpl*> web_contents_vector = WebContentsImpl::GetAllWebContents(); for (size_t i = 0; i < web_contents_vector.size(); ++i)
diff --git a/content/browser/accessibility/browser_accessibility_state_impl_unittest.cc b/content/browser/accessibility/browser_accessibility_state_impl_unittest.cc index 6a2ce107..48a5b162 100644 --- a/content/browser/accessibility/browser_accessibility_state_impl_unittest.cc +++ b/content/browser/accessibility/browser_accessibility_state_impl_unittest.cc
@@ -13,7 +13,7 @@ namespace content { -class BrowserAccessibilityStateImplTest : public testing::Test { +class BrowserAccessibilityStateImplTest : public ::testing::Test { public: BrowserAccessibilityStateImplTest() = default; BrowserAccessibilityStateImplTest(const BrowserAccessibilityStateImplTest&) =
diff --git a/content/browser/accessibility/browser_accessibility_unittest.cc b/content/browser/accessibility/browser_accessibility_unittest.cc index 47d8f3c..b9aa817 100644 --- a/content/browser/accessibility/browser_accessibility_unittest.cc +++ b/content/browser/accessibility/browser_accessibility_unittest.cc
@@ -26,15 +26,17 @@ void SetUp() override; BrowserTaskEnvironment task_environment_; + ui::testing::ScopedAxModeSetter ax_mode_setter_; + DISALLOW_COPY_AND_ASSIGN(BrowserAccessibilityTest); }; -BrowserAccessibilityTest::BrowserAccessibilityTest() = default; +BrowserAccessibilityTest::BrowserAccessibilityTest() + : ax_mode_setter_(ui::kAXModeComplete) {} BrowserAccessibilityTest::~BrowserAccessibilityTest() = default; void BrowserAccessibilityTest::SetUp() { - ui::AXPlatformNode::NotifyAddAXModeFlags(ui::kAXModeComplete); test_browser_accessibility_delegate_ = std::make_unique<TestBrowserAccessibilityDelegate>(); }
diff --git a/content/browser/accessibility/browser_accessibility_win_unittest.cc b/content/browser/accessibility/browser_accessibility_win_unittest.cc index 0828b37..7642483 100644 --- a/content/browser/accessibility/browser_accessibility_win_unittest.cc +++ b/content/browser/accessibility/browser_accessibility_win_unittest.cc
@@ -97,7 +97,7 @@ // BrowserAccessibilityWinTest ------------------------------------------------ -class BrowserAccessibilityWinTest : public testing::Test { +class BrowserAccessibilityWinTest : public ::testing::Test { public: BrowserAccessibilityWinTest(); ~BrowserAccessibilityWinTest() override;
diff --git a/content/browser/accessibility/site_per_process_accessibility_browsertest.cc b/content/browser/accessibility/site_per_process_accessibility_browsertest.cc index 32e078c5..46173258 100644 --- a/content/browser/accessibility/site_per_process_accessibility_browsertest.cc +++ b/content/browser/accessibility/site_per_process_accessibility_browsertest.cc
@@ -199,7 +199,8 @@ "Title Of Awesomeness"); } -INSTANTIATE_TEST_SUITE_P(MAYBE_All, - MAYBE_SitePerProcessAccessibilityBrowserTest, - testing::ValuesIn(RenderDocumentFeatureLevelValues())); +INSTANTIATE_TEST_SUITE_P( + MAYBE_All, + MAYBE_SitePerProcessAccessibilityBrowserTest, + ::testing::ValuesIn(RenderDocumentFeatureLevelValues())); } // namespace content
diff --git a/content/browser/browsing_instance.cc b/content/browser/browsing_instance.cc index 30e374ae..db2d3cd 100644 --- a/content/browser/browsing_instance.cc +++ b/content/browser/browsing_instance.cc
@@ -24,13 +24,13 @@ BrowsingInstance::BrowsingInstance( BrowserContext* browser_context, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info) + const WebExposedIsolationInfo& web_exposed_isolation_info) : isolation_context_( BrowsingInstanceId::FromUnsafeValue(next_browsing_instance_id_++), BrowserOrResourceContext(browser_context)), active_contents_count_(0u), default_site_instance_(nullptr), - cross_origin_isolated_info_(cross_origin_isolated_info) { + web_exposed_isolation_info_(web_exposed_isolation_info) { DCHECK(browser_context); } @@ -171,7 +171,7 @@ SiteInfo BrowsingInstance::ComputeSiteInfoForURL( const UrlInfo& url_info) const { return SiteInfo::Create(isolation_context_, url_info, - cross_origin_isolated_info_); + web_exposed_isolation_info_); } } // namespace content
diff --git a/content/browser/browsing_instance.h b/content/browser/browsing_instance.h index f426d1eb..edefaee 100644 --- a/content/browser/browsing_instance.h +++ b/content/browser/browsing_instance.h
@@ -14,9 +14,9 @@ #include "base/lazy_instance.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "content/browser/coop_coep_cross_origin_isolated_info.h" #include "content/browser/isolation_context.h" #include "content/browser/site_instance_group_manager.h" +#include "content/browser/web_exposed_isolation_info.h" #include "content/common/content_export.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/render_process_host_observer.h" @@ -84,14 +84,14 @@ static BrowsingInstanceId NextBrowsingInstanceId(); // Create a new BrowsingInstance. - // |cross_origin_isolated_info| indicates whether the BrowsingInstance + // |web_exposed_isolation_info| indicates whether the BrowsingInstance // should contain only cross-origin isolated pages, i.e. pages with // cross-origin-opener-policy set to same-origin and // cross-origin-embedder-policy set to require-corp, and if so, from which // top level origin. explicit BrowsingInstance( BrowserContext* context, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info); + const WebExposedIsolationInfo& web_exposed_isolation_info); ~BrowsingInstance(); @@ -187,9 +187,8 @@ typedef std::map<SiteInfo, SiteInstanceImpl*> SiteInstanceMap; // Returns the cross-origin isolation status of the BrowsingInstance. - const CoopCoepCrossOriginIsolatedInfo& coop_coep_cross_origin_isolated_info() - const { - return cross_origin_isolated_info_; + const WebExposedIsolationInfo& web_exposed_isolation_info() const { + return web_exposed_isolation_info_; } // The next available browser-global BrowsingInstance ID. @@ -231,7 +230,7 @@ // The cross-origin isolation status of the BrowsingInstance. This indicates // whether this BrowsingInstance is hosting only cross-origin isolated pages // and if so, from which top level origin. - const CoopCoepCrossOriginIsolatedInfo cross_origin_isolated_info_; + const WebExposedIsolationInfo web_exposed_isolation_info_; DISALLOW_COPY_AND_ASSIGN(BrowsingInstance); };
diff --git a/content/browser/child_process_security_policy_impl.cc b/content/browser/child_process_security_policy_impl.cc index 7519c34..8ed2f63 100644 --- a/content/browser/child_process_security_policy_impl.cc +++ b/content/browser/child_process_security_policy_impl.cc
@@ -174,19 +174,19 @@ // static ProcessLock ProcessLock::CreateAllowAnySite( - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info) { + const WebExposedIsolationInfo& web_exposed_isolation_info) { return ProcessLock( - SiteInfo(GURL(), GURL(), false, cross_origin_isolated_info)); + SiteInfo(GURL(), GURL(), false, web_exposed_isolation_info)); } // static ProcessLock ProcessLock::Create( const IsolationContext& isolation_context, const UrlInfo& url_info, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info) { + const WebExposedIsolationInfo& web_exposed_isolation_info) { if (BrowserThread::CurrentlyOn(BrowserThread::UI)) return ProcessLock(SiteInfo::Create(isolation_context, url_info, - cross_origin_isolated_info)); + web_exposed_isolation_info)); DCHECK_CURRENTLY_ON(BrowserThread::IO); @@ -195,7 +195,7 @@ // ProcessLocks must always match no matter which thread they were created on, // but the SiteInfo objects used to create them may not always match. return ProcessLock(SiteInfo::CreateOnIOThread(isolation_context, url_info, - cross_origin_isolated_info)); + web_exposed_isolation_info)); } ProcessLock::ProcessLock(const SiteInfo& site_info) : site_info_(site_info) {} @@ -223,11 +223,10 @@ return origin == process_lock_origin; } -bool ProcessLock::IsCompatibleWithCoopCoepCrossOriginIsolation( +bool ProcessLock::IsCompatibleWithWebExposedIsolation( const SiteInfo& site_info) const { - return site_info_.has_value() && - site_info_->coop_coep_cross_origin_isolated_info() == - site_info.coop_coep_cross_origin_isolated_info(); + return site_info_.has_value() && site_info_->web_exposed_isolation_info() == + site_info.web_exposed_isolation_info(); } bool ProcessLock::operator==(const ProcessLock& rhs) const { @@ -242,8 +241,8 @@ is_equal = site_info_->process_lock_url() == rhs.site_info_->process_lock_url() && site_info_->is_origin_keyed() == rhs.site_info_->is_origin_keyed() && - (site_info_->coop_coep_cross_origin_isolated_info() == - rhs.site_info_->coop_coep_cross_origin_isolated_info()); + (site_info_->web_exposed_isolation_info() == + rhs.site_info_->web_exposed_isolation_info()); } return is_equal; @@ -255,15 +254,13 @@ bool ProcessLock::operator<(const ProcessLock& rhs) const { const auto this_is_origin_keyed = is_origin_keyed(); - const auto this_coop_coep_cross_origin_isolated_info = - coop_coep_cross_origin_isolated_info(); + const auto this_web_exposed_isolation_info = web_exposed_isolation_info(); const auto rhs_is_origin_keyed = is_origin_keyed(); - const auto rhs_coop_coep_cross_origin_isolated_info = - coop_coep_cross_origin_isolated_info(); + const auto rhs_web_exposed_isolation_info = web_exposed_isolation_info(); return std::tie(lock_url(), this_is_origin_keyed, - this_coop_coep_cross_origin_isolated_info) < + this_web_exposed_isolation_info) < std::tie(rhs.lock_url(), rhs_is_origin_keyed, - rhs_coop_coep_cross_origin_isolated_info); + rhs_web_exposed_isolation_info); } std::string ProcessLock::ToString() const { @@ -275,11 +272,12 @@ if (is_origin_keyed()) ret += " origin-keyed"; - if (coop_coep_cross_origin_isolated_info().is_isolated()) { + if (web_exposed_isolation_info().is_isolated()) { ret += " cross-origin-isolated"; + if (web_exposed_isolation_info().is_isolated_application()) + ret += "-application"; ret += " coi-origin='" + - coop_coep_cross_origin_isolated_info().origin().GetDebugString() + - "'"; + web_exposed_isolation_info().origin().GetDebugString() + "'"; } } else { ret += " no-site-info"; @@ -576,8 +574,8 @@ } else { // Verify that we are not trying to update the lock with different // COOP/COEP information. - CHECK(process_lock_.coop_coep_cross_origin_isolated_info() == - lock.coop_coep_cross_origin_isolated_info()); + CHECK(process_lock_.web_exposed_isolation_info() == + lock.web_exposed_isolation_info()); if (process_lock_.allows_any_site()) { // TODO(acolwell): Remove ability to lock to an allows_any_site @@ -858,7 +856,7 @@ LockProcess(IsolationContext(BrowsingInstanceId(1), browser_context), child_id, ProcessLock::CreateAllowAnySite( - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated())); + WebExposedIsolationInfo::CreateNonIsolated())); } void ChildProcessSecurityPolicyImpl::Remove(int child_id) { @@ -1536,14 +1534,14 @@ const IsolationContext& isolation_context, const url::Origin& origin, const UrlInfo& url_info, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info) { + const WebExposedIsolationInfo& web_exposed_isolation_info) { const url::Origin url_origin = url::Origin::Resolve(url_info.url, origin); if (!CanAccessDataForOrigin(child_id, url_origin)) { // Check for special cases, like blob:null/ and data: URLs, where the // origin does not contain information to match against the process lock, // but using the whole URL can result in a process lock match. const auto expected_process_lock = ProcessLock::Create( - isolation_context, url_info, cross_origin_isolated_info); + isolation_context, url_info, web_exposed_isolation_info); const ProcessLock& actual_process_lock = GetProcessLock(child_id); if (actual_process_lock == expected_process_lock) return CanCommitStatus::CAN_COMMIT_ORIGIN_AND_URL; @@ -1698,7 +1696,7 @@ expected_process_lock = ProcessLock::Create( isolation_context, UrlInfo(url, UrlInfo::OriginIsolationRequest::kNone), - actual_process_lock.coop_coep_cross_origin_isolated_info()); + actual_process_lock.web_exposed_isolation_info()); if (actual_process_lock.is_locked_to_site()) { // Jail-style enforcement - a process with a lock can only access @@ -1783,7 +1781,7 @@ SiteInfo site_info = SiteInfo::Create( isolation_context, UrlInfo(url, UrlInfo::OriginIsolationRequest::kNone), - actual_process_lock.coop_coep_cross_origin_isolated_info()); + actual_process_lock.web_exposed_isolation_info()); // A process that's not locked to any site can only access data from // origins that do not require a locked process.
diff --git a/content/browser/child_process_security_policy_impl.h b/content/browser/child_process_security_policy_impl.h index dc64d4a..9c729f0c 100644 --- a/content/browser/child_process_security_policy_impl.h +++ b/content/browser/child_process_security_policy_impl.h
@@ -24,6 +24,7 @@ #include "content/browser/isolated_origin_util.h" #include "content/browser/isolation_context.h" #include "content/browser/site_instance_impl.h" +#include "content/browser/web_exposed_isolation_info.h" #include "content/public/browser/child_process_security_policy.h" #include "storage/common/file_system/file_system_types.h" #include "url/origin.h" @@ -75,12 +76,13 @@ public: // Create a lock that that represents a process that is associated with at // least one SiteInstance, but is not locked to a specific site. Any request - // that wants to commit in this process must have COOP/COEP information that - // matches the values used to create this lock. + // that wants to commit in this process must have web-exposed isolation + // information (COOP/COEP, for example) that matches the values used to create + // this lock. static ProcessLock CreateAllowAnySite( - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info); + const WebExposedIsolationInfo& web_exposed_isolation_info); - // Create a lock for a specific UrlInfo and COOP/COEP information. This + // Create a lock for a specific UrlInfo and WebExposedIsolationInfo. This // method can be called from both the UI and IO threads. Locks created with // the same parameters must always be considered equal independent of what // thread they are called on. Special care must be taken since SiteInfos @@ -89,7 +91,7 @@ static ProcessLock Create( const IsolationContext& isolation_context, const UrlInfo& url_info, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info); + const WebExposedIsolationInfo& web_exposed_isolation_info); ProcessLock(); explicit ProcessLock(const SiteInfo& site_info); @@ -139,10 +141,10 @@ // This property is renderer process global because we ensure that a // renderer process host only cross-origin isolated agents or only // non-cross-origin isolated agents, not both. - CoopCoepCrossOriginIsolatedInfo coop_coep_cross_origin_isolated_info() const { + WebExposedIsolationInfo web_exposed_isolation_info() const { return site_info_.has_value() - ? site_info_->coop_coep_cross_origin_isolated_info() - : CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated(); + ? site_info_->web_exposed_isolation_info() + : WebExposedIsolationInfo::CreateNonIsolated(); } bool is_error_page() const { @@ -167,8 +169,9 @@ // Returns true if the COOP/COEP origin isolation information in this lock // is set and matches the information in |site_info|. - bool IsCompatibleWithCoopCoepCrossOriginIsolation( - const SiteInfo& site_info) const; + // Returns true if the web-exposed isolation level in this lock is set and + // matches (or exceeds) the level set in |site_info|.|. + bool IsCompatibleWithWebExposedIsolation(const SiteInfo& site_info) const; bool operator==(const ProcessLock& rhs) const; bool operator!=(const ProcessLock& rhs) const; @@ -327,9 +330,8 @@ IsolatedOriginSource source) override; void ClearIsolatedOriginsForTesting() override; - // Determines if the combination of |origin|, |url|, - // |is_coop_coep_cross_origin_isolated|, and - // |coop_coep_cross_origin_isolated_origin| is safe to commit to the process + // Determines if the combination of |origin|, |url|, and + // |web_exposed_isolation_info| is safe to commit to the process // associated with |child_id|. // // Returns CAN_COMMIT_ORIGIN_AND_URL if it is safe to commit the |origin| and @@ -341,7 +343,7 @@ const IsolationContext& isolation_context, const url::Origin& origin, const UrlInfo& url_info, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info); + const WebExposedIsolationInfo& web_exposed_isolation_info); // This function will check whether |origin| requires process isolation // within |isolation_context|, and if so, it will return true and put the
diff --git a/content/browser/child_process_security_policy_unittest.cc b/content/browser/child_process_security_policy_unittest.cc index a949bdd..010773b4 100644 --- a/content/browser/child_process_security_policy_unittest.cc +++ b/content/browser/child_process_security_policy_unittest.cc
@@ -86,7 +86,7 @@ scoped_refptr<SiteInstanceImpl> site_instance = SiteInstanceImpl::CreateForUrlInfo( browser_context, UrlInfo::CreateForTesting(url), - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated()); + WebExposedIsolationInfo::CreateNonIsolated()); if (site_instance->RequiresDedicatedProcess() && site_instance->GetSiteInfo().ShouldLockProcessToSite( site_instance->GetIsolationContext())) { @@ -2671,7 +2671,7 @@ SetBrowserClientForTesting(&modified_client); IsolationContext isolation_context(browser_context()); - const auto coi_info = CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated(); + const auto coi_info = WebExposedIsolationInfo::CreateNonIsolated(); auto ui_nonapp_url_siteinfo = SiteInfo::Create( isolation_context, UrlInfo::CreateForTesting(nonapp_url), coi_info);
diff --git a/content/browser/coop_coep_cross_origin_isolated_info.cc b/content/browser/coop_coep_cross_origin_isolated_info.cc deleted file mode 100644 index b09ec835..0000000 --- a/content/browser/coop_coep_cross_origin_isolated_info.cc +++ /dev/null
@@ -1,69 +0,0 @@ -// Copyright 2020 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 "content/browser/coop_coep_cross_origin_isolated_info.h" - -namespace content { - -// static -CoopCoepCrossOriginIsolatedInfo -CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated() { - return CoopCoepCrossOriginIsolatedInfo(base::nullopt /* origin */); -} - -CoopCoepCrossOriginIsolatedInfo CoopCoepCrossOriginIsolatedInfo::CreateIsolated( - const url::Origin& origin) { - return CoopCoepCrossOriginIsolatedInfo(origin); -} - -CoopCoepCrossOriginIsolatedInfo::CoopCoepCrossOriginIsolatedInfo( - const base::Optional<url::Origin>& origin) - : origin_(origin) {} - -CoopCoepCrossOriginIsolatedInfo::CoopCoepCrossOriginIsolatedInfo( - const CoopCoepCrossOriginIsolatedInfo& other) = default; - -CoopCoepCrossOriginIsolatedInfo::~CoopCoepCrossOriginIsolatedInfo() = default; - -const url::Origin& CoopCoepCrossOriginIsolatedInfo::origin() const { - DCHECK(is_isolated()) - << "The origin() getter should only be used for " - "CoopCoepCrossOriginIsolatedInfo's where is_isolated() is true."; - return origin_.value(); -} - -bool CoopCoepCrossOriginIsolatedInfo::operator==( - const CoopCoepCrossOriginIsolatedInfo& b) const { - if (is_isolated() != b.is_isolated()) - return false; - - if (is_isolated() && !(origin_->IsSameOriginWith(b.origin()))) - return false; - - return true; -} - -bool CoopCoepCrossOriginIsolatedInfo::operator!=( - const CoopCoepCrossOriginIsolatedInfo& b) const { - return !(operator==(b)); -} - -bool CoopCoepCrossOriginIsolatedInfo::operator<( - const CoopCoepCrossOriginIsolatedInfo& b) const { - if (!(is_isolated() && b.is_isolated())) - return is_isolated() < b.is_isolated(); - - return origin_.value() < b.origin(); -} - -std::ostream& operator<<(std::ostream& out, - const CoopCoepCrossOriginIsolatedInfo& info) { - out << "{"; - if (info.is_isolated()) { - out << info.origin(); - } - out << "}"; - return out; -} -} // namespace content
diff --git a/content/browser/coop_coep_cross_origin_isolated_info.h b/content/browser/coop_coep_cross_origin_isolated_info.h deleted file mode 100644 index abe0022..0000000 --- a/content/browser/coop_coep_cross_origin_isolated_info.h +++ /dev/null
@@ -1,58 +0,0 @@ -// Copyright 2020 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. - -#ifndef CONTENT_BROWSER_COOP_COEP_CROSS_ORIGIN_ISOLATED_INFO_H_ -#define CONTENT_BROWSER_COOP_COEP_CROSS_ORIGIN_ISOLATED_INFO_H_ - -#include "base/optional.h" -#include "content/common/content_export.h" -#include "url/origin.h" - -namespace content { - -// Groups information about the cross-origin isolation of a page or group of -// pages. This is used for process allocation and to selectively enable -// powerful powerful features, such as SharedArrayBuffer. -// -// This is computed using the Cross-Origin-Opener-Policy and -// Cross-Origin-Embedder-Policy headers. -class CONTENT_EXPORT CoopCoepCrossOriginIsolatedInfo { - public: - static CoopCoepCrossOriginIsolatedInfo CreateNonIsolated(); - static CoopCoepCrossOriginIsolatedInfo CreateIsolated( - const url::Origin& origin); - - CoopCoepCrossOriginIsolatedInfo(const CoopCoepCrossOriginIsolatedInfo& other); - ~CoopCoepCrossOriginIsolatedInfo(); - - // Returns the value of the window.crossOriginIsolated boolean. - bool is_isolated() const { return origin_.has_value(); } - - // Returns the top level origin shared across pages with this cross-origin - // isolation status. This only returns a value if is_isolated is true. - const url::Origin& origin() const; - - bool operator==(const CoopCoepCrossOriginIsolatedInfo& b) const; - bool operator!=(const CoopCoepCrossOriginIsolatedInfo& b) const; - - // Note: This only exists to be compatible with std::tie usage of SiteInfo. - bool operator<(const CoopCoepCrossOriginIsolatedInfo& b) const; - - private: - explicit CoopCoepCrossOriginIsolatedInfo( - const base::Optional<url::Origin>& origin); - - // |origin_| serve two purposes. If null, it indicates that the page(s) it - // refers to are not isolated, and that the crossOriginIsolated boolean is - // false. If it has a value, all these page(s) share the same top level - // origin. This ensure we can put them in the same process. - base::Optional<url::Origin> origin_; -}; - -CONTENT_EXPORT std::ostream& operator<<( - std::ostream& out, - const CoopCoepCrossOriginIsolatedInfo& info); -} // namespace content - -#endif // CONTENT_BROWSER_COOP_COEP_CROSS_ORIGIN_ISOLATED_INFO_H_
diff --git a/content/browser/cross_origin_opener_policy_browsertest.cc b/content/browser/cross_origin_opener_policy_browsertest.cc index fbd8e338..866d8bc0 100644 --- a/content/browser/cross_origin_opener_policy_browsertest.cc +++ b/content/browser/cross_origin_opener_policy_browsertest.cc
@@ -2150,7 +2150,7 @@ { EXPECT_TRUE(NavigateToURL(shell(), non_isolated_page)); SiteInstanceImpl* current_si = current_frame_host()->GetSiteInstance(); - EXPECT_FALSE(current_si->IsCoopCoepCrossOriginIsolated()); + EXPECT_FALSE(current_si->IsCrossOriginIsolated()); } // Navigation to a cross-origin isolated page. @@ -2159,7 +2159,7 @@ current_frame_host()->GetSiteInstance(); EXPECT_TRUE(NavigateToURL(shell(), isolated_page)); SiteInstanceImpl* current_si = current_frame_host()->GetSiteInstance(); - EXPECT_TRUE(current_si->IsCoopCoepCrossOriginIsolated()); + EXPECT_TRUE(current_si->IsCrossOriginIsolated()); EXPECT_FALSE(current_si->IsRelatedSiteInstance(previous_si.get())); EXPECT_NE(current_si->GetProcess(), previous_si->GetProcess()); } @@ -2170,7 +2170,7 @@ current_frame_host()->GetSiteInstance(); EXPECT_TRUE(NavigateToURL(shell(), isolated_page)); SiteInstanceImpl* current_si = current_frame_host()->GetSiteInstance(); - EXPECT_TRUE(current_si->IsCoopCoepCrossOriginIsolated()); + EXPECT_TRUE(current_si->IsCrossOriginIsolated()); EXPECT_EQ(current_si, previous_si); } @@ -2180,7 +2180,7 @@ current_frame_host()->GetSiteInstance(); EXPECT_TRUE(NavigateToURL(shell(), non_isolated_page)); SiteInstanceImpl* current_si = current_frame_host()->GetSiteInstance(); - EXPECT_FALSE(current_si->IsCoopCoepCrossOriginIsolated()); + EXPECT_FALSE(current_si->IsCrossOriginIsolated()); EXPECT_FALSE(current_si->IsRelatedSiteInstance(previous_si.get())); EXPECT_NE(current_si->GetProcess(), previous_si->GetProcess()); } @@ -2192,16 +2192,15 @@ scoped_refptr<SiteInstanceImpl> cross_origin_isolated_site_instance = current_frame_host()->GetSiteInstance(); - EXPECT_TRUE( - cross_origin_isolated_site_instance->IsCoopCoepCrossOriginIsolated()); + EXPECT_TRUE(cross_origin_isolated_site_instance->IsCrossOriginIsolated()); web_contents()->GetController().GoBack(); EXPECT_TRUE(WaitForLoadStop(web_contents())); scoped_refptr<SiteInstanceImpl> non_cross_origin_isolated_site_instance = current_frame_host()->GetSiteInstance(); - EXPECT_FALSE(non_cross_origin_isolated_site_instance - ->IsCoopCoepCrossOriginIsolated()); + EXPECT_FALSE( + non_cross_origin_isolated_site_instance->IsCrossOriginIsolated()); EXPECT_FALSE(non_cross_origin_isolated_site_instance->IsRelatedSiteInstance( cross_origin_isolated_site_instance.get())); EXPECT_NE(non_cross_origin_isolated_site_instance->GetProcess(), @@ -2215,8 +2214,8 @@ current_frame_host()->GetSiteInstance(); EXPECT_TRUE(NavigateToURL(shell(), isolated_page_b)); SiteInstanceImpl* site_instance_2 = current_frame_host()->GetSiteInstance(); - EXPECT_TRUE(site_instance_1->IsCoopCoepCrossOriginIsolated()); - EXPECT_TRUE(site_instance_2->IsCoopCoepCrossOriginIsolated()); + EXPECT_TRUE(site_instance_1->IsCrossOriginIsolated()); + EXPECT_TRUE(site_instance_2->IsCrossOriginIsolated()); EXPECT_FALSE(site_instance_1->IsRelatedSiteInstance(site_instance_2)); EXPECT_NE(site_instance_1->GetProcess(), site_instance_2->GetProcess()); } @@ -2243,7 +2242,7 @@ { EXPECT_TRUE(NavigateToURL(shell(), non_isolated_page)); SiteInstanceImpl* current_si = current_frame_host()->GetSiteInstance(); - EXPECT_FALSE(current_si->IsCoopCoepCrossOriginIsolated()); + EXPECT_FALSE(current_si->IsCrossOriginIsolated()); } // Navigation to a cross-origin isolated page. @@ -2252,7 +2251,7 @@ current_frame_host()->GetSiteInstance(); EXPECT_TRUE(NavigateToURLFromRenderer(shell(), isolated_page)); SiteInstanceImpl* current_si = current_frame_host()->GetSiteInstance(); - EXPECT_TRUE(current_si->IsCoopCoepCrossOriginIsolated()); + EXPECT_TRUE(current_si->IsCrossOriginIsolated()); EXPECT_FALSE(current_si->IsRelatedSiteInstance(previous_si.get())); EXPECT_NE(current_si->GetProcess(), previous_si->GetProcess()); } @@ -2263,7 +2262,7 @@ current_frame_host()->GetSiteInstance(); EXPECT_TRUE(NavigateToURLFromRenderer(shell(), isolated_page)); SiteInstanceImpl* current_si = current_frame_host()->GetSiteInstance(); - EXPECT_TRUE(current_si->IsCoopCoepCrossOriginIsolated()); + EXPECT_TRUE(current_si->IsCrossOriginIsolated()); EXPECT_EQ(current_si, previous_si); } @@ -2273,7 +2272,7 @@ current_frame_host()->GetSiteInstance(); EXPECT_TRUE(NavigateToURLFromRenderer(shell(), non_isolated_page)); SiteInstanceImpl* current_si = current_frame_host()->GetSiteInstance(); - EXPECT_FALSE(current_si->IsCoopCoepCrossOriginIsolated()); + EXPECT_FALSE(current_si->IsCrossOriginIsolated()); EXPECT_FALSE(current_si->IsRelatedSiteInstance(previous_si.get())); EXPECT_NE(current_si->GetProcess(), previous_si->GetProcess()); } @@ -2285,8 +2284,8 @@ current_frame_host()->GetSiteInstance(); EXPECT_TRUE(NavigateToURLFromRenderer(shell(), isolated_page_b)); SiteInstanceImpl* site_instance_2 = current_frame_host()->GetSiteInstance(); - EXPECT_TRUE(site_instance_1->IsCoopCoepCrossOriginIsolated()); - EXPECT_TRUE(site_instance_2->IsCoopCoepCrossOriginIsolated()); + EXPECT_TRUE(site_instance_1->IsCrossOriginIsolated()); + EXPECT_TRUE(site_instance_2->IsCrossOriginIsolated()); EXPECT_FALSE(site_instance_1->IsRelatedSiteInstance(site_instance_2)); EXPECT_NE(site_instance_1->GetProcess(), site_instance_2->GetProcess()); } @@ -2308,7 +2307,7 @@ // Initial cross-origin isolated page. EXPECT_TRUE(NavigateToURL(shell(), isolated_page)); SiteInstanceImpl* main_si = current_frame_host()->GetSiteInstance(); - EXPECT_TRUE(main_si->IsCoopCoepCrossOriginIsolated()); + EXPECT_TRUE(main_si->IsCrossOriginIsolated()); // Same origin iframe. { @@ -2347,7 +2346,7 @@ RenderFrameHostImpl* iframe_rfh = current_frame_host()->child_at(1)->current_frame_host(); SiteInstanceImpl* iframe_si = iframe_rfh->GetSiteInstance(); - EXPECT_TRUE(iframe_si->IsCoopCoepCrossOriginIsolated()); + EXPECT_TRUE(iframe_si->IsCrossOriginIsolated()); EXPECT_TRUE(iframe_si->IsRelatedSiteInstance(main_si)); EXPECT_EQ(iframe_si->GetProcess(), main_si->GetProcess()); } @@ -2371,7 +2370,7 @@ // Initial cross-origin isolated page. EXPECT_TRUE(NavigateToURL(shell(), isolated_page)); SiteInstanceImpl* main_si = current_frame_host()->GetSiteInstance(); - EXPECT_TRUE(main_si->IsCoopCoepCrossOriginIsolated()); + EXPECT_TRUE(main_si->IsCrossOriginIsolated()); // Open a non isolated popup. { @@ -2383,7 +2382,7 @@ ->root() ->current_frame_host(); - EXPECT_FALSE(popup_rfh->GetSiteInstance()->IsCoopCoepCrossOriginIsolated()); + EXPECT_FALSE(popup_rfh->GetSiteInstance()->IsCrossOriginIsolated()); EXPECT_FALSE(popup_rfh->GetSiteInstance()->IsRelatedSiteInstance( current_frame_host()->GetSiteInstance())); EXPECT_FALSE(popup_rfh->frame_tree_node()->opener()); @@ -2398,7 +2397,7 @@ ->root() ->current_frame_host(); - EXPECT_TRUE(popup_rfh->GetSiteInstance()->IsCoopCoepCrossOriginIsolated()); + EXPECT_TRUE(popup_rfh->GetSiteInstance()->IsCrossOriginIsolated()); EXPECT_EQ(popup_rfh->GetSiteInstance(), current_frame_host()->GetSiteInstance()); } @@ -2413,7 +2412,7 @@ ->root() ->current_frame_host(); - EXPECT_TRUE(popup_rfh->GetSiteInstance()->IsCoopCoepCrossOriginIsolated()); + EXPECT_TRUE(popup_rfh->GetSiteInstance()->IsCrossOriginIsolated()); EXPECT_FALSE(popup_rfh->GetSiteInstance()->IsRelatedSiteInstance( current_frame_host()->GetSiteInstance())); EXPECT_FALSE(popup_rfh->frame_tree_node()->opener()); @@ -2441,7 +2440,7 @@ // Initial cross-origin isolated page. EXPECT_TRUE(NavigateToURL(shell(), isolated_page)); SiteInstanceImpl* main_si = current_frame_host()->GetSiteInstance(); - EXPECT_TRUE(main_si->IsCoopCoepCrossOriginIsolated()); + EXPECT_TRUE(main_si->IsCrossOriginIsolated()); // Iframe. { @@ -2464,7 +2463,7 @@ EXPECT_EQ(GURL(kUnreachableWebDataURL), EvalJs(iframe_rfh, "document.location.href;")); EXPECT_TRUE(IsExpectedSubframeErrorTransition(main_si, iframe_si)); - EXPECT_TRUE(iframe_si->IsCoopCoepCrossOriginIsolated()); + EXPECT_TRUE(iframe_si->IsCrossOriginIsolated()); } // Iframe with a body added to the HTTP 404. @@ -2489,7 +2488,7 @@ // by COEP. An error page is expected in lieu of that document. EXPECT_EQ(GURL(kUnreachableWebDataURL), EvalJs(iframe_rfh, "document.location.href;")); - EXPECT_TRUE(iframe_si->IsCoopCoepCrossOriginIsolated()); + EXPECT_TRUE(iframe_si->IsCrossOriginIsolated()); } // Iframe blocked by coep. @@ -2509,7 +2508,7 @@ current_frame_host()->child_at(0)->current_frame_host(); SiteInstanceImpl* iframe_si = iframe_rfh->GetSiteInstance(); EXPECT_TRUE(IsExpectedSubframeErrorTransition(main_si, iframe_si)); - EXPECT_TRUE(iframe_si->IsCoopCoepCrossOriginIsolated()); + EXPECT_TRUE(iframe_si->IsCrossOriginIsolated()); } // Top frame. @@ -2520,7 +2519,7 @@ SiteInstanceImpl* current_si = current_frame_host()->GetSiteInstance(); EXPECT_FALSE(current_si->IsRelatedSiteInstance(previous_si.get())); EXPECT_NE(current_si->GetProcess(), previous_si->GetProcess()); - EXPECT_FALSE(current_si->IsCoopCoepCrossOriginIsolated()); + EXPECT_FALSE(current_si->IsCrossOriginIsolated()); } } @@ -2540,14 +2539,14 @@ EXPECT_TRUE(NavigateToURL(shell(), non_isolated_page)); SiteInstanceImpl* current_si = current_frame_host()->GetSiteInstance(); - EXPECT_FALSE(current_si->IsCoopCoepCrossOriginIsolated()); + EXPECT_FALSE(current_si->IsCrossOriginIsolated()); EXPECT_TRUE(NavigateToURL(shell(), redirect_isolated_page, isolated_page)); current_si = current_frame_host()->GetSiteInstance(); - EXPECT_TRUE(current_si->IsCoopCoepCrossOriginIsolated()); - EXPECT_TRUE(current_si->GetCoopCoepCrossOriginIsolatedInfo() - .origin() - .IsSameOriginWith(url::Origin::Create(isolated_page))); + EXPECT_TRUE(current_si->IsCrossOriginIsolated()); + EXPECT_TRUE( + current_si->GetWebExposedIsolationInfo().origin().IsSameOriginWith( + url::Origin::Create(isolated_page))); } // Reproducer test for https://crbug.com/1150938. @@ -2567,7 +2566,7 @@ // Initial cross-origin isolated page. EXPECT_TRUE(NavigateToURL(shell(), isolated_page)); SiteInstanceImpl* main_si = current_frame_host()->GetSiteInstance(); - EXPECT_TRUE(main_si->IsCoopCoepCrossOriginIsolated()); + EXPECT_TRUE(main_si->IsCrossOriginIsolated()); TestNavigationManager cross_origin_iframe_navigation(web_contents(), isolated_page_b); @@ -2583,7 +2582,7 @@ RenderFrameHostImpl* iframe_rfh = current_frame_host()->child_at(0)->current_frame_host(); SiteInstanceImpl* iframe_si = iframe_rfh->GetSiteInstance(); - EXPECT_TRUE(iframe_si->IsCoopCoepCrossOriginIsolated()); + EXPECT_TRUE(iframe_si->IsCrossOriginIsolated()); EXPECT_TRUE(iframe_si->IsRelatedSiteInstance(main_si)); EXPECT_EQ(iframe_si->GetProcess(), main_si->GetProcess()); @@ -2596,7 +2595,7 @@ ->root() ->current_frame_host(); - EXPECT_TRUE(popup_rfh->GetSiteInstance()->IsCoopCoepCrossOriginIsolated()); + EXPECT_TRUE(popup_rfh->GetSiteInstance()->IsCrossOriginIsolated()); EXPECT_FALSE(popup_rfh->GetSiteInstance()->IsRelatedSiteInstance( current_frame_host()->GetSiteInstance())); EXPECT_FALSE(popup_rfh->frame_tree_node()->opener());
diff --git a/content/browser/devtools/protocol/network_handler.cc b/content/browser/devtools/protocol/network_handler.cc index 117e009..aea5ce0 100644 --- a/content/browser/devtools/protocol/network_handler.cc +++ b/content/browser/devtools/protocol/network_handler.cc
@@ -2551,7 +2551,7 @@ switch (value) { case network::mojom::CrossOriginEmbedderPolicyValue::kNone: return protocol::Network::CrossOriginEmbedderPolicyValueEnum::None; - case network::mojom::CrossOriginEmbedderPolicyValue::kCorsOrCredentialless: + case network::mojom::CrossOriginEmbedderPolicyValue::kCredentialless: return protocol::Network::CrossOriginEmbedderPolicyValueEnum:: CorsOrCredentialless; case network::mojom::CrossOriginEmbedderPolicyValue::kRequireCorp:
diff --git a/content/browser/file_system_access/file_system_chooser_unittest.cc b/content/browser/file_system_access/file_system_chooser_unittest.cc index 0b6108751..3fc7b59 100644 --- a/content/browser/file_system_access/file_system_chooser_unittest.cc +++ b/content/browser/file_system_access/file_system_chooser_unittest.cc
@@ -237,19 +237,19 @@ new CancellingSelectFileDialogFactory(&dialog_params)); std::vector<blink::mojom::ChooseFileSystemEntryAcceptsOptionPtr> accepts; accepts.emplace_back(blink::mojom::ChooseFileSystemEntryAcceptsOption::New( - u"Description with \t a \r lot of \n " - u" spaces", + base::UTF8ToUTF16("Description with \t a \r lot of \n " + " spaces"), std::vector<std::string>({}), std::vector<std::string>({"txt"}))); accepts.emplace_back(blink::mojom::ChooseFileSystemEntryAcceptsOption::New( - u"Description that is very long and should be " - u"truncated to 64 code points if it works", + base::UTF8ToUTF16("Description that is very long and should be " + "truncated to 64 code points if it works"), std::vector<std::string>({}), std::vector<std::string>({"js"}))); accepts.emplace_back(blink::mojom::ChooseFileSystemEntryAcceptsOption::New( - u"Unbalanced RTL \u202e section", std::vector<std::string>({}), - std::vector<std::string>({"js"}))); + base::UTF8ToUTF16("Unbalanced RTL \xe2\x80\xae section"), + std::vector<std::string>({}), std::vector<std::string>({"js"}))); accepts.emplace_back(blink::mojom::ChooseFileSystemEntryAcceptsOption::New( - u"Unbalanced RTL \u202e section in a otherwise " - u"very long description that will be truncated", + base::UTF8ToUTF16("Unbalanced RTL \xe2\x80\xae section in a otherwise " + "very long description that will be truncated"), std::vector<std::string>({}), std::vector<std::string>({"js"}))); SyncShowDialog(std::move(accepts), /*include_accepts_all=*/false); @@ -258,14 +258,16 @@ dialog_params.file_types->extension_description_overrides.size()); EXPECT_EQ(u"Description with a lot of spaces", dialog_params.file_types->extension_description_overrides[0]); - EXPECT_EQ(u"Description that is very long and should be truncated to 64 cod…", - dialog_params.file_types->extension_description_overrides[1]); - EXPECT_EQ(u"Unbalanced RTL \u202e section\u202c", - dialog_params.file_types->extension_description_overrides[2]); EXPECT_EQ( - u"Unbalanced RTL \u202e section in a " - u"otherwise very long description t…\u202c", - dialog_params.file_types->extension_description_overrides[3]); + base::UTF8ToUTF16( + "Description that is very long and should be truncated to 64 cod…"), + dialog_params.file_types->extension_description_overrides[1]); + EXPECT_EQ( + base::UTF8ToUTF16("Unbalanced RTL \xe2\x80\xae section\xe2\x80\xac"), + dialog_params.file_types->extension_description_overrides[2]); + EXPECT_EQ(base::UTF8ToUTF16("Unbalanced RTL \xe2\x80\xae section in a " + "otherwise very long description t…\xe2\x80\xac"), + dialog_params.file_types->extension_description_overrides[3]); } } // namespace content
diff --git a/content/browser/indexed_db/indexed_db_dispatcher_host_unittest.cc b/content/browser/indexed_db/indexed_db_dispatcher_host_unittest.cc index 14c32e96..0212255 100644 --- a/content/browser/indexed_db/indexed_db_dispatcher_host_unittest.cc +++ b/content/browser/indexed_db/indexed_db_dispatcher_host_unittest.cc
@@ -81,7 +81,7 @@ return arg.Equals(key); } -static const char16_t kDatabaseName[] = u"db"; +static const char kDatabaseName[] = "db"; static const char kOrigin[] = "https://www.example.com"; base::FilePath CreateAndReturnTempDir(base::ScopedTempDir* temp_dir) { @@ -255,7 +255,7 @@ FROM_HERE, base::BindLambdaForTesting([&]() { connection = std::make_unique<TestDatabaseConnection>( context_impl_->IDBTaskRunner(), url::Origin::Create(GURL(kOrigin)), - kDatabaseName, kDBVersion, kTransactionId); + base::UTF8ToUTF16(kDatabaseName), kDBVersion, kTransactionId); EXPECT_CALL(*connection->open_callbacks, MockedUpgradeNeeded(IsAssociatedInterfacePtrInfoValid(true), IndexedDBDatabaseMetadata::NO_VERSION, @@ -287,7 +287,7 @@ const int64_t kDBVersion = 1; const int64_t kTransactionId = 1; const int64_t kObjectStoreId = 10; - const char16_t kObjectStoreName[] = u"os"; + const char kObjectStoreName[] = "os"; std::unique_ptr<TestDatabaseConnection> connection; IndexedDBDatabaseMetadata metadata; mojo::PendingAssociatedRemote<blink::mojom::IDBDatabase> pending_database; @@ -297,8 +297,8 @@ FROM_HERE, base::BindLambdaForTesting([&]() { // Open connection. connection = std::make_unique<TestDatabaseConnection>( - context_impl_->IDBTaskRunner(), ToOrigin(kOrigin), kDatabaseName, - kDBVersion, kTransactionId); + context_impl_->IDBTaskRunner(), ToOrigin(kOrigin), + base::UTF8ToUTF16(kDatabaseName), kDBVersion, kTransactionId); EXPECT_CALL(*connection->open_callbacks, MockedUpgradeNeeded(IsAssociatedInterfacePtrInfoValid(true), @@ -337,7 +337,8 @@ ASSERT_TRUE(connection->database.is_bound()); ASSERT_TRUE(connection->version_change_transaction.is_bound()); connection->version_change_transaction->CreateObjectStore( - kObjectStoreId, kObjectStoreName, blink::IndexedDBKeyPath(), false); + kObjectStoreId, base::UTF8ToUTF16(kObjectStoreName), + blink::IndexedDBKeyPath(), false); connection->version_change_transaction->Commit(0); })); loop2.Run(); @@ -356,7 +357,7 @@ const int64_t kDBVersion = 1; const int64_t kTransactionId = 1; const int64_t kObjectStoreId = 10; - const char16_t kObjectStoreName[] = u"os"; + const char kObjectStoreName[] = "os"; std::unique_ptr<TestDatabaseConnection> connection1; mojo::PendingAssociatedRemote<blink::mojom::IDBDatabase> pending_database1; IndexedDBDatabaseMetadata metadata1; @@ -367,7 +368,7 @@ // Open connection 1, and expect the upgrade needed. connection1 = std::make_unique<TestDatabaseConnection>( context_impl_->IDBTaskRunner(), url::Origin::Create(GURL(kOrigin)), - kDatabaseName, kDBVersion, kTransactionId); + base::UTF8ToUTF16(kDatabaseName), kDBVersion, kTransactionId); EXPECT_CALL(*connection1->open_callbacks, MockedUpgradeNeeded(IsAssociatedInterfacePtrInfoValid(true), @@ -393,8 +394,8 @@ context_impl_->IDBTaskRunner()->PostTask( FROM_HERE, base::BindLambdaForTesting([&]() { connection2 = std::make_unique<TestDatabaseConnection>( - context_impl_->IDBTaskRunner(), ToOrigin(kOrigin), kDatabaseName, - kDBVersion, 0); + context_impl_->IDBTaskRunner(), ToOrigin(kOrigin), + base::UTF8ToUTF16(kDatabaseName), kDBVersion, 0); // Check that we're called in order and the second connection gets it's // database after the first connection completes. @@ -424,7 +425,8 @@ // Create object store. connection1->version_change_transaction->CreateObjectStore( - kObjectStoreId, kObjectStoreName, blink::IndexedDBKeyPath(), false); + kObjectStoreId, base::UTF8ToUTF16(kObjectStoreName), + blink::IndexedDBKeyPath(), false); connection1->version_change_transaction->Commit(0); })); loop2.Run(); @@ -455,7 +457,7 @@ const int64_t kDBVersion = 1; const int64_t kTransactionId = 1; const int64_t kObjectStoreId = 10; - const char16_t kObjectStoreName[] = u"os"; + const char kObjectStoreName[] = "os"; std::unique_ptr<TestDatabaseConnection> connection; IndexedDBDatabaseMetadata metadata; mojo::PendingAssociatedRemote<blink::mojom::IDBDatabase> pending_database; @@ -466,7 +468,7 @@ // Open connection. connection = std::make_unique<TestDatabaseConnection>( context_impl_->IDBTaskRunner(), url::Origin::Create(GURL(kOrigin)), - kDatabaseName, kDBVersion, kTransactionId); + base::UTF8ToUTF16(kDatabaseName), kDBVersion, kTransactionId); EXPECT_CALL(*connection->open_callbacks, MockedUpgradeNeeded(IsAssociatedInterfacePtrInfoValid(true), @@ -516,7 +518,8 @@ ASSERT_TRUE(connection->database.is_bound()); ASSERT_TRUE(connection->version_change_transaction.is_bound()); connection->version_change_transaction->CreateObjectStore( - kObjectStoreId, kObjectStoreName, blink::IndexedDBKeyPath(), false); + kObjectStoreId, base::UTF8ToUTF16(kObjectStoreName), + blink::IndexedDBKeyPath(), false); // Call Put with an invalid blob. std::vector<blink::mojom::IDBExternalObjectPtr> external_objects; mojo::PendingRemote<blink::mojom::Blob> blob; @@ -568,8 +571,8 @@ FROM_HERE, base::BindLambdaForTesting([&]() { // Open connection. connection = std::make_unique<TestDatabaseConnection>( - context_impl_->IDBTaskRunner(), ToOrigin(kOrigin), kDatabaseName, - kDBVersion, kTransactionId); + context_impl_->IDBTaskRunner(), ToOrigin(kOrigin), + base::UTF8ToUTF16(kDatabaseName), kDBVersion, kTransactionId); EXPECT_CALL(*connection->open_callbacks, MockedUpgradeNeeded(IsAssociatedInterfacePtrInfoValid(true), IndexedDBDatabaseMetadata::NO_VERSION, @@ -630,7 +633,7 @@ const int64_t kDBVersion = 1; const int64_t kTransactionId = 1; const int64_t kObjectStoreId = 10; - const char16_t kObjectStoreName[] = u"os"; + const char kObjectStoreName[] = "os"; std::unique_ptr<TestDatabaseConnection> connection; IndexedDBDatabaseMetadata metadata; mojo::PendingAssociatedRemote<blink::mojom::IDBDatabase> pending_database; @@ -640,8 +643,8 @@ FROM_HERE, base::BindLambdaForTesting([&]() { // Open connection. connection = std::make_unique<TestDatabaseConnection>( - context_impl_->IDBTaskRunner(), ToOrigin(kOrigin), kDatabaseName, - kDBVersion, kTransactionId); + context_impl_->IDBTaskRunner(), ToOrigin(kOrigin), + base::UTF8ToUTF16(kDatabaseName), kDBVersion, kTransactionId); EXPECT_CALL(*connection->open_callbacks, MockedUpgradeNeeded(IsAssociatedInterfacePtrInfoValid(true), IndexedDBDatabaseMetadata::NO_VERSION, @@ -686,7 +689,8 @@ ASSERT_TRUE(connection->database.is_bound()); ASSERT_TRUE(connection->version_change_transaction.is_bound()); connection->version_change_transaction->CreateObjectStore( - kObjectStoreId, kObjectStoreName, blink::IndexedDBKeyPath(), false); + kObjectStoreId, base::UTF8ToUTF16(kObjectStoreName), + blink::IndexedDBKeyPath(), false); idb_mojo_factory_->AbortTransactionsAndCompactDatabase(base::BindOnce( &TestStatusCallback, std::move(quit_closure2), &callback_result)); })); @@ -715,8 +719,8 @@ FROM_HERE, base::BindLambdaForTesting([&]() { // Open connection. connection = std::make_unique<TestDatabaseConnection>( - context_impl_->IDBTaskRunner(), ToOrigin(kOrigin), kDatabaseName, - kDBVersion, kTransactionId); + context_impl_->IDBTaskRunner(), ToOrigin(kOrigin), + base::UTF8ToUTF16(kDatabaseName), kDBVersion, kTransactionId); EXPECT_CALL(*connection->open_callbacks, MockedUpgradeNeeded(IsAssociatedInterfacePtrInfoValid(true), IndexedDBDatabaseMetadata::NO_VERSION, @@ -789,8 +793,8 @@ FROM_HERE, base::BindLambdaForTesting([&]() { // Open connection. connection = std::make_unique<TestDatabaseConnection>( - context_impl_->IDBTaskRunner(), ToOrigin(kOrigin), kDatabaseName, - kDBVersion, kTransactionId); + context_impl_->IDBTaskRunner(), ToOrigin(kOrigin), + base::UTF8ToUTF16(kDatabaseName), kDBVersion, kTransactionId); { EXPECT_CALL(*connection->open_callbacks, MockedUpgradeNeeded( @@ -855,7 +859,7 @@ const int64_t kDBVersion = 1; const int64_t kTransactionId = 1; const int64_t kObjectStoreId = 10; - const char16_t kObjectStoreName[] = u"os"; + const char kObjectStoreName[] = "os"; std::unique_ptr<TestDatabaseConnection> connection; IndexedDBDatabaseMetadata metadata; mojo::PendingAssociatedRemote<blink::mojom::IDBDatabase> pending_database; @@ -865,8 +869,8 @@ FROM_HERE, base::BindLambdaForTesting([&]() { // Open connection. connection = std::make_unique<TestDatabaseConnection>( - context_impl_->IDBTaskRunner(), ToOrigin(kOrigin), kDatabaseName, - kDBVersion, kTransactionId); + context_impl_->IDBTaskRunner(), ToOrigin(kOrigin), + base::UTF8ToUTF16(kDatabaseName), kDBVersion, kTransactionId); EXPECT_CALL(*connection->open_callbacks, MockedUpgradeNeeded(IsAssociatedInterfacePtrInfoValid(true), @@ -912,7 +916,8 @@ ASSERT_TRUE(connection->database.is_bound()); ASSERT_TRUE(connection->version_change_transaction.is_bound()); connection->version_change_transaction->CreateObjectStore( - kObjectStoreId, kObjectStoreName, blink::IndexedDBKeyPath(), false); + kObjectStoreId, base::UTF8ToUTF16(kObjectStoreName), + blink::IndexedDBKeyPath(), false); idb_mojo_factory_->AbortTransactionsForDatabase(base::BindOnce( &TestStatusCallback, std::move(quit_closure2), &callback_result)); })); @@ -941,8 +946,8 @@ FROM_HERE, base::BindLambdaForTesting([&]() { // Open connection. connection = std::make_unique<TestDatabaseConnection>( - context_impl_->IDBTaskRunner(), ToOrigin(kOrigin), kDatabaseName, - kDBVersion, kTransactionId); + context_impl_->IDBTaskRunner(), ToOrigin(kOrigin), + base::UTF8ToUTF16(kDatabaseName), kDBVersion, kTransactionId); EXPECT_CALL(*connection->open_callbacks, MockedUpgradeNeeded(IsAssociatedInterfacePtrInfoValid(true), @@ -1013,8 +1018,8 @@ const int64_t kTransactionId3 = 3; const int64_t kObjectStoreId = 10; const int64_t kIndexId = 100; - const char16_t kObjectStoreName[] = u"os"; - const char16_t kIndexName[] = u"index"; + const char kObjectStoreName[] = "os"; + const char kIndexName[] = "index"; mojo::PendingReceiver<storage::mojom::IndexedDBObserver> receiver; mojo::PendingRemote<storage::mojom::IndexedDBObserver> remote; @@ -1032,8 +1037,8 @@ context_impl_->IDBTaskRunner()->PostTask( FROM_HERE, base::BindLambdaForTesting([&]() { connection1 = std::make_unique<TestDatabaseConnection>( - context_impl_->IDBTaskRunner(), ToOrigin(kOrigin), kDatabaseName, - kDBVersion1, kTransactionId1); + context_impl_->IDBTaskRunner(), ToOrigin(kOrigin), + base::UTF8ToUTF16(kDatabaseName), kDBVersion1, kTransactionId1); EXPECT_CALL(*connection1->open_callbacks, MockedUpgradeNeeded( @@ -1077,11 +1082,12 @@ ASSERT_TRUE(connection1->database.is_bound()); connection1->version_change_transaction->CreateObjectStore( - kObjectStoreId, kObjectStoreName, blink::IndexedDBKeyPath(), - false); + kObjectStoreId, base::UTF8ToUTF16(kObjectStoreName), + blink::IndexedDBKeyPath(), false); connection1->database->CreateIndex( - kTransactionId1, kObjectStoreId, kIndexId, kIndexName, - blink::IndexedDBKeyPath(), false, false); + kTransactionId1, kObjectStoreId, kIndexId, + base::UTF8ToUTF16(kIndexName), blink::IndexedDBKeyPath(), false, + false); connection1->version_change_transaction->Commit(0); })); loop.Run(); @@ -1105,8 +1111,8 @@ connection2 = std::make_unique<TestDatabaseConnection>( context_impl_->IDBTaskRunner(), - url::Origin::Create(GURL(kOrigin)), kDatabaseName, kDBVersion2, - kTransactionId2); + url::Origin::Create(GURL(kOrigin)), + base::UTF8ToUTF16(kDatabaseName), kDBVersion2, kTransactionId2); EXPECT_CALL(*connection2->open_callbacks, MockedUpgradeNeeded( @@ -1168,8 +1174,8 @@ FROM_HERE, base::BindLambdaForTesting([&]() { connection2->database->Close(); connection3 = std::make_unique<TestDatabaseConnection>( - context_impl_->IDBTaskRunner(), ToOrigin(kOrigin), kDatabaseName, - kDBVersion3, kTransactionId3); + context_impl_->IDBTaskRunner(), ToOrigin(kOrigin), + base::UTF8ToUTF16(kDatabaseName), kDBVersion3, kTransactionId3); EXPECT_CALL(*connection3->open_callbacks, MockedUpgradeNeeded( @@ -1243,7 +1249,7 @@ const int64_t kTransactionId1 = 1; const int64_t kTransactionId2 = 2; const int64_t kObjectStoreId = 10; - const char16_t kObjectStoreName[] = u"os"; + const char kObjectStoreName[] = "os"; mojo::PendingReceiver<storage::mojom::IndexedDBObserver> receiver; mojo::PendingRemote<storage::mojom::IndexedDBObserver> remote; @@ -1262,7 +1268,7 @@ // Open connection 1. connection1 = std::make_unique<TestDatabaseConnection>( context_impl_->IDBTaskRunner(), url::Origin::Create(GURL(kOrigin)), - kDatabaseName, kDBVersion1, kTransactionId1); + base::UTF8ToUTF16(kDatabaseName), kDBVersion1, kTransactionId1); EXPECT_CALL(*connection1->open_callbacks, MockedUpgradeNeeded(IsAssociatedInterfacePtrInfoValid(true), @@ -1309,7 +1315,8 @@ ASSERT_TRUE(connection1->database.is_bound()); ASSERT_TRUE(connection1->version_change_transaction.is_bound()); connection1->version_change_transaction->CreateObjectStore( - kObjectStoreId, kObjectStoreName, blink::IndexedDBKeyPath(), false); + kObjectStoreId, base::UTF8ToUTF16(kObjectStoreName), + blink::IndexedDBKeyPath(), false); std::string value = "value"; const char* value_data = value.data(); @@ -1350,8 +1357,8 @@ ::testing::InSequence dummy; connection2 = std::make_unique<TestDatabaseConnection>( - context_impl_->IDBTaskRunner(), ToOrigin(kOrigin), kDatabaseName, - kDBVersion2, kTransactionId2); + context_impl_->IDBTaskRunner(), ToOrigin(kOrigin), + base::UTF8ToUTF16(kDatabaseName), kDBVersion2, kTransactionId2); EXPECT_CALL(*connection2->open_callbacks, MockedUpgradeNeeded( @@ -1443,8 +1450,8 @@ FROM_HERE, base::BindLambdaForTesting([&]() { // Open connection. connection = std::make_unique<TestDatabaseConnection>( - context_impl_->IDBTaskRunner(), ToOrigin(kOrigin), kDatabaseName, - kDBVersion, kTransactionId); + context_impl_->IDBTaskRunner(), ToOrigin(kOrigin), + base::UTF8ToUTF16(kDatabaseName), kDBVersion, kTransactionId); EXPECT_CALL(*connection->open_callbacks, MockedUpgradeNeeded(IsAssociatedInterfacePtrInfoValid(true),
diff --git a/content/browser/isolated_origin_browsertest.cc b/content/browser/isolated_origin_browsertest.cc index 65b98551..9f18a15 100644 --- a/content/browser/isolated_origin_browsertest.cc +++ b/content/browser/isolated_origin_browsertest.cc
@@ -95,9 +95,9 @@ } ProcessLock ProcessLockFromUrl(const std::string& url) { - return ProcessLock( - SiteInfo(GURL(url), GURL(url), false /* is_origin_keyed */, - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated())); + return ProcessLock(SiteInfo(GURL(url), GURL(url), + false /* is_origin_keyed */, + WebExposedIsolationInfo::CreateNonIsolated())); } WebContentsImpl* web_contents() const { @@ -113,9 +113,9 @@ // is_origin_keyed to true. ProcessLock GetStrictProcessLock(const GURL& url) { GURL origin_url = url::Origin::Create(url).GetURL(); - return ProcessLock( - SiteInfo(origin_url, origin_url, false /* is_origin_keyed */, - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated())); + return ProcessLock(SiteInfo(origin_url, origin_url, + false /* is_origin_keyed */, + WebExposedIsolationInfo::CreateNonIsolated())); } private: @@ -482,9 +482,9 @@ GURL isolated_suborigin_url( https_server()->GetURL("isolated.foo.com", "/isolate_origin")); GURL origin_url = url::Origin::Create(isolated_suborigin_url).GetURL(); - auto expected_isolated_suborigin_lock = ProcessLock( - SiteInfo(origin_url, origin_url, true /* is_origin_keyed */, - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated())); + auto expected_isolated_suborigin_lock = + ProcessLock(SiteInfo(origin_url, origin_url, true /* is_origin_keyed */, + WebExposedIsolationInfo::CreateNonIsolated())); EXPECT_TRUE(NavigateToURL(shell(), test_url)); EXPECT_EQ(2u, shell()->web_contents()->GetAllFrames().size()); @@ -2890,7 +2890,7 @@ scoped_refptr<SiteInstanceImpl> sw_site_instance = SiteInstanceImpl::CreateForServiceWorker( web_contents()->GetBrowserContext(), hung_isolated_url, - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated(), + WebExposedIsolationInfo::CreateNonIsolated(), /* can_reuse_process= */ true); RenderProcessHost* sw_host = sw_site_instance->GetProcess(); EXPECT_NE(new_shell->web_contents()->GetMainFrame()->GetProcess(), sw_host); @@ -5127,7 +5127,7 @@ EXPECT_TRUE(coop_instance->RequiresDedicatedProcess()); auto* policy = ChildProcessSecurityPolicyImpl::GetInstance(); auto lock = policy->GetProcessLock(coop_instance->GetProcess()->GetID()); - EXPECT_TRUE(lock.coop_coep_cross_origin_isolated_info().is_isolated()); + EXPECT_TRUE(lock.web_exposed_isolation_info().is_isolated()); EXPECT_TRUE(lock.is_locked_to_site()); EXPECT_TRUE( lock.MatchesOrigin(url::Origin::Create(GURL("https://coop.com"))));
diff --git a/content/browser/media/media_internals_unittest.cc b/content/browser/media/media_internals_unittest.cc index 09a06fc..ab4b44e 100644 --- a/content/browser/media/media_internals_unittest.cc +++ b/content/browser/media/media_internals_unittest.cc
@@ -308,8 +308,8 @@ namespace { // Test page titles. -const char16_t kTestTitle1[] = u"Test Title 1"; -const char16_t kTestTitle2[] = u"Test Title 2"; +const char kTestTitle1[] = "Test Title 1"; +const char kTestTitle2[] = "Test Title 2"; } // namespace @@ -415,7 +415,8 @@ TEST_F(MediaInternalsAudioFocusTest, AudioFocusStateIsUpdated) { // Create a test media session and request audio focus. std::unique_ptr<WebContents> web_contents1 = CreateTestWebContents(); - static_cast<TestWebContents*>(web_contents1.get())->SetTitle(kTestTitle1); + static_cast<TestWebContents*>(web_contents1.get()) + ->SetTitle(base::UTF8ToUTF16(kTestTitle1)); MediaSessionImpl* media_session1 = MediaSessionImpl::Get(web_contents1.get()); media_session1->RequestSystemAudioFocus(AudioFocusType::kGain); WaitForCallbackCount(1); @@ -437,7 +438,8 @@ // Create another media session. std::unique_ptr<WebContents> web_contents2 = CreateTestWebContents(); - static_cast<TestWebContents*>(web_contents2.get())->SetTitle(kTestTitle2); + static_cast<TestWebContents*>(web_contents2.get()) + ->SetTitle(base::UTF8ToUTF16(kTestTitle2)); MediaSessionImpl* media_session2 = MediaSessionImpl::Get(web_contents2.get()); media_session2->RequestSystemAudioFocus( AudioFocusType::kGainTransientMayDuck);
diff --git a/content/browser/pointer_lock_browsertest.cc b/content/browser/pointer_lock_browsertest.cc index 64d082c7..7a284f26 100644 --- a/content/browser/pointer_lock_browsertest.cc +++ b/content/browser/pointer_lock_browsertest.cc
@@ -530,7 +530,13 @@ } } -IN_PROC_BROWSER_TEST_F(PointerLockBrowserTest, PointerLockWheelEventRouting) { +#if defined(OS_LINUX) +#define MAYBE_PointerLockWheelEventRouting DISABLED_PointerLockWheelEventRouting +#else +#define MAYBE_PointerLockWheelEventRouting PointerLockWheelEventRouting +#endif +IN_PROC_BROWSER_TEST_F(PointerLockBrowserTest, + MAYBE_PointerLockWheelEventRouting) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b)")); EXPECT_TRUE(NavigateToURL(shell(), main_url));
diff --git a/content/browser/portal/portal_browsertest.cc b/content/browser/portal/portal_browsertest.cc index 80cd520..2167516 100644 --- a/content/browser/portal/portal_browsertest.cc +++ b/content/browser/portal/portal_browsertest.cc
@@ -76,7 +76,7 @@ #include "url/gurl.h" #include "url/url_constants.h" -using testing::_; +using ::testing::_; using trace_analyzer::Query; using trace_analyzer::TraceAnalyzer; using trace_analyzer::TraceEventVector; @@ -1278,7 +1278,7 @@ class PortalOrphanedNavigationBrowserTest : public PortalBrowserTest, - public testing::WithParamInterface<std::tuple<bool, bool>> { + public ::testing::WithParamInterface<std::tuple<bool, bool>> { public: PortalOrphanedNavigationBrowserTest() : cross_site_(std::get<0>(GetParam())), @@ -1286,7 +1286,7 @@ // Provides meaningful param names instead of /0, /1, ... static std::string DescribeParams( - const testing::TestParamInfo<ParamType>& info) { + const ::testing::TestParamInfo<ParamType>& info) { bool cross_site; bool commit_after_adoption; std::tie(cross_site, commit_after_adoption) = info.param; @@ -1308,7 +1308,8 @@ INSTANTIATE_TEST_SUITE_P(All, PortalOrphanedNavigationBrowserTest, - testing::Combine(testing::Bool(), testing::Bool()), + ::testing::Combine(::testing::Bool(), + ::testing::Bool()), PortalOrphanedNavigationBrowserTest::DescribeParams); // Tests that a portal can navigate while orphaned.
diff --git a/content/browser/renderer_host/dwrite_font_proxy_impl_win_unittest.cc b/content/browser/renderer_host/dwrite_font_proxy_impl_win_unittest.cc index 6a869e3a..72cc421c 100644 --- a/content/browser/renderer_host/dwrite_font_proxy_impl_win_unittest.cc +++ b/content/browser/renderer_host/dwrite_font_proxy_impl_win_unittest.cc
@@ -36,7 +36,7 @@ namespace { struct FontExpectation { - const char* font_name; + const char font_name[64]; uint16_t ttc_index; }; @@ -354,10 +354,10 @@ return; base::FilePath result_path; uint32_t ttc_index; - std::u16string unavailable_font_name = - u"Unavailable_Font_Name_56E7EA7E-2C69-4E23-99DC-750BC19B250E"; - dwrite_font_proxy().MatchUniqueFont(unavailable_font_name, &result_path, - &ttc_index); + std::string unavailable_font_name = + "Unavailable_Font_Name_56E7EA7E-2C69-4E23-99DC-750BC19B250E"; + dwrite_font_proxy().MatchUniqueFont(base::UTF8ToUTF16(unavailable_font_name), + &result_path, &ttc_index); ASSERT_EQ(result_path.value().size(), 0u); ASSERT_EQ(ttc_index, 0u); }
diff --git a/content/browser/renderer_host/navigation_request.cc b/content/browser/renderer_host/navigation_request.cc index d176366..a9421808 100644 --- a/content/browser/renderer_host/navigation_request.cc +++ b/content/browser/renderer_host/navigation_request.cc
@@ -1726,7 +1726,7 @@ starting_site_instance_ = frame_tree_node->current_frame_host()->GetSiteInstance(); site_info_ = GetSiteInfoForCommonParamsURL( - starting_site_instance_->GetCoopCoepCrossOriginIsolatedInfo()); + starting_site_instance_->GetWebExposedIsolationInfo()); // Compute the redirect chain. // TODO(clamy): Try to simplify this and have the redirects be part of @@ -2357,10 +2357,9 @@ RenderProcessHost* expected_process = site_instance->HasProcess() ? site_instance->GetProcess() : nullptr; - CoopCoepCrossOriginIsolatedInfo cross_origin_isolated_info = - frame_tree_node_->render_manager()->GetCoopCoepCrossOriginIsolationInfo( - this); - WillRedirectRequest(common_params_->referrer->url, cross_origin_isolated_info, + WebExposedIsolationInfo web_exposed_isolation_info = + frame_tree_node_->render_manager()->GetWebExposedIsolationInfo(this); + WillRedirectRequest(common_params_->referrer->url, web_exposed_isolation_info, expected_process); } @@ -2990,9 +2989,8 @@ // https://crbug.com/738634. SiteInstanceImpl* instance = render_frame_host_->GetSiteInstance(); const IsolationContext& isolation_context = instance->GetIsolationContext(); - auto site_info = - SiteInfo::Create(isolation_context, GetUrlInfo(), - instance->GetCoopCoepCrossOriginIsolatedInfo()); + auto site_info = SiteInfo::Create(isolation_context, GetUrlInfo(), + instance->GetWebExposedIsolationInfo()); if (!instance->HasSite() && site_info.RequiresDedicatedProcess(isolation_context)) { instance->ConvertToDefaultOrSetSite(GetUrlInfo()); @@ -4221,14 +4219,14 @@ } void NavigationRequest::UpdateSiteInfo( - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info, + const WebExposedIsolationInfo& web_exposed_isolation_info, RenderProcessHost* post_redirect_process) { int post_redirect_process_id = post_redirect_process ? post_redirect_process->GetID() : ChildProcessHost::kInvalidUniqueID; SiteInfo new_site_info = - GetSiteInfoForCommonParamsURL(cross_origin_isolated_info); + GetSiteInfoForCommonParamsURL(web_exposed_isolation_info); if (new_site_info == site_info_ && post_redirect_process_id == expected_render_process_host_id_) { return; @@ -4996,12 +4994,12 @@ void NavigationRequest::WillRedirectRequest( const GURL& new_referrer_url, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info, + const WebExposedIsolationInfo& web_exposed_isolation_info, RenderProcessHost* post_redirect_process) { EnterChildTraceEvent("WillRedirectRequest", this, "url", common_params_->url.possibly_invalid_spec()); UpdateStateFollowingRedirect(new_referrer_url); - UpdateSiteInfo(cross_origin_isolated_info, post_redirect_process); + UpdateSiteInfo(web_exposed_isolation_info, post_redirect_process); if (IsSelfReferentialURL()) { SetState(CANCELING); @@ -5166,11 +5164,11 @@ } SiteInfo NavigationRequest::GetSiteInfoForCommonParamsURL( - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info) { + const WebExposedIsolationInfo& web_exposed_isolation_info) { // TODO(alexmos): Using |starting_site_instance_|'s IsolationContext may not // be correct for cross-BrowsingInstance redirects. return SiteInfo::Create(starting_site_instance_->GetIsolationContext(), - GetUrlInfo(), cross_origin_isolated_info); + GetUrlInfo(), web_exposed_isolation_info); } // TODO(zetamoo): Try to merge this function inside its callers.
diff --git a/content/browser/renderer_host/navigation_request.h b/content/browser/renderer_host/navigation_request.h index 46fb388f..8a80bdd 100644 --- a/content/browser/renderer_host/navigation_request.h +++ b/content/browser/renderer_host/navigation_request.h
@@ -468,11 +468,10 @@ // redirects. |post_redirect_process| is the renderer process that should // handle the navigation following the redirect if it can be handled by an // existing RenderProcessHost. Otherwise, it should be null. - // |cross_origin_isolated_info| is the new COOP/COEP info extracted from the + // |web_exposed_isolation_info| is the new isolation info extracted from the // redirect response. - void UpdateSiteInfo( - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info, - RenderProcessHost* post_redirect_process); + void UpdateSiteInfo(const WebExposedIsolationInfo& web_exposed_isolation_info, + RenderProcessHost* post_redirect_process); int nav_entry_id() const { return nav_entry_id_; } @@ -1154,11 +1153,11 @@ // no live process that can be used. In that case, a suitable renderer process // will be created at commit time. // - // |cross_origin_isolated_info| is the new COOP/COEP info extracted from the + // |web_exposed_isolation_info| is the new isolation info extracted from the // redirect response. void WillRedirectRequest( const GURL& new_referrer_url, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info, + const WebExposedIsolationInfo& web_exposed_isolation_info, RenderProcessHost* post_redirect_process); // Called when the URLRequest will fail. @@ -1189,8 +1188,7 @@ // Helper function that computes the SiteInfo for |common_params_.url|. // Note: |site_info_| should only be updated with the result of this function. SiteInfo GetSiteInfoForCommonParamsURL( - const CoopCoepCrossOriginIsolatedInfo& - cross_origin_isolated_origin_status); + const WebExposedIsolationInfo& cross_origin_isolated_origin_status); // Updates the state of the navigation handle after encountering a server // redirect.
diff --git a/content/browser/renderer_host/navigation_request_unittest.cc b/content/browser/renderer_host/navigation_request_unittest.cc index 49b925d..bd0f5c8 100644 --- a/content/browser/renderer_host/navigation_request_unittest.cc +++ b/content/browser/renderer_host/navigation_request_unittest.cc
@@ -118,9 +118,9 @@ base::BindOnce(&NavigationRequestTest::UpdateThrottleCheckResult, base::Unretained(this))); - request_->WillRedirectRequest( - GURL(), CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated(), - nullptr /* post_redirect_process */); + request_->WillRedirectRequest(GURL(), + WebExposedIsolationInfo::CreateNonIsolated(), + nullptr /* post_redirect_process */); } // Helper function to call WillFailRequest on |handle|. If this function
diff --git a/content/browser/renderer_host/navigator.cc b/content/browser/renderer_host/navigator.cc index e494a06..d71c4f4 100644 --- a/content/browser/renderer_host/navigator.cc +++ b/content/browser/renderer_host/navigator.cc
@@ -79,10 +79,10 @@ switch (rfh->cross_origin_embedder_policy().value) { case network::mojom::CrossOriginEmbedderPolicyValue::kNone: break; - case network::mojom::CrossOriginEmbedderPolicyValue::kCorsOrCredentialless: + case network::mojom::CrossOriginEmbedderPolicyValue::kCredentialless: client->LogWebFeatureForCurrentPage( - rfh, blink::mojom::WebFeature:: - kCrossOriginEmbedderPolicyCorsOrCredentialless); + rfh, + blink::mojom::WebFeature::kCrossOriginEmbedderPolicyCredentialless); break; case network::mojom::CrossOriginEmbedderPolicyValue::kRequireCorp: client->LogWebFeatureForCurrentPage(
diff --git a/content/browser/renderer_host/navigator_unittest.cc b/content/browser/renderer_host/navigator_unittest.cc index 35cd4f90..cc3254b0 100644 --- a/content/browser/renderer_host/navigator_unittest.cc +++ b/content/browser/renderer_host/navigator_unittest.cc
@@ -1224,7 +1224,7 @@ SiteInstanceDescriptor descriptor( UrlInfo::CreateForTesting(kUrlSameSiteAs1), SiteInstanceRelation::RELATED, - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated()); + WebExposedIsolationInfo::CreateNonIsolated()); scoped_refptr<SiteInstance> converted_instance = ConvertToSiteInstance(rfhm, descriptor, nullptr); EXPECT_EQ(current_instance, converted_instance); @@ -1238,7 +1238,7 @@ SiteInstanceDescriptor descriptor( UrlInfo::CreateForTesting(kUrlSameSiteAs2), SiteInstanceRelation::RELATED, - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated()); + WebExposedIsolationInfo::CreateNonIsolated()); related_instance = ConvertToSiteInstance(rfhm, descriptor, nullptr); // If kUrlSameSiteAs2 requires a dedicated process on this platform, this // should return a new instance, related to the current and set to the new @@ -1264,7 +1264,7 @@ SiteInstanceDescriptor descriptor( UrlInfo::CreateForTesting(kUrlSameSiteAs1), SiteInstanceRelation::UNRELATED, - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated()); + WebExposedIsolationInfo::CreateNonIsolated()); scoped_refptr<SiteInstanceImpl> converted_instance_1 = ConvertToSiteInstance(rfhm, descriptor, nullptr); // Should return a new instance, unrelated to the current one, set to the @@ -1304,7 +1304,7 @@ SiteInstanceDescriptor descriptor( UrlInfo::CreateForTesting(kUrlSameSiteAs2), SiteInstanceRelation::UNRELATED, - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated()); + WebExposedIsolationInfo::CreateNonIsolated()); scoped_refptr<SiteInstanceImpl> converted_instance_1 = ConvertToSiteInstance(rfhm, descriptor, related_instance.get()); // Should return a new instance, unrelated to the current, set to the
diff --git a/content/browser/renderer_host/recently_destroyed_hosts_unittest.cc b/content/browser/renderer_host/recently_destroyed_hosts_unittest.cc index 53fca612..b0cfd4b 100644 --- a/content/browser/renderer_host/recently_destroyed_hosts_unittest.cc +++ b/content/browser/renderer_host/recently_destroyed_hosts_unittest.cc
@@ -10,9 +10,9 @@ #include "base/time/time.h" #include "content/browser/browsing_instance.h" #include "content/browser/child_process_security_policy_impl.h" -#include "content/browser/coop_coep_cross_origin_isolated_info.h" #include "content/browser/isolation_context.h" #include "content/browser/site_instance_impl.h" +#include "content/browser/web_exposed_isolation_info.h" #include "content/public/test/browser_task_environment.h" #include "content/public/test/mock_render_process_host.h" #include "content/public/test/test_browser_context.h" @@ -54,7 +54,7 @@ const ProcessLock process_lock = ProcessLock::Create( isolation_context, UrlInfo::CreateForTesting(GURL("https://www.google.com")), - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated()); + WebExposedIsolationInfo::CreateNonIsolated()); constexpr char kHistogramName[] = "SiteIsolation.ReusePendingOrCommittedSite."
diff --git a/content/browser/renderer_host/render_frame_host_impl.cc b/content/browser/renderer_host/render_frame_host_impl.cc index 01cd1f3..61a3754 100644 --- a/content/browser/renderer_host/render_frame_host_impl.cc +++ b/content/browser/renderer_host/render_frame_host_impl.cc
@@ -56,7 +56,6 @@ #include "content/browser/child_process_security_policy_impl.h" #include "content/browser/compute_pressure/compute_pressure_manager.h" #include "content/browser/contacts/contacts_manager_impl.h" -#include "content/browser/coop_coep_cross_origin_isolated_info.h" #include "content/browser/data_url_loader_factory.h" #include "content/browser/devtools/devtools_instrumentation.h" #include "content/browser/devtools/protocol/audits.h" @@ -131,6 +130,7 @@ #include "content/browser/speech/speech_synthesis_impl.h" #include "content/browser/storage_partition_impl.h" #include "content/browser/url_loader_factory_params_helper.h" +#include "content/browser/web_exposed_isolation_info.h" #include "content/browser/web_package/prefetched_signed_exchange_cache.h" #include "content/browser/web_package/subresource_web_bundle_navigation_info.h" #include "content/browser/web_package/web_bundle_handle.h" @@ -1879,7 +1879,7 @@ RenderFrameHostImpl::GetCrossOriginIsolationStatus() { ProcessLock process_lock = GetSiteInstance()->GetProcessLock(); if (process_lock.is_invalid() || - !process_lock.coop_coep_cross_origin_isolated_info().is_isolated()) { + !process_lock.web_exposed_isolation_info().is_isolated()) { // Cross-origin isolated frames must be hosted in cross-origin isolated // processes. return RenderFrameHost::CrossOriginIsolationStatus::kNotIsolated; @@ -6337,7 +6337,7 @@ const CanCommitStatus can_commit_status = policy->CanCommitOriginAndUrl( GetProcess()->GetID(), GetSiteInstance()->GetIsolationContext(), origin, UrlInfo(url, UrlInfo::OriginIsolationRequest::kNone, origin), - GetSiteInstance()->GetCoopCoepCrossOriginIsolatedInfo()); + GetSiteInstance()->GetWebExposedIsolationInfo()); if (can_commit_status != CanCommitStatus::CAN_COMMIT_ORIGIN_AND_URL) { LogCanCommitOriginAndUrlFailureReason("cpspi_disallowed_commit"); return can_commit_status; @@ -6720,8 +6720,7 @@ return false; } if (!old_frame_host->IsNavigationSameSite( - dest_url_info, - GetSiteInstance()->GetCoopCoepCrossOriginIsolatedInfo())) { + dest_url_info, GetSiteInstance()->GetWebExposedIsolationInfo())) { return false; } DCHECK(frame_tree_node_->IsMainFrame()); @@ -8904,12 +8903,11 @@ // Since |url| has already committed, |origin_isolation_request| below should // be set to kNone. SiteInfo site_info = - url.is_empty() - ? SiteInfo() - : SiteInfo::Create( - GetSiteInstance()->GetIsolationContext(), - UrlInfo(url, UrlInfo::OriginIsolationRequest::kNone), - GetSiteInstance()->GetCoopCoepCrossOriginIsolatedInfo()); + url.is_empty() ? SiteInfo() + : SiteInfo::Create( + GetSiteInstance()->GetIsolationContext(), + UrlInfo(url, UrlInfo::OriginIsolationRequest::kNone), + GetSiteInstance()->GetWebExposedIsolationInfo()); if (last_committed_site_info_ == site_info) return; @@ -9074,9 +9072,9 @@ bool RenderFrameHostImpl::IsNavigationSameSite( const UrlInfo& dest_url_info, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info) { - if (GetSiteInstance()->GetCoopCoepCrossOriginIsolatedInfo() != - cross_origin_isolated_info) { + const WebExposedIsolationInfo& web_exposed_isolation_info) { + if (GetSiteInstance()->GetWebExposedIsolationInfo() != + web_exposed_isolation_info) { return false; } return GetSiteInstance()->IsNavigationSameSite( @@ -10437,6 +10435,7 @@ // - http_status_code // - should_update_history // - gesture + // - should_replace_current_entry // TODO(crbug.com/1131832): Verify more params. // We can know if we're going to be in an error page after this navigation // if the net error code is not net::OK, or if we're doing a same-document @@ -10484,6 +10483,21 @@ const bool renderer_gesture = (params.gesture == NavigationGesture::NavigationGestureUser); + const bool browser_should_replace_current_entry = + CalculateShouldReplaceCurrentEntry( + request, same_document_params.Clone(), frame_tree_node_, + last_committed_url_, is_loaded_from_load_data_with_base_url_, + last_base_url_); + // Currently it's not possible to correctly predict the value of + // should_replace_current_entry in the browser for iframes with + // has_committed_real_load == false because some cases like document.open() + // will affect the result in the renderer (through EmptyDocumentStatus) but + // the browser don't have a way to know that it happened. + // See https://crbug.com/1204981 and https://crrev.com/c/2818538. + const bool ignore_should_replace_current_entry_difference = + (!frame_tree_node_->IsMainFrame() && + !frame_tree_node_->has_committed_real_load()); + if ((!ShouldVerify("intended_as_new_entry") || request->commit_params().intended_as_new_entry == params.intended_as_new_entry) && @@ -10497,7 +10511,11 @@ browser_http_status_code == params.http_status_code) && (!ShouldVerify("should_update_history") || browser_should_update_history == params.should_update_history) && - (!ShouldVerify("gesture") || browser_gesture == renderer_gesture)) { + (!ShouldVerify("gesture") || browser_gesture == renderer_gesture) && + (!ShouldVerify("should_replace_current_entry") || + ignore_should_replace_current_entry_difference || + browser_should_replace_current_entry == + params.should_replace_current_entry)) { return; } @@ -10572,6 +10590,11 @@ SCOPED_CRASH_KEY_BOOL("VerifyDidCommit", "gesture_renderer", renderer_gesture); + SCOPED_CRASH_KEY_BOOL("VerifyDidCommit", "replace_browser", + browser_should_replace_current_entry); + SCOPED_CRASH_KEY_BOOL("VerifyDidCommit", "replace_renderer", + params.should_replace_current_entry); + SCOPED_CRASH_KEY_BOOL("VerifyDidCommit", "is_same_document", is_same_document_navigation); SCOPED_CRASH_KEY_BOOL("VerifyDidCommit", "is_history_api", @@ -10673,6 +10696,8 @@ DCHECK_EQ(browser_http_status_code, params.http_status_code); DCHECK_EQ(browser_should_update_history, params.should_update_history); DCHECK_EQ(browser_gesture, renderer_gesture); + DCHECK_EQ(browser_should_replace_current_entry, + params.should_replace_current_entry); // Log histograms to trigger Chrometto slow reports, allowing us to see traces // to analyze what happened in these navigations. @@ -10709,6 +10734,11 @@ LogVerifyDidCommitParamsDifference( VerifyDidCommitParamsDifference::kGesture); } + if (browser_should_replace_current_entry != + params.should_replace_current_entry) { + LogVerifyDidCommitParamsDifference( + VerifyDidCommitParamsDifference::kShouldReplaceCurrentEntry); + } base::debug::DumpWithoutCrashing(); }
diff --git a/content/browser/renderer_host/render_frame_host_impl.h b/content/browser/renderer_host/render_frame_host_impl.h index 1b1aa38..410ba79 100644 --- a/content/browser/renderer_host/render_frame_host_impl.h +++ b/content/browser/renderer_host/render_frame_host_impl.h
@@ -36,7 +36,6 @@ #include "content/browser/bad_message.h" #include "content/browser/browser_interface_broker_impl.h" #include "content/browser/can_commit_status.h" -#include "content/browser/coop_coep_cross_origin_isolated_info.h" #include "content/browser/feature_observer.h" #include "content/browser/idle/idle_manager_impl.h" #include "content/browser/net/cross_origin_opener_policy_reporter.h" @@ -48,6 +47,7 @@ #include "content/browser/renderer_host/policy_container_host.h" #include "content/browser/renderer_host/render_widget_host_impl.h" #include "content/browser/site_instance_impl.h" +#include "content/browser/web_exposed_isolation_info.h" #include "content/browser/webui/web_ui_impl.h" #include "content/common/buildflags.h" #include "content/common/content_export.h" @@ -613,11 +613,11 @@ // determining if a navigation to |dest_url_info| should stay in this // RenderFrameHost's SiteInstance. // - // |cross_origin_isolated_info| indicates the cross-origin isolation status, + // |web_exposed_isolation_info| indicates the web-exposed isolation status, // as deduced from COOP and COEP headers. bool IsNavigationSameSite( const UrlInfo& dest_url_info, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info); + const WebExposedIsolationInfo& web_exposed_isolation_info); // Returns |frame_origin| if this frame is the top (i.e. root) frame in the // frame tree. Otherwise, it returns the top frame's origin.
diff --git a/content/browser/renderer_host/render_frame_host_manager.cc b/content/browser/renderer_host/render_frame_host_manager.cc index 3bd26f7..1fda71b 100644 --- a/content/browser/renderer_host/render_frame_host_manager.cc +++ b/content/browser/renderer_host/render_frame_host_manager.cc
@@ -99,7 +99,7 @@ bool ShouldSwapBrowsingInstancesForDynamicIsolation( RenderFrameHostImpl* current_rfh, const UrlInfo& destination_effective_url_info, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info) { + const WebExposedIsolationInfo& web_exposed_isolation_info) { // Only main frames are eligible to swap BrowsingInstances. if (!current_rfh->frame_tree_node()->IsMainFrame()) return false; @@ -115,7 +115,7 @@ auto& current_isolation_context = current_instance->GetIsolationContext(); auto current_site_info = SiteInfo::Create(current_isolation_context, destination_effective_url_info, - cross_origin_isolated_info); + web_exposed_isolation_info); if (current_site_info.RequiresDedicatedProcess(current_isolation_context)) return false; @@ -127,7 +127,7 @@ current_instance->GetBrowserContext()); auto future_site_info = SiteInfo::Create(future_isolation_context, destination_effective_url_info, - cross_origin_isolated_info); + web_exposed_isolation_info); return future_site_info.RequiresDedicatedProcess(future_isolation_context); } @@ -151,11 +151,11 @@ return is_site_instance_for_failures == is_failure; } -bool IsSiteInstanceCompatibleWithCoopCoepCrossOriginIsolation( +bool IsSiteInstanceCompatibleWithWebExposedIsolation( SiteInstance* site_instance, bool is_main_frame, const GURL& url, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info, + const WebExposedIsolationInfo& web_exposed_isolation_info, bool is_speculative) { // We do not want cross-origin-isolated have any impact on SiteInstances until // we get an actual COOP value in a redirect or a final response. @@ -165,8 +165,8 @@ // Note: The about blank case is to accommodate web tests that use COOP. They // expect an about:blank page to stay in process, and hang otherwise. In // general, it is safe to allow about:blank pages to stay in process, since - // scriptability is limited to the BrowsingInstance and all pages in a - // cross-origin isolated BrowsingInstance are trusted. + // scriptability is limited to the BrowsingInstance and all pages with the + // same web-exposed isolation level are trusted. if (url.IsAboutBlank()) return true; @@ -174,14 +174,14 @@ static_cast<SiteInstanceImpl*>(site_instance); if (is_main_frame) { - return site_instance_impl->GetCoopCoepCrossOriginIsolatedInfo() == - cross_origin_isolated_info; + return site_instance_impl->GetWebExposedIsolationInfo() == + web_exposed_isolation_info; } // Subframes cannot swap BrowsingInstances, as a result they should either not // load, for instance blocked by COEP, or inherit a compatible cross-origin // isolated state. - DCHECK_EQ(site_instance_impl->IsCoopCoepCrossOriginIsolated(), - cross_origin_isolated_info.is_isolated()); + DCHECK_EQ(site_instance_impl->IsCrossOriginIsolated(), + web_exposed_isolation_info.is_isolated()); return true; } @@ -877,7 +877,7 @@ bool use_current_rfh = current_site_instance == dest_site_instance; bool is_same_site = render_frame_host_->IsNavigationSameSite( - request->GetUrlInfo(), GetCoopCoepCrossOriginIsolationInfo(request)); + request->GetUrlInfo(), GetWebExposedIsolationInfo(request)); if (frame_tree_node_->IsMainFrame()) { // Same-site navigations could swap BrowsingInstance as well. But we only // want to clear window.name on cross-site cross-BrowsingInstance main frame @@ -1280,11 +1280,11 @@ RenderFrameHostManager::SiteInstanceDescriptor::SiteInstanceDescriptor( UrlInfo dest_url_info, SiteInstanceRelation relation_to_current, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info) + const WebExposedIsolationInfo& web_exposed_isolation_info) : existing_site_instance(nullptr), dest_url_info(dest_url_info), relation(relation_to_current), - cross_origin_isolated_info(cross_origin_isolated_info) {} + web_exposed_isolation_info(web_exposed_isolation_info) {} void RenderFrameHostManager::RenderProcessGone( SiteInstanceImpl* instance, @@ -1385,7 +1385,7 @@ SiteInstanceImpl* current_instance, SiteInstance* destination_instance, const UrlInfo& destination_url_info, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info, + const WebExposedIsolationInfo& web_exposed_isolation_info, bool destination_is_view_source_mode, ui::PageTransition transition, bool is_failure, @@ -1521,7 +1521,7 @@ render_frame_host_.get(), UrlInfo(destination_effective_url, destination_url_info.origin_isolation_request), - cross_origin_isolated_info)) { + web_exposed_isolation_info)) { return ShouldSwapBrowsingInstance::kYes_ForceSwap; } @@ -1536,10 +1536,10 @@ frame_tree_node_->IsMainFrame()); if (current_instance->HasSite() && !render_frame_host_->IsNavigationSameSite(destination_url_info, - cross_origin_isolated_info) && + web_exposed_isolation_info) && !CanUseSourceSiteInstance(destination_url, source_instance, was_server_redirect, is_failure, - cross_origin_isolated_info, is_speculative) && + web_exposed_isolation_info, is_speculative) && !is_for_isolated_error_page && IsBrowsingInstanceSwapAllowedForPageTransition(transition, destination_url) && @@ -1550,14 +1550,14 @@ // Experimental mode to swap BrowsingInstances on most navigations when there // are no other windows in the BrowsingInstance. return ShouldProactivelySwapBrowsingInstance( - destination_url_info, cross_origin_isolated_info, is_reload, + destination_url_info, web_exposed_isolation_info, is_reload, should_replace_current_entry); } ShouldSwapBrowsingInstance RenderFrameHostManager::ShouldProactivelySwapBrowsingInstance( const UrlInfo& destination_url_info, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info, + const WebExposedIsolationInfo& web_exposed_isolation_info, bool is_reload, bool should_replace_current_entry) { // If we've disabled proactive BrowsingInstance swap for this RenderFrameHost, @@ -1633,7 +1633,7 @@ return ShouldSwapBrowsingInstance::kNo_Reload; bool is_same_site = render_frame_host_->IsNavigationSameSite( - destination_url_info, cross_origin_isolated_info); + destination_url_info, web_exposed_isolation_info); if (is_same_site) { // If it's a same-site navigation, we should only swap if same-site // ProactivelySwapBrowsingInstance is enabled, or if same-site @@ -1692,7 +1692,7 @@ scoped_refptr<SiteInstance> RenderFrameHostManager::GetSiteInstanceForNavigation( const UrlInfo& dest_url_info, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info, + const WebExposedIsolationInfo& web_exposed_isolation_info, SiteInstanceImpl* source_instance, SiteInstanceImpl* dest_instance, SiteInstanceImpl* candidate_instance, @@ -1764,7 +1764,7 @@ ShouldSwapBrowsingInstancesForNavigation( current_effective_url, current_is_view_source_mode, source_instance, current_instance_impl, dest_instance, dest_url_info, - cross_origin_isolated_info, dest_is_view_source_mode, transition, + web_exposed_isolation_info, dest_is_view_source_mode, transition, is_failure, is_reload, is_same_document, cross_origin_opener_policy_mismatch, was_server_redirect, should_replace_current_entry, is_speculative); @@ -1789,7 +1789,7 @@ } SiteInstanceDescriptor new_instance_descriptor = DetermineSiteInstanceForURL( - dest_url_info, cross_origin_isolated_info, source_instance, + dest_url_info, web_exposed_isolation_info, source_instance, current_instance, dest_instance, transition, is_failure, dest_is_restore, dest_is_view_source_mode, should_swap, was_server_redirect, is_speculative, reason); @@ -1798,9 +1798,9 @@ new_instance_descriptor, candidate_instance, is_speculative); SiteInstanceImpl* new_instance_impl = static_cast<SiteInstanceImpl*>(new_instance.get()); - DCHECK(IsSiteInstanceCompatibleWithCoopCoepCrossOriginIsolation( + DCHECK(IsSiteInstanceCompatibleWithWebExposedIsolation( new_instance_impl, frame_tree_node_->IsMainFrame(), dest_url, - cross_origin_isolated_info, is_speculative)); + web_exposed_isolation_info, is_speculative)); // If |should_swap| is true, we must use a different SiteInstance than the // current one. If we didn't, we would have two RenderFrameHosts in the same @@ -1884,7 +1884,7 @@ if (is_same_site_proactive_swap_enabled && is_history_navigation && swapped_browsing_instance && render_frame_host_->IsNavigationSameSite(dest_url_info, - cross_origin_isolated_info)) { + web_exposed_isolation_info)) { reuse_current_process_if_possible = true; } @@ -1949,7 +1949,7 @@ RenderFrameHostManager::SiteInstanceDescriptor RenderFrameHostManager::DetermineSiteInstanceForURL( const UrlInfo& dest_url_info, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info, + const WebExposedIsolationInfo& web_exposed_isolation_info, SiteInstance* source_instance, SiteInstance* current_instance, SiteInstance* dest_instance, @@ -1978,9 +1978,9 @@ // when error pages are involved. if (IsSiteInstanceCompatibleWithErrorIsolation( dest_instance, frame_tree_node_->IsMainFrame(), is_failure)) { - if (IsSiteInstanceCompatibleWithCoopCoepCrossOriginIsolation( + if (IsSiteInstanceCompatibleWithWebExposedIsolation( dest_instance, frame_tree_node_->IsMainFrame(), dest_url_info.url, - cross_origin_isolated_info, is_speculative)) { + web_exposed_isolation_info, is_speculative)) { // TODO(nasko,creis): The check whether data: or about: URLs are allowed // to commit in the current process should be in IsSuitableForURL. // However, making this change has further implications and needs more @@ -2019,14 +2019,14 @@ UrlInfo::OriginIsolationRequest::kNone), force_browsing_instance_swap ? SiteInstanceRelation::UNRELATED : SiteInstanceRelation::RELATED, - cross_origin_isolated_info); + web_exposed_isolation_info); } // If a swap is required, we need to force the SiteInstance AND // BrowsingInstance to be different ones, using CreateForURL. bool can_use_source_instance = CanUseSourceSiteInstance( dest_url_info.url, source_instance, was_server_redirect, is_failure, - cross_origin_isolated_info, is_speculative); + web_exposed_isolation_info, is_speculative); if (force_browsing_instance_swap) { // In rare cases, |source_instance| maybe be already in another // BrowsingInstance from |current_instance| (e.g. see how the @@ -2049,7 +2049,7 @@ "DetermineSiteInstanceForURL / browsing-instance-swap"); return SiteInstanceDescriptor(dest_url_info, SiteInstanceRelation::UNRELATED, - cross_origin_isolated_info); + web_exposed_isolation_info); } // TODO(https://crbug.com/566091): Don't create OOPIFs on the NTP. Remove @@ -2060,8 +2060,8 @@ frame_tree_node_->parent()->GetSiteInstance(); if (GetContentClient()->browser()->ShouldStayInParentProcessForNTP( dest_url_info.url, parent_site_instance)) { - // NTP does not define COOP/COEP. - DCHECK(!cross_origin_isolated_info.is_isolated()); + // NTP is considered non-isolated. + DCHECK(!web_exposed_isolation_info.is_isolated()); AppendReason(reason, "DetermineSiteInstanceForURL => parent_site_instance"); return SiteInstanceDescriptor(parent_site_instance); @@ -2082,10 +2082,10 @@ // is received (in OnResponseStarted), unless the navigation entry was // restored or it's a Web UI as described below. // TODO(ahemery): In theory we should be able to go for an unused SiteInstance - // with the same |is_coop_coep_cross_origin_isolated| status. + // with the same |is_cross_origin_isolated| status. if (!current_instance_impl->HasSite() && - !cross_origin_isolated_info.is_isolated() && - !current_instance_impl->IsCoopCoepCrossOriginIsolated()) { + !web_exposed_isolation_info.is_isolated() && + !current_instance_impl->IsCrossOriginIsolated()) { // If we've already created a SiteInstance for our destination, we don't // want to use this unused SiteInstance; use the existing one. (We don't // do this check if the current_instance has a site, because for now, we @@ -2100,11 +2100,11 @@ DCHECK_EQ(controller.GetBrowserContext(), current_instance_impl->GetBrowserContext()); - // TODO(acolwell): Remove DCHECK once |cross_origin_isolated_info| has been + // TODO(acolwell): Remove DCHECK once |web_exposed_isolation_info| has been // moved into UrlInfo and becomes part of |dest_url_info|. The // DeriveSiteInfo() call below is depending on the COOP/COEP info matching. - DCHECK(cross_origin_isolated_info == - current_instance_impl->GetCoopCoepCrossOriginIsolatedInfo()); + DCHECK(web_exposed_isolation_info == + current_instance_impl->GetWebExposedIsolationInfo()); const SiteInfo dest_site_info = current_instance_impl->DeriveSiteInfo(dest_url_info); bool use_process_per_site = @@ -2120,7 +2120,7 @@ "has-related-site-instance-or-using-process-per-site"); return SiteInstanceDescriptor( dest_url_info, SiteInstanceRelation::RELATED, - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated()); + WebExposedIsolationInfo::CreateNonIsolated()); } // For extensions, Web UI URLs (such as the new tab page), and apps we do @@ -2133,7 +2133,7 @@ "!current_instance->IsSuitable"); return SiteInstanceDescriptor( dest_url_info, SiteInstanceRelation::RELATED, - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated()); + WebExposedIsolationInfo::CreateNonIsolated()); } // Normally the "site" on the SiteInstance is set lazily when the load @@ -2162,11 +2162,11 @@ // Use the current SiteInstance for same site navigations. if (render_frame_host_->IsNavigationSameSite(dest_url_info, - cross_origin_isolated_info) && - IsSiteInstanceCompatibleWithCoopCoepCrossOriginIsolation( + web_exposed_isolation_info) && + IsSiteInstanceCompatibleWithWebExposedIsolation( render_frame_host_->GetSiteInstance(), frame_tree_node_->IsMainFrame(), dest_url_info.url, - cross_origin_isolated_info, is_speculative)) { + web_exposed_isolation_info, is_speculative)) { AppendReason(reason, "DetermineSiteInstanceForURL / same-site-navigation"); return SiteInstanceDescriptor(render_frame_host_->GetSiteInstance()); } @@ -2190,7 +2190,7 @@ RenderFrameHostImpl* main_frame = frame_tree_node_->frame_tree()->root()->current_frame_host(); if (IsCandidateSameSite(main_frame, dest_url_info, - cross_origin_isolated_info)) { + web_exposed_isolation_info)) { AppendReason(reason, "DetermineSiteInstanceForURL / subframe-reuse => " "main-frame-instance"); @@ -2198,7 +2198,7 @@ } RenderFrameHostImpl* parent = frame_tree_node_->parent(); if (IsCandidateSameSite(parent, dest_url_info, - cross_origin_isolated_info)) { + web_exposed_isolation_info)) { AppendReason(reason, "DetermineSiteInstanceForURL / subframe-reuse => " "parent-instance"); @@ -2209,7 +2209,7 @@ RenderFrameHostImpl* opener_frame = frame_tree_node_->opener()->current_frame_host(); if (IsCandidateSameSite(opener_frame, dest_url_info, - cross_origin_isolated_info)) { + web_exposed_isolation_info)) { AppendReason(reason, "DetermineSiteInstanceForURL => opener-instance"); return SiteInstanceDescriptor(opener_frame->GetSiteInstance()); } @@ -2236,7 +2236,7 @@ parent->GetSiteInstance()->GetIsolationContext(); auto site_info = SiteInfo::Create(parent_isolation_context, dest_url_info, - cross_origin_isolated_info); + web_exposed_isolation_info); if (!parent->GetSiteInstance()->RequiresDedicatedProcess() && !site_info.RequiresDedicatedProcess(parent_isolation_context)) { AppendReason(reason, @@ -2248,22 +2248,22 @@ } // Start the new renderer in a new SiteInstance, but in the current - // BrowsingInstance, unless the destination URL's cross-origin isolated state + // BrowsingInstance, unless the destination URL's web-exposed isolated state // cannot be hosted by it. - if (IsSiteInstanceCompatibleWithCoopCoepCrossOriginIsolation( + if (IsSiteInstanceCompatibleWithWebExposedIsolation( render_frame_host_->GetSiteInstance(), frame_tree_node_->IsMainFrame(), dest_url_info.url, - cross_origin_isolated_info, is_speculative)) { + web_exposed_isolation_info, is_speculative)) { AppendReason(reason, "DetermineSiteInstanceForURL / fallback / coop-compatible"); return SiteInstanceDescriptor(dest_url_info, SiteInstanceRelation::RELATED, - cross_origin_isolated_info); + web_exposed_isolation_info); } else { AppendReason( reason, "DetermineSiteInstanceForURL / fallback / not-coop-compatible"); return SiteInstanceDescriptor(dest_url_info, SiteInstanceRelation::UNRELATED, - cross_origin_isolated_info); + web_exposed_isolation_info); } } @@ -2316,8 +2316,8 @@ // not yet been invoked. CHECK(is_speculative || descriptor.relation != SiteInstanceRelation::RELATED || - current_instance->IsCoopCoepCrossOriginIsolated() == - descriptor.cross_origin_isolated_info.is_isolated()); + current_instance->IsCrossOriginIsolated() == + descriptor.web_exposed_isolation_info.is_isolated()); // Note: If the |candidate_instance| matches the descriptor, it will already // be set to |descriptor.existing_site_instance|. @@ -2333,7 +2333,7 @@ // Note that by the time we get here, we've already ensured that this // BrowsingInstance has a compatible cross-origin isolated state, so we are // guaranteed to return a SiteInstance that will be compatible with - // |descriptor.is_coop_coep_cross_origin_isolated|." + // |descriptor.web_exposed_isolation_info|." if (descriptor.relation == SiteInstanceRelation::RELATED) return current_instance->GetRelatedSiteInstanceImpl( descriptor.dest_url_info); @@ -2341,9 +2341,9 @@ // At this point we know an unrelated site instance must be returned. First // check if the candidate matches. if (candidate_instance && - IsSiteInstanceCompatibleWithCoopCoepCrossOriginIsolation( + IsSiteInstanceCompatibleWithWebExposedIsolation( candidate_instance, frame_tree_node_->IsMainFrame(), - descriptor.dest_url_info.url, descriptor.cross_origin_isolated_info, + descriptor.dest_url_info.url, descriptor.web_exposed_isolation_info, is_speculative) && !current_instance->IsRelatedSiteInstance(candidate_instance) && candidate_instance->DoesSiteInfoForURLMatch(descriptor.dest_url_info)) { @@ -2353,7 +2353,7 @@ // Otherwise return a newly created one. return SiteInstanceImpl::CreateForUrlInfo( GetNavigationController().GetBrowserContext(), descriptor.dest_url_info, - descriptor.cross_origin_isolated_info); + descriptor.web_exposed_isolation_info); } bool RenderFrameHostManager::CanUseSourceSiteInstance( @@ -2361,7 +2361,7 @@ SiteInstance* source_instance, bool was_server_redirect, bool is_failure, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info, + const WebExposedIsolationInfo& web_exposed_isolation_info, bool is_speculative) { if (!source_instance) return false; @@ -2394,9 +2394,9 @@ return false; } - if (!IsSiteInstanceCompatibleWithCoopCoepCrossOriginIsolation( + if (!IsSiteInstanceCompatibleWithWebExposedIsolation( source_instance, frame_tree_node_->IsMainFrame(), dest_url, - cross_origin_isolated_info, is_speculative)) { + web_exposed_isolation_info, is_speculative)) { return false; } @@ -2407,11 +2407,11 @@ bool RenderFrameHostManager::IsCandidateSameSite( RenderFrameHostImpl* candidate, const UrlInfo& dest_url_info, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info) { + const WebExposedIsolationInfo& web_exposed_isolation_info) { DCHECK_EQ(GetNavigationController().GetBrowserContext(), candidate->GetSiteInstance()->GetBrowserContext()); - if (candidate->GetSiteInstance()->GetCoopCoepCrossOriginIsolatedInfo() != - cross_origin_isolated_info) { + if (candidate->GetSiteInstance()->GetWebExposedIsolationInfo() != + web_exposed_isolation_info) { return false; } @@ -2828,30 +2828,32 @@ return created; } -CoopCoepCrossOriginIsolatedInfo -RenderFrameHostManager::GetCoopCoepCrossOriginIsolationInfo( +WebExposedIsolationInfo RenderFrameHostManager::GetWebExposedIsolationInfo( NavigationRequest* navigation_request) { if (base::FeatureList::IsEnabled(network::features::kCrossOriginIsolated)) { if (frame_tree_node_->IsMainFrame()) { - bool is_coop_coep_cross_origin_isolated = + bool is_cross_origin_isolated = navigation_request->coop_status().current_coop().value == network::mojom::CrossOriginOpenerPolicyValue::kSameOriginPlusCoep; - if (is_coop_coep_cross_origin_isolated) { - return CoopCoepCrossOriginIsolatedInfo::CreateIsolated( + if (is_cross_origin_isolated) { + return WebExposedIsolationInfo::CreateIsolated( url::Origin::Create(navigation_request->common_params().url)); } } else { - // If we are in an iframe, we inherit the cross-origin isolated state of + // If we are in an iframe, we inherit the isolation state of // the top level frame. This can be inferred from the main frame // SiteInstance. Note that Iframes have to pass COEP tests in // |OnResponseStarted| before being loaded and inheriting this // cross-origin isolated state. + // + // TODO(crbug.com/1206150): This may change as we work out the model for + // isolation mechanisms beyond "cross-origin isolation". SiteInstanceImpl* main_frame_site_instance = render_frame_host_->GetMainFrame()->GetSiteInstance(); - return main_frame_site_instance->GetCoopCoepCrossOriginIsolatedInfo(); + return main_frame_site_instance->GetWebExposedIsolationInfo(); } } - return CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated(); + return WebExposedIsolationInfo::CreateNonIsolated(); } scoped_refptr<SiteInstance> @@ -2896,11 +2898,11 @@ bool is_reload = NavigationTypeUtils::IsReload(request->common_params().navigation_type); - CoopCoepCrossOriginIsolatedInfo cross_origin_isolated_info = - GetCoopCoepCrossOriginIsolationInfo(request); + WebExposedIsolationInfo web_exposed_isolation_info = + GetWebExposedIsolationInfo(request); scoped_refptr<SiteInstance> dest_site_instance = GetSiteInstanceForNavigation( - request->GetUrlInfo(), cross_origin_isolated_info, + request->GetUrlInfo(), web_exposed_isolation_info, request->GetSourceSiteInstance(), request->dest_site_instance(), candidate_site_instance, request->common_params().transition, request->state() >= NavigationRequest::CANCELING, is_reload,
diff --git a/content/browser/renderer_host/render_frame_host_manager.h b/content/browser/renderer_host/render_frame_host_manager.h index f4ff686..857e5b9 100644 --- a/content/browser/renderer_host/render_frame_host_manager.h +++ b/content/browser/renderer_host/render_frame_host_manager.h
@@ -18,11 +18,11 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/optional.h" -#include "content/browser/coop_coep_cross_origin_isolated_info.h" #include "content/browser/renderer_host/back_forward_cache_impl.h" #include "content/browser/renderer_host/render_frame_host_impl.h" #include "content/browser/renderer_host/should_swap_browsing_instance.h" #include "content/browser/site_instance_impl.h" +#include "content/browser/web_exposed_isolation_info.h" #include "content/common/content_export.h" #include "content/public/browser/global_request_id.h" #include "content/public/common/referrer.h" @@ -546,9 +546,10 @@ attach_to_inner_delegate_state_ = AttachToInnerDelegateState::ATTACHED; } - // Computes the COOP/COEP information based on the |navigation_request| - // and current |frame_tree_node_| & |render_frame_host_| info. - CoopCoepCrossOriginIsolatedInfo GetCoopCoepCrossOriginIsolationInfo( + // Computes the web-exposed isolation information based on the + // |navigation_request| and current |frame_tree_node_| & |render_frame_host_| + // info. + WebExposedIsolationInfo GetWebExposedIsolationInfo( NavigationRequest* navigation_request); Delegate* delegate() { return delegate_; } @@ -599,13 +600,13 @@ explicit SiteInstanceDescriptor(content::SiteInstance* site_instance) : existing_site_instance(site_instance), relation(SiteInstanceRelation::PREEXISTING), - cross_origin_isolated_info( - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated()) {} + web_exposed_isolation_info( + WebExposedIsolationInfo::CreateNonIsolated()) {} SiteInstanceDescriptor( UrlInfo dest_url_info, SiteInstanceRelation relation_to_current, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info); + const WebExposedIsolationInfo& web_exposed_isolation_info); // Set with an existing SiteInstance to be reused. content::SiteInstance* existing_site_instance; @@ -617,13 +618,12 @@ // This is PREEXISTING iff |existing_site_instance| is defined. SiteInstanceRelation relation; - // A cross-origin isolated page has its top level frame - // cross-origin-opener-policy set to "same-origin" and - // cross-origin-embedder-policy set to "require-corp". - // This allows the use of more powerful features such as SharedArrayBuffer. - // A cross-origin isolated SiteInstance hosts such pages and should only - // live in cross-origin isolated BrowsingInstances. - CoopCoepCrossOriginIsolatedInfo cross_origin_isolated_info; + // Pages may choose to isolate themselves more strongly than the web's + // default, thus allowing access to APIs that would be difficult to + // safely expose otherwise. "Cross-origin isolation", for example, requires + // assertion of a Cross-Origin-Opener-Policy and + // Cross-Origin-Embedder-Policy, and unlocks `SharedArrayBuffer`. + WebExposedIsolationInfo web_exposed_isolation_info; }; // Create a RenderFrameProxyHost owned by this object. @@ -665,7 +665,7 @@ SiteInstanceImpl* current_instance, SiteInstance* destination_instance, const UrlInfo& destination_url_info, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info, + const WebExposedIsolationInfo& web_exposed_isolation_info, bool destination_is_view_source_mode, ui::PageTransition transition, bool is_failure, @@ -678,7 +678,7 @@ ShouldSwapBrowsingInstance ShouldProactivelySwapBrowsingInstance( const UrlInfo& destination_url_info, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info, + const WebExposedIsolationInfo& web_exposed_isolation_info, bool is_reload, bool should_replace_current_entry); @@ -687,7 +687,7 @@ // This is a helper function for GetSiteInstanceForNavigationRequest. scoped_refptr<SiteInstance> GetSiteInstanceForNavigation( const UrlInfo& dest_url_info, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info, + const WebExposedIsolationInfo& web_exposed_isolation_info, SiteInstanceImpl* source_instance, SiteInstanceImpl* dest_instance, SiteInstanceImpl* candidate_instance, @@ -708,9 +708,8 @@ // SiteInstance. The actual SiteInstance can then be obtained calling // ConvertToSiteInstance with the descriptor. // - // |cross_origin_isolated_info| reflects the cross-origin isolation - // information we got from the response for |dest_url|, more specifically the - // COOP and COEP headers. + // |web_exposed_isolation_info| reflects the web-exposed isolation + // information we got from the response for |dest_url|. // // |source_instance| is the SiteInstance of the frame that initiated the // navigation. |current_instance| is the SiteInstance of the frame that is @@ -728,7 +727,7 @@ // This is a helper function for GetSiteInstanceForNavigation. SiteInstanceDescriptor DetermineSiteInstanceForURL( const UrlInfo& dest_url_info, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info, + const WebExposedIsolationInfo& web_exposed_isolation_info, SiteInstance* source_instance, SiteInstance* current_instance, SiteInstance* dest_instance, @@ -768,7 +767,7 @@ SiteInstance* source_instance, bool was_server_redirect, bool is_failure, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info, + const WebExposedIsolationInfo& web_exposed_isolation_info, bool is_speculative); // Converts a SiteInstanceDescriptor to the actual SiteInstance it describes. @@ -788,7 +787,7 @@ bool IsCandidateSameSite( RenderFrameHostImpl* candidate, const UrlInfo& dest_url_info, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info); + const WebExposedIsolationInfo& web_exposed_isolation_info); // Ensure that we have created all needed proxies for a new RFH with // SiteInstance |new_instance|: (1) create swapped-out RVHs and proxies for
diff --git a/content/browser/renderer_host/render_frame_host_manager_browsertest.cc b/content/browser/renderer_host/render_frame_host_manager_browsertest.cc index ea4dd62..9de6b99 100644 --- a/content/browser/renderer_host/render_frame_host_manager_browsertest.cc +++ b/content/browser/renderer_host/render_frame_host_manager_browsertest.cc
@@ -8483,10 +8483,9 @@ EXPECT_NE(process1, process2); EXPECT_EQ(GURL("http://foo.com"), web_contents->GetMainFrame()->GetSiteInstance()->GetSiteURL()); - EXPECT_EQ(ProcessLock( - SiteInfo(GURL("http://foo.com"), GURL("http://foo.com"), - false /* is_origin_keyed */, - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated())), + EXPECT_EQ(ProcessLock(SiteInfo(GURL("http://foo.com"), GURL("http://foo.com"), + false /* is_origin_keyed */, + WebExposedIsolationInfo::CreateNonIsolated())), policy->GetProcessLock(process2->GetID())); // Ensure also that the foo.com process didn't change midway through the
diff --git a/content/browser/renderer_host/render_process_host_impl.cc b/content/browser/renderer_host/render_process_host_impl.cc index 805f772e..a1382e2 100644 --- a/content/browser/renderer_host/render_process_host_impl.cc +++ b/content/browser/renderer_host/render_process_host_impl.cc
@@ -3084,7 +3084,10 @@ return; GetRendererInterface()->SetIsCrossOriginIsolated( - process_lock.coop_coep_cross_origin_isolated_info().is_isolated()); + process_lock.web_exposed_isolation_info().is_isolated()); + + GetRendererInterface()->SetIsDirectSocketEnabled( + process_lock.web_exposed_isolation_info().is_isolated_application()); if (!process_lock.IsASiteOrOrigin()) return; @@ -4026,11 +4029,10 @@ return false; } else { // Even when this process is not locked to a site, it is still associated - // with a particular COOP/COEP configuration. Ensure that it cannot be - // reused for destinations with incompatible COOP/COEP requirements. + // with a particular isolation configuration. Ensure that it cannot be + // reused for destinations with incompatible isolation requirements. if (process_lock.allows_any_site() && - !process_lock.IsCompatibleWithCoopCoepCrossOriginIsolation( - site_info)) { + !process_lock.IsCompatibleWithWebExposedIsolation(site_info)) { return false; }
diff --git a/content/browser/renderer_host/render_process_host_unittest.cc b/content/browser/renderer_host/render_process_host_unittest.cc index 817610a5..03c627e7 100644 --- a/content/browser/renderer_host/render_process_host_unittest.cc +++ b/content/browser/renderer_host/render_process_host_unittest.cc
@@ -207,7 +207,7 @@ scoped_refptr<SiteInstanceImpl> sw_site_instance1 = SiteInstanceImpl::CreateForServiceWorker( browser_context(), kUrl, - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated()); + WebExposedIsolationInfo::CreateNonIsolated()); RenderProcessHost* sw_host1 = sw_site_instance1->GetProcess(); EXPECT_EQ(SiteInstanceProcessAssignment::CREATED_NEW_PROCESS, sw_site_instance1->GetLastProcessAssignmentOutcome()); @@ -218,7 +218,7 @@ scoped_refptr<SiteInstanceImpl> sw_site_instance2 = SiteInstanceImpl::CreateForServiceWorker( browser_context(), kUrl, - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated()); + WebExposedIsolationInfo::CreateNonIsolated()); RenderProcessHost* sw_host2 = sw_site_instance2->GetProcess(); EXPECT_NE(sw_host1, sw_host2); EXPECT_EQ(SiteInstanceProcessAssignment::CREATED_NEW_PROCESS, @@ -271,7 +271,7 @@ scoped_refptr<SiteInstanceImpl> sw_site_instance = SiteInstanceImpl::CreateForServiceWorker( browser_context(), kUrl, - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated()); + WebExposedIsolationInfo::CreateNonIsolated()); RenderProcessHost* sw_host = sw_site_instance->GetProcess(); EXPECT_EQ(SiteInstanceProcessAssignment::CREATED_NEW_PROCESS, sw_site_instance->GetLastProcessAssignmentOutcome()); @@ -306,8 +306,7 @@ // Gets a RenderProcessHost for a service worker. scoped_refptr<SiteInstanceImpl> sw_site_instance1 = SiteInstanceImpl::CreateForServiceWorker( - browser_context(), kUrl, - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated(), + browser_context(), kUrl, WebExposedIsolationInfo::CreateNonIsolated(), /* can_reuse_process */ true); RenderProcessHost* sw_host1 = sw_site_instance1->GetProcess(); EXPECT_EQ(SiteInstanceProcessAssignment::CREATED_NEW_PROCESS, @@ -321,7 +320,7 @@ scoped_refptr<SiteInstanceImpl> sw_site_instance2 = SiteInstanceImpl::CreateForServiceWorker( browser_context(), kUrl, - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated()); + WebExposedIsolationInfo::CreateNonIsolated()); RenderProcessHost* sw_host2 = sw_site_instance2->GetProcess(); EXPECT_NE(sw_host1, sw_host2); EXPECT_EQ(SiteInstanceProcessAssignment::CREATED_NEW_PROCESS, @@ -332,8 +331,7 @@ // unmatched service worker's process (i.e., sw_host2). scoped_refptr<SiteInstanceImpl> sw_site_instance3 = SiteInstanceImpl::CreateForServiceWorker( - browser_context(), kUrl, - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated(), + browser_context(), kUrl, WebExposedIsolationInfo::CreateNonIsolated(), /* can_reuse_process */ true); RenderProcessHost* sw_host3 = sw_site_instance3->GetProcess(); EXPECT_EQ(sw_host2, sw_host3); @@ -347,8 +345,7 @@ // workers in that process. scoped_refptr<SiteInstanceImpl> sw_site_instance4 = SiteInstanceImpl::CreateForServiceWorker( - browser_context(), kUrl, - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated(), + browser_context(), kUrl, WebExposedIsolationInfo::CreateNonIsolated(), /* can_reuse_process */ true); RenderProcessHost* sw_host4 = sw_site_instance4->GetProcess(); EXPECT_EQ(sw_host2, sw_host4); @@ -382,7 +379,7 @@ scoped_refptr<SiteInstanceImpl> sw_site_instance1 = SiteInstanceImpl::CreateForServiceWorker( browser_context(), kUrl, - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated()); + WebExposedIsolationInfo::CreateNonIsolated()); RenderProcessHost* sw_host1 = sw_site_instance1->GetProcess(); EXPECT_EQ(SiteInstanceProcessAssignment::CREATED_NEW_PROCESS, sw_site_instance1->GetLastProcessAssignmentOutcome()); @@ -392,7 +389,7 @@ scoped_refptr<SiteInstanceImpl> sw_site_instance2 = SiteInstanceImpl::CreateForServiceWorker( browser_context(), kUrl, - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated()); + WebExposedIsolationInfo::CreateNonIsolated()); RenderProcessHost* sw_host2 = sw_site_instance2->GetProcess(); EXPECT_EQ(sw_host1, sw_host2); EXPECT_EQ(SiteInstanceProcessAssignment::REUSED_EXISTING_PROCESS, @@ -423,7 +420,7 @@ scoped_refptr<SiteInstanceImpl> sw_site_instance1 = SiteInstanceImpl::CreateForServiceWorker( browser_context(), kUrl1, - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated()); + WebExposedIsolationInfo::CreateNonIsolated()); RenderProcessHost* sw_host1 = sw_site_instance1->GetProcess(); EXPECT_EQ(SiteInstanceProcessAssignment::CREATED_NEW_PROCESS, sw_site_instance1->GetLastProcessAssignmentOutcome()); @@ -896,7 +893,7 @@ scoped_refptr<SiteInstanceImpl> sw_site_instance = SiteInstanceImpl::CreateForServiceWorker( browser_context(), kUrl, - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated()); + WebExposedIsolationInfo::CreateNonIsolated()); RenderProcessHost* sw_process = sw_site_instance->GetProcess(); // Change foo.com SiteInstances to use a different StoragePartition.
diff --git a/content/browser/service_worker/service_worker_browsertest.cc b/content/browser/service_worker/service_worker_browsertest.cc index 0cb3d2c..4ed67de8 100644 --- a/content/browser/service_worker/service_worker_browsertest.cc +++ b/content/browser/service_worker/service_worker_browsertest.cc
@@ -3177,12 +3177,10 @@ ChildProcessSecurityPolicyImpl::GetInstance()->GetProcessLock( running_info.render_process_id); if (base::FeatureList::IsEnabled(features::kPlzServiceWorker)) { - EXPECT_EQ( - IsServiceWorkerCrossOriginIsolated(), - process_lock.coop_coep_cross_origin_isolated_info().is_isolated()); + EXPECT_EQ(IsServiceWorkerCrossOriginIsolated(), + process_lock.web_exposed_isolation_info().is_isolated()); } else { - EXPECT_FALSE( - process_lock.coop_coep_cross_origin_isolated_info().is_isolated()); + EXPECT_FALSE(process_lock.web_exposed_isolation_info().is_isolated()); } } @@ -3238,7 +3236,7 @@ ChildProcessSecurityPolicyImpl::GetInstance()->GetProcessLock( running_info.render_process_id); EXPECT_EQ(IsServiceWorkerCrossOriginIsolated(), - process_lock.coop_coep_cross_origin_isolated_info().is_isolated()); + process_lock.web_exposed_isolation_info().is_isolated()); } INSTANTIATE_TEST_SUITE_P(All,
diff --git a/content/browser/service_worker/service_worker_process_manager.cc b/content/browser/service_worker/service_worker_process_manager.cc index 8b1a392..c8dc0d6a 100644 --- a/content/browser/service_worker/service_worker_process_manager.cc +++ b/content/browser/service_worker/service_worker_process_manager.cc
@@ -131,9 +131,9 @@ SiteInstanceImpl::CreateForServiceWorker( browser_context_, service_worker_url, is_coop_coep_cross_origin_isolated - ? CoopCoepCrossOriginIsolatedInfo::CreateIsolated( + ? WebExposedIsolationInfo::CreateIsolated( url::Origin::Create(service_worker_url)) - : CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated(), + : WebExposedIsolationInfo::CreateNonIsolated(), can_use_existing_process, is_guest); // Get the process from the SiteInstance.
diff --git a/content/browser/site_instance_impl.cc b/content/browser/site_instance_impl.cc index b0e1ce5..ddf7978 100644 --- a/content/browser/site_instance_impl.cc +++ b/content/browser/site_instance_impl.cc
@@ -108,18 +108,18 @@ // static SiteInfo SiteInfo::CreateForErrorPage( - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info) { + const WebExposedIsolationInfo& web_exposed_isolation_info) { return SiteInfo(GetErrorPageSiteAndLockURL(), GetErrorPageSiteAndLockURL(), - false /* is_origin_keyed */, cross_origin_isolated_info, + false /* is_origin_keyed */, web_exposed_isolation_info, false /* is_guest */); } // static SiteInfo SiteInfo::CreateForDefaultSiteInstance( - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info) { + const WebExposedIsolationInfo& web_exposed_isolation_info) { return SiteInfo(SiteInstanceImpl::GetDefaultSiteURL(), SiteInstanceImpl::GetDefaultSiteURL(), - false /* is_origin_keyed */, cross_origin_isolated_info, + false /* is_origin_keyed */, web_exposed_isolation_info, false /* is_guest */); } @@ -130,7 +130,7 @@ // do for user provided URLs. Callers expect GetSiteURL() to return the // value they provide in |guest_site_url|. return SiteInfo(guest_site_url, guest_site_url, false /* is_origin_keyed */, - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated(), + WebExposedIsolationInfo::CreateNonIsolated(), true /* is_guest */); } @@ -138,11 +138,11 @@ SiteInfo SiteInfo::Create( const IsolationContext& isolation_context, const UrlInfo& url_info, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info) { + const WebExposedIsolationInfo& web_exposed_isolation_info) { // The call to GetSiteForURL() below is only allowed on the UI thread, due to // its possible use of effective urls. DCHECK_CURRENTLY_ON(BrowserThread::UI); - return CreateInternal(isolation_context, url_info, cross_origin_isolated_info, + return CreateInternal(isolation_context, url_info, web_exposed_isolation_info, /*compute_site_url=*/true); } @@ -150,9 +150,9 @@ SiteInfo SiteInfo::CreateOnIOThread( const IsolationContext& isolation_context, const UrlInfo& url_info, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info) { + const WebExposedIsolationInfo& web_exposed_isolation_info) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - return CreateInternal(isolation_context, url_info, cross_origin_isolated_info, + return CreateInternal(isolation_context, url_info, web_exposed_isolation_info, /*compute_site_url=*/false); } @@ -160,10 +160,10 @@ SiteInfo SiteInfo::CreateInternal( const IsolationContext& isolation_context, const UrlInfo& url_info, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info, + const WebExposedIsolationInfo& web_exposed_isolation_info, bool compute_site_url) { if (url_info.url.SchemeIs(kChromeErrorScheme)) - return CreateForErrorPage(cross_origin_isolated_info); + return CreateForErrorPage(web_exposed_isolation_info); GURL lock_url = DetermineProcessLockURL(isolation_context, url_info); GURL site_url = lock_url; @@ -184,7 +184,7 @@ url_info.requests_coop_isolation(); return SiteInfo(site_url, lock_url, is_origin_keyed, - cross_origin_isolated_info, false /* is_guest */, + web_exposed_isolation_info, false /* is_guest */, does_site_request_dedicated_process_for_coop); } @@ -192,7 +192,7 @@ SiteInfo SiteInfo::CreateForTesting(const IsolationContext& isolation_context, const GURL& url) { return Create(isolation_context, UrlInfo::CreateForTesting(url), - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated()); + WebExposedIsolationInfo::CreateNonIsolated()); } SiteInfo::SiteInfo() = default; @@ -200,17 +200,16 @@ SiteInfo::~SiteInfo() = default; -SiteInfo::SiteInfo( - const GURL& site_url, - const GURL& process_lock_url, - bool is_origin_keyed, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info, - bool is_guest, - bool does_site_request_dedicated_process_for_coop) +SiteInfo::SiteInfo(const GURL& site_url, + const GURL& process_lock_url, + bool is_origin_keyed, + const WebExposedIsolationInfo& web_exposed_isolation_info, + bool is_guest, + bool does_site_request_dedicated_process_for_coop) : site_url_(site_url), process_lock_url_(process_lock_url), is_origin_keyed_(is_origin_keyed), - coop_coep_cross_origin_isolated_info_(cross_origin_isolated_info), + web_exposed_isolation_info_(web_exposed_isolation_info), is_guest_(is_guest), does_site_request_dedicated_process_for_coop_( does_site_request_dedicated_process_for_coop) {} @@ -226,8 +225,7 @@ return std::tie(site_info.site_url_.possibly_invalid_spec(), site_info.process_lock_url_.possibly_invalid_spec(), site_info.is_origin_keyed_, - site_info.coop_coep_cross_origin_isolated_info_, - site_info.is_guest_); + site_info.web_exposed_isolation_info_, site_info.is_guest_); } SiteInfo& SiteInfo::operator=(const SiteInfo& rhs) = default; @@ -237,14 +235,14 @@ } bool SiteInfo::IsExactMatch(const SiteInfo& other) const { - bool is_match = site_url_ == other.site_url_ && - process_lock_url_ == other.process_lock_url_ && - is_origin_keyed_ == other.is_origin_keyed_ && - coop_coep_cross_origin_isolated_info_ == - other.coop_coep_cross_origin_isolated_info_ && - is_guest_ == other.is_guest_ && - does_site_request_dedicated_process_for_coop_ == - other.does_site_request_dedicated_process_for_coop_; + bool is_match = + site_url_ == other.site_url_ && + process_lock_url_ == other.process_lock_url_ && + is_origin_keyed_ == other.is_origin_keyed_ && + web_exposed_isolation_info_ == other.web_exposed_isolation_info_ && + is_guest_ == other.is_guest_ && + does_site_request_dedicated_process_for_coop_ == + other.does_site_request_dedicated_process_for_coop_; if (is_match) { // If all the fields match, then the "same principal" subset must also @@ -279,11 +277,12 @@ if (is_origin_keyed_) debug_string += ", origin-keyed"; - if (coop_coep_cross_origin_isolated_info_.is_isolated()) { + if (web_exposed_isolation_info_.is_isolated()) { debug_string += ", cross-origin isolated"; - debug_string += - ", coi-origin='" + - coop_coep_cross_origin_isolated_info_.origin().GetDebugString() + "'"; + if (web_exposed_isolation_info_.is_isolated_application()) + debug_string += " application"; + debug_string += ", coi-origin='" + + web_exposed_isolation_info_.origin().GetDebugString() + "'"; } if (is_guest_) @@ -661,18 +660,18 @@ BrowserContext* browser_context) { DCHECK(browser_context); return base::WrapRefCounted(new SiteInstanceImpl(new BrowsingInstance( - browser_context, CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated()))); + browser_context, WebExposedIsolationInfo::CreateNonIsolated()))); } // static scoped_refptr<SiteInstanceImpl> SiteInstanceImpl::CreateForUrlInfo( BrowserContext* browser_context, const UrlInfo& url_info, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info) { + const WebExposedIsolationInfo& web_exposed_isolation_info) { DCHECK(browser_context); // This will create a new SiteInstance and BrowsingInstance. scoped_refptr<BrowsingInstance> instance( - new BrowsingInstance(browser_context, cross_origin_isolated_info)); + new BrowsingInstance(browser_context, web_exposed_isolation_info)); // Note: The |allow_default_instance| value used here MUST match the value // used in DoesSiteForURLMatch(). @@ -684,7 +683,7 @@ scoped_refptr<SiteInstanceImpl> SiteInstanceImpl::CreateForServiceWorker( BrowserContext* browser_context, const GURL& url, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info, + const WebExposedIsolationInfo& web_exposed_isolation_info, bool can_reuse_process, bool is_guest) { DCHECK(!url.SchemeIs(kChromeErrorScheme)); @@ -695,7 +694,7 @@ } else { // This will create a new SiteInstance and BrowsingInstance. scoped_refptr<BrowsingInstance> instance( - new BrowsingInstance(browser_context, cross_origin_isolated_info)); + new BrowsingInstance(browser_context, web_exposed_isolation_info)); // We do NOT want to allow the default site instance here because workers // need to be kept separate from other sites. @@ -730,8 +729,7 @@ auto guest_site_info = SiteInfo::CreateForGuest(guest_site_url); scoped_refptr<SiteInstanceImpl> site_instance = base::WrapRefCounted(new SiteInstanceImpl(new BrowsingInstance( - browser_context, - guest_site_info.coop_coep_cross_origin_isolated_info()))); + browser_context, guest_site_info.web_exposed_isolation_info()))); site_instance->SetSiteInfoInternal(guest_site_info); @@ -746,7 +744,7 @@ DCHECK(browser_context); // This will create a new SiteInstance and BrowsingInstance. scoped_refptr<BrowsingInstance> instance(new BrowsingInstance( - browser_context, CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated())); + browser_context, WebExposedIsolationInfo::CreateNonIsolated())); auto site_instance = instance->GetSiteInstanceForURL( UrlInfo(url, UrlInfo::OriginIsolationRequest::kNone), /* allow_default_instance */ false); @@ -762,7 +760,7 @@ DCHECK(browser_context); return SiteInstanceImpl::CreateForUrlInfo( browser_context, UrlInfo::CreateForTesting(url), - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated()); + WebExposedIsolationInfo::CreateNonIsolated()); } // static @@ -973,14 +971,14 @@ default_site_instance_state_ = std::make_unique<DefaultSiteInstanceState>(); original_url_ = GetDefaultSiteURL(); SetSiteInfoInternal(SiteInfo::CreateForDefaultSiteInstance( - browsing_instance_->coop_coep_cross_origin_isolated_info())); + browsing_instance_->web_exposed_isolation_info())); } void SiteInstanceImpl::SetSiteInfoInternal(const SiteInfo& site_info) { // TODO(acolwell): Add logic to validate |site_url| and |lock_url| are valid. DCHECK(!has_site_); - CHECK_EQ(site_info.coop_coep_cross_origin_isolated_info(), - browsing_instance_->coop_coep_cross_origin_isolated_info()); + CHECK_EQ(site_info.web_exposed_isolation_info(), + browsing_instance_->web_exposed_isolation_info()); if (verify_storage_partition_info_) { auto* browser_context = browsing_instance_->GetBrowserContext(); @@ -1066,8 +1064,8 @@ DCHECK(!has_site_); if (!browsing_instance_->HasDefaultSiteInstance()) { - const SiteInfo site_info = SiteInfo::Create( - GetIsolationContext(), url_info, GetCoopCoepCrossOriginIsolatedInfo()); + const SiteInfo site_info = SiteInfo::Create(GetIsolationContext(), url_info, + GetWebExposedIsolationInfo()); if (CanBePlacedInDefaultSiteInstance(GetIsolationContext(), url_info.url, site_info)) { SetSiteInfoToDefault(); @@ -1121,7 +1119,7 @@ } return SiteInfo::Create(GetIsolationContext(), url_info, - GetCoopCoepCrossOriginIsolatedInfo()); + GetWebExposedIsolationInfo()); } const ProcessLock SiteInstanceImpl::GetProcessLock() const { @@ -1288,7 +1286,7 @@ DCHECK(browser_context); return SiteInstanceImpl::CreateForUrlInfo( browser_context, UrlInfo(url, UrlInfo::OriginIsolationRequest::kNone), - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated()); + WebExposedIsolationInfo::CreateNonIsolated()); } // static @@ -1325,7 +1323,7 @@ // that should be routed to the default SiteInstance. DCHECK_EQ(site_info_.site_url(), GetDefaultSiteURL()); auto site_info = SiteInfo::Create(GetIsolationContext(), url_info, - GetCoopCoepCrossOriginIsolatedInfo()); + GetWebExposedIsolationInfo()); return CanBePlacedInDefaultSiteInstance(GetIsolationContext(), url, site_info) && !browsing_instance_->HasSiteInstance(site_info); @@ -1577,12 +1575,12 @@ // this method. The code is currently safe because the caller checks to make // sure the COOP/COEP info matches on this object before calling this method. auto site_info = SiteInfo::Create(GetIsolationContext(), url_info, - GetCoopCoepCrossOriginIsolatedInfo()); + GetWebExposedIsolationInfo()); if (kCreateForURLAllowsDefaultSiteInstance && CanBePlacedInDefaultSiteInstance(GetIsolationContext(), url_info.url, site_info)) { - site_info = SiteInfo::CreateForDefaultSiteInstance( - GetCoopCoepCrossOriginIsolatedInfo()); + site_info = + SiteInfo::CreateForDefaultSiteInstance(GetWebExposedIsolationInfo()); } return site_info_.IsExactMatch(site_info); @@ -1686,7 +1684,7 @@ // https://crbug.com/1135539. if (process_lock.is_invalid()) { auto new_process_lock = - ProcessLock::CreateAllowAnySite(GetCoopCoepCrossOriginIsolatedInfo()); + ProcessLock::CreateAllowAnySite(GetWebExposedIsolationInfo()); process_->SetProcessLock(GetIsolationContext(), new_process_lock); } else { CHECK(process_lock.allows_any_site()) @@ -1750,7 +1748,7 @@ // Update the process lock state to signal that the process has been // associated with a SiteInstance that is not locked to a site yet. auto new_process_lock = - ProcessLock::CreateAllowAnySite(GetCoopCoepCrossOriginIsolatedInfo()); + ProcessLock::CreateAllowAnySite(GetWebExposedIsolationInfo()); process_->SetProcessLock(GetIsolationContext(), new_process_lock); } else { CHECK(process_lock.allows_any_site()) @@ -1765,13 +1763,13 @@ policy->IncludeIsolationContext(process_->GetID(), GetIsolationContext()); } -const CoopCoepCrossOriginIsolatedInfo& -SiteInstanceImpl::GetCoopCoepCrossOriginIsolatedInfo() const { - return browsing_instance_->coop_coep_cross_origin_isolated_info(); +const WebExposedIsolationInfo& SiteInstanceImpl::GetWebExposedIsolationInfo() + const { + return browsing_instance_->web_exposed_isolation_info(); } -bool SiteInstanceImpl::IsCoopCoepCrossOriginIsolated() const { - return GetCoopCoepCrossOriginIsolatedInfo().is_isolated(); +bool SiteInstanceImpl::IsCrossOriginIsolated() const { + return GetWebExposedIsolationInfo().is_isolated(); } // static
diff --git a/content/browser/site_instance_impl.h b/content/browser/site_instance_impl.h index 2108cdf1..1b21a56 100644 --- a/content/browser/site_instance_impl.h +++ b/content/browser/site_instance_impl.h
@@ -9,8 +9,8 @@ #include <stdint.h> #include "base/observer_list.h" -#include "content/browser/coop_coep_cross_origin_isolated_info.h" #include "content/browser/isolation_context.h" +#include "content/browser/web_exposed_isolation_info.h" #include "content/common/content_export.h" #include "content/public/browser/render_process_host_observer.h" #include "content/public/browser/site_instance.h" @@ -141,9 +141,9 @@ class CONTENT_EXPORT SiteInfo { public: static SiteInfo CreateForErrorPage( - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info); + const WebExposedIsolationInfo& web_exposed_isolation_info); static SiteInfo CreateForDefaultSiteInstance( - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info); + const WebExposedIsolationInfo& web_exposed_isolation_info); static SiteInfo CreateForGuest(const GURL& guest_site_url); // This function returns a SiteInfo with the appropriate site_url and @@ -152,7 +152,7 @@ static SiteInfo Create( const IsolationContext& isolation_context, const UrlInfo& url_info, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info); + const WebExposedIsolationInfo& web_exposed_isolation_info); // Similar to the function above, but this method can only be called on the // IO thread. All fields except for the site_url should be the same as @@ -168,11 +168,11 @@ static SiteInfo CreateOnIOThread( const IsolationContext& isolation_context, const UrlInfo& url_info, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info); + const WebExposedIsolationInfo& web_exposed_isolation_info); // Method to make creating SiteInfo objects for tests easier. It is a thin // wrapper around Create() that uses UrlInfo::CreateForTesting(), - // and CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated() to generate the + // and WebExposedIsolationInfo::CreateNonIsolated() to generate the // information that is not provided. static SiteInfo CreateForTesting(const IsolationContext& isolation_context, const GURL& url); @@ -207,7 +207,7 @@ SiteInfo(const GURL& site_url, const GURL& process_lock_url, bool is_origin_keyed, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info, + const WebExposedIsolationInfo& web_exposed_isolation_info, bool is_guest = false, bool does_site_request_dedicated_process_for_coop = false); SiteInfo(); @@ -258,13 +258,13 @@ // in their site urls. bool is_origin_keyed() const { return is_origin_keyed_; } - // Returns the cross-origin isolation status of pages hosted by the - // SiteInstance. This is deduced from the COOP and COEP headers and has - // implications for which pages can live in this SiteInstance as well as - // process allocation decisions. - const CoopCoepCrossOriginIsolatedInfo& coop_coep_cross_origin_isolated_info() - const { - return coop_coep_cross_origin_isolated_info_; + // Returns the web-exposed isolation status of pages hosted by the + // SiteInstance. The level of isolation which a page opts-into has + // implications for the set of other pages which can live in this + // SiteInstance, process allocation decisions, and API exposure in the page's + // JavaScript context. + const WebExposedIsolationInfo& web_exposed_isolation_info() const { + return web_exposed_isolation_info_; } bool is_guest() const { return is_guest_; } @@ -360,7 +360,7 @@ static SiteInfo CreateInternal( const IsolationContext& isolation_context, const UrlInfo& url_info, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info, + const WebExposedIsolationInfo& web_exposed_isolation_info, bool compute_site_url); // Returns the URL to which a process should be locked for the given UrlInfo. @@ -389,12 +389,13 @@ // isolation. In contrast, the site-level URLs that are typically used in // SiteInfo include subdomains, as do command-line isolated origins. bool is_origin_keyed_ = false; - // Indicates the cross-origin isolation status of pages hosted by the - // SiteInstance. This is deduced from the COOP and COEP headers and has - // implications for which pages can live in this SiteInstance as well as - // process allocation decisions. - CoopCoepCrossOriginIsolatedInfo coop_coep_cross_origin_isolated_info_ = - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated(); + // Indicates the web-exposed isolation status of pages hosted by the + // SiteInstance. The level of isolation which a page opts-into has + // implications for the set of other pages which can live in this + // SiteInstance, process allocation decisions, and API exposure in the page's + // JavaScript context. + WebExposedIsolationInfo web_exposed_isolation_info_ = + WebExposedIsolationInfo::CreateNonIsolated(); // Indicates this SiteInfo is for a <webview> guest. bool is_guest_ = false; @@ -435,15 +436,15 @@ BrowserContext* browser_context); // |url_info| contains the GURL for which we want to create a SiteInstance, // along with other state relevant to making process allocation decisions. - // |cross_origin_isolated_info| is not exposed in content/public. It - // sets the BrowsingInstance coop_coep_cross_origin_isolated_info_ property. + // |web_exposed_isolation_info| is not exposed in content/public. It + // sets the BrowsingInstance web_exposed_isolation_info_ property. // Once this property is set it cannot be changed and is used in process // allocation decisions. - // TODO(wjmaclean): absorb |coop_coep_cross_origin_info| into UrlInfo. + // TODO(wjmaclean): absorb |web_exposed_isolation_info| into UrlInfo. static scoped_refptr<SiteInstanceImpl> CreateForUrlInfo( BrowserContext* browser_context, const UrlInfo& url_info, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info); + const WebExposedIsolationInfo& web_exposed_isolation_info); static scoped_refptr<SiteInstanceImpl> CreateForGuest( content::BrowserContext* browser_context, const GURL& guest_site_url); @@ -453,17 +454,16 @@ // The <webview> guest site URL if |is_guest| is true. // |can_reuse_process| - Set to true if the new SiteInstance can use the // same process as the renderer for |url|. - // |cross_origin_isolated_info| - Indicates the cross-origin isolation state - // of the main script. ServiceWorkers are - // considered cross-origin Isolated if their - // Cross-Origin-Embedder-Policy header is set - // to "same-origin". + // |web_exposed_isolation_info| - Indicates the web-exposed isolation state + // of the main script (note that ServiceWorker + // "cross-origin isolation" does not require + // Cross-Origin-Opener-Policy to be set). // |is_guest| - Set to true if the new SiteInstance is for a <webview> // guest. static scoped_refptr<SiteInstanceImpl> CreateForServiceWorker( BrowserContext* browser_context, const GURL& url, - const CoopCoepCrossOriginIsolatedInfo& cross_origin_isolated_info, + const WebExposedIsolationInfo& web_exposed_isolation_info, bool can_reuse_process = false, bool is_guest = false); @@ -769,14 +769,13 @@ // RenderProcessHost (with a new ID). AgentSchedulingGroupHost& GetAgentSchedulingGroup(); - // Returns the cross-origin isolation status of the BrowsingInstance this + // Returns the web-exposed isolation status of the BrowsingInstance this // SiteInstance is part of. - const CoopCoepCrossOriginIsolatedInfo& GetCoopCoepCrossOriginIsolatedInfo() - const; + const WebExposedIsolationInfo& GetWebExposedIsolationInfo() const; // Simple helper function that returns the is_isolated property of the - // CoopCoepCrossOriginIsolatedInfo of this BrowsingInstance. - bool IsCoopCoepCrossOriginIsolated() const; + // WebExposedIsolationInfo of this BrowsingInstance. + bool IsCrossOriginIsolated() const; private: friend class BrowsingInstance;
diff --git a/content/browser/site_instance_impl_unittest.cc b/content/browser/site_instance_impl_unittest.cc index a75f902..f267a2c 100644 --- a/content/browser/site_instance_impl_unittest.cc +++ b/content/browser/site_instance_impl_unittest.cc
@@ -63,7 +63,7 @@ bool is_origin_keyed) { return SiteInfo(GURL("https://www.foo.com"), process_lock_url, is_origin_keyed, - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated()); + WebExposedIsolationInfo::CreateNonIsolated()); } } // namespace @@ -126,7 +126,7 @@ return SiteInfo::Create( isolation_context, UrlInfo(url, UrlInfo::OriginIsolationRequest::kNone), - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated()) + WebExposedIsolationInfo::CreateNonIsolated()) .site_url(); } @@ -267,13 +267,12 @@ // Check that SiteInfos with differing values of // `does_site_request_dedicated_process_for_coop_` are still considered // same-principal. - auto site_info_1_with_isolation_request = - SiteInfo(GURL("https://www.foo.com") /* site_url */, - GURL("https://foo.com") /* process_lock_url */, - false /* is_origin_keyed */, - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated(), - false /* is_guest */, - true /* does_site_request_dedicated_process_for_coop */); + auto site_info_1_with_isolation_request = SiteInfo( + GURL("https://www.foo.com") /* site_url */, + GURL("https://foo.com") /* process_lock_url */, + false /* is_origin_keyed */, WebExposedIsolationInfo::CreateNonIsolated(), + false /* is_guest */, + true /* does_site_request_dedicated_process_for_coop */); EXPECT_TRUE( site_info_1.IsSamePrincipalWith(site_info_1_with_isolation_request)); EXPECT_EQ(site_info_1, site_info_1_with_isolation_request); @@ -480,7 +479,7 @@ switches::kDisableSiteIsolation); const auto cross_origin_isolation_info = - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated(); + WebExposedIsolationInfo::CreateNonIsolated(); auto site_instance = SiteInstanceImpl::CreateForUrlInfo( &browser_context, UrlInfo::CreateForTesting(GURL("http://foo.com")), cross_origin_isolation_info); @@ -676,7 +675,7 @@ // Error page URLs. auto error_site_info = SiteInfo::CreateForErrorPage( - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated()); + WebExposedIsolationInfo::CreateNonIsolated()); test_url = GURL(kUnreachableWebDataURL); site_url = GetSiteForURL(test_url); EXPECT_EQ(error_site_info.site_url(), site_url); @@ -713,10 +712,10 @@ EXPECT_EQ(app_url, site_info.site_url()); } - SiteInfo expected_site_info( - app_url /* site_url */, nonapp_site_url /* process_lock_url */, - false /* is_origin_keyed */, - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated()); + SiteInfo expected_site_info(app_url /* site_url */, + nonapp_site_url /* process_lock_url */, + false /* is_origin_keyed */, + WebExposedIsolationInfo::CreateNonIsolated()); // New SiteInstance in a new BrowsingInstance with a predetermined URL. { @@ -823,8 +822,7 @@ switches::kProcessPerSite)); std::unique_ptr<TestBrowserContext> browser_context(new TestBrowserContext()); BrowsingInstance* browsing_instance = new BrowsingInstance( - browser_context.get(), - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated()); + browser_context.get(), WebExposedIsolationInfo::CreateNonIsolated()); const GURL url_a1("http://www.google.com/1.html"); scoped_refptr<SiteInstanceImpl> site_instance_a1( @@ -857,8 +855,7 @@ // A visit to the original site in a new BrowsingInstance (same or different // browser context) should return a different SiteInstance. BrowsingInstance* browsing_instance2 = new BrowsingInstance( - browser_context.get(), - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated()); + browser_context.get(), WebExposedIsolationInfo::CreateNonIsolated()); // Ensure the new SiteInstance is ref counted so that it gets deleted. scoped_refptr<SiteInstanceImpl> site_instance_a2_2( browsing_instance2->GetSiteInstanceForURL( @@ -900,8 +897,7 @@ switches::kProcessPerSite); std::unique_ptr<TestBrowserContext> browser_context(new TestBrowserContext()); scoped_refptr<BrowsingInstance> browsing_instance = new BrowsingInstance( - browser_context.get(), - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated()); + browser_context.get(), WebExposedIsolationInfo::CreateNonIsolated()); const GURL url_a1("http://www.google.com/1.html"); scoped_refptr<SiteInstanceImpl> site_instance_a1( @@ -934,8 +930,7 @@ // A visit to the original site in a new BrowsingInstance (same browser // context) should return a different SiteInstance with the same process. BrowsingInstance* browsing_instance2 = new BrowsingInstance( - browser_context.get(), - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated()); + browser_context.get(), WebExposedIsolationInfo::CreateNonIsolated()); scoped_refptr<SiteInstanceImpl> site_instance_a1_2( browsing_instance2->GetSiteInstanceForURL( UrlInfo::CreateForTesting(url_a1), false)); @@ -948,8 +943,7 @@ std::unique_ptr<TestBrowserContext> browser_context2( new TestBrowserContext()); BrowsingInstance* browsing_instance3 = new BrowsingInstance( - browser_context2.get(), - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated()); + browser_context2.get(), WebExposedIsolationInfo::CreateNonIsolated()); scoped_refptr<SiteInstanceImpl> site_instance_a2_3( browsing_instance3->GetSiteInstanceForURL( UrlInfo::CreateForTesting(url_a2), false)); @@ -1514,10 +1508,10 @@ SetBrowserClientForTesting(&modified_client); std::unique_ptr<TestBrowserContext> browser_context(new TestBrowserContext()); - SiteInfo expected_site_info( - app_url /* site_url */, original_url /* process_lock_url */, - false /* is_origin_keyed */, - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated()); + SiteInfo expected_site_info(app_url /* site_url */, + original_url /* process_lock_url */, + false /* is_origin_keyed */, + WebExposedIsolationInfo::CreateNonIsolated()); // New SiteInstance in a new BrowsingInstance with a predetermined URL. In // this and subsequent cases, the site URL should consist of the effective @@ -1561,9 +1555,8 @@ namespace { ProcessLock ProcessLockFromString(const std::string& url) { - return ProcessLock( - SiteInfo(GURL(url), GURL(url), false /* is_origin_keyed */, - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated())); + return ProcessLock(SiteInfo(GURL(url), GURL(url), false /* is_origin_keyed */, + WebExposedIsolationInfo::CreateNonIsolated())); } } // namespace @@ -1866,9 +1859,8 @@ const GURL non_error_page_url("http://foo.com"); const GURL error_page_url(kUnreachableWebDataURL); - const auto non_isolated_coi = - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated(); - const auto isolated_coi = CoopCoepCrossOriginIsolatedInfo::CreateIsolated( + const auto non_isolated_coi = WebExposedIsolationInfo::CreateNonIsolated(); + const auto isolated_coi = WebExposedIsolationInfo::CreateIsolated( url::Origin::Create(non_error_page_url)); const auto non_isolated_error_site_info = @@ -1880,12 +1872,11 @@ // equal, but indicate they are both for error pages. EXPECT_NE(non_isolated_error_site_info, isolated_error_site_info); EXPECT_TRUE(non_isolated_error_site_info.is_error_page()); - EXPECT_EQ( - non_isolated_coi, - non_isolated_error_site_info.coop_coep_cross_origin_isolated_info()); + EXPECT_EQ(non_isolated_coi, + non_isolated_error_site_info.web_exposed_isolation_info()); EXPECT_TRUE(isolated_error_site_info.is_error_page()); EXPECT_EQ(isolated_coi, - isolated_error_site_info.coop_coep_cross_origin_isolated_info()); + isolated_error_site_info.web_exposed_isolation_info()); // Verify that non-error URLs don't generate error page SiteInfos and // non-isolated and isolated SiteInfos do not match even though the URL is @@ -1909,11 +1900,11 @@ EXPECT_EQ(non_isolated_error_site_info, non_isolated_error_instance->GetSiteInfo()); EXPECT_EQ(non_isolated_coi, - non_isolated_error_instance->GetCoopCoepCrossOriginIsolatedInfo()); + non_isolated_error_instance->GetWebExposedIsolationInfo()); EXPECT_EQ(isolated_error_site_info, isolated_error_instance->GetSiteInfo()); EXPECT_EQ(isolated_coi, - isolated_error_instance->GetCoopCoepCrossOriginIsolatedInfo()); + isolated_error_instance->GetWebExposedIsolationInfo()); // Verify that deriving a SiteInfo for an error page URL always returns // an error page SiteInfo with the correct isolation info.
diff --git a/content/browser/web_exposed_isolation_info.cc b/content/browser/web_exposed_isolation_info.cc new file mode 100644 index 0000000..47d1926 --- /dev/null +++ b/content/browser/web_exposed_isolation_info.cc
@@ -0,0 +1,92 @@ +// Copyright 2020 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 "content/browser/web_exposed_isolation_info.h" + +namespace content { + +// static +WebExposedIsolationInfo WebExposedIsolationInfo::CreateNonIsolated() { + return WebExposedIsolationInfo(base::nullopt /* origin */, + false /* isolated_application */); +} + +WebExposedIsolationInfo WebExposedIsolationInfo::CreateIsolated( + const url::Origin& origin) { + return WebExposedIsolationInfo(origin, false /* isolated_application */); +} + +WebExposedIsolationInfo WebExposedIsolationInfo::CreateIsolatedApplication( + const url::Origin& origin) { + return WebExposedIsolationInfo(origin, true /* isolated_application */); +} + +WebExposedIsolationInfo::WebExposedIsolationInfo( + const base::Optional<url::Origin>& origin, + bool isolated_application) + : origin_(origin), isolated_application_(isolated_application) {} + +WebExposedIsolationInfo::WebExposedIsolationInfo( + const WebExposedIsolationInfo& other) = default; + +WebExposedIsolationInfo::~WebExposedIsolationInfo() = default; + +const url::Origin& WebExposedIsolationInfo::origin() const { + DCHECK(is_isolated()) + << "The origin() getter should only be used for " + "WebExposedIsolationInfo's where is_isolated() is true."; + return origin_.value(); +} + +bool WebExposedIsolationInfo::operator==( + const WebExposedIsolationInfo& b) const { + if (is_isolated_application() != b.is_isolated_application()) + return false; + + if (is_isolated() != b.is_isolated()) + return false; + + if (is_isolated() && !(origin_->IsSameOriginWith(b.origin()))) + return false; + + return true; +} + +bool WebExposedIsolationInfo::operator!=( + const WebExposedIsolationInfo& b) const { + return !(operator==(b)); +} + +bool WebExposedIsolationInfo::operator<( + const WebExposedIsolationInfo& b) const { + // Nonisolated < Isolated < Isolated Application. + if (is_isolated_application() != b.is_isolated_application()) + return !is_isolated_application(); + + if (is_isolated() != b.is_isolated()) + return !is_isolated(); + + // Within Isolated and Isolated Application, compare origins: + if (is_isolated()) { + DCHECK(b.is_isolated()); + return origin_.value() < b.origin(); + } + + // Nonisolated == Nonisolated. + DCHECK(!is_isolated() && !b.is_isolated()); + return false; +} + +std::ostream& operator<<(std::ostream& out, + const WebExposedIsolationInfo& info) { + out << "{"; + if (info.is_isolated()) { + out << info.origin(); + if (info.is_isolated_application()) + out << " (application)"; + } + out << "}"; + return out; +} +} // namespace content
diff --git a/content/browser/web_exposed_isolation_info.h b/content/browser/web_exposed_isolation_info.h new file mode 100644 index 0000000..76dcb97 --- /dev/null +++ b/content/browser/web_exposed_isolation_info.h
@@ -0,0 +1,99 @@ +// Copyright 2020 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. + +#ifndef CONTENT_BROWSER_WEB_EXPOSED_ISOLATION_INFO_H_ +#define CONTENT_BROWSER_WEB_EXPOSED_ISOLATION_INFO_H_ + +#include "base/optional.h" +#include "content/common/content_export.h" +#include "url/origin.h" + +namespace content { + +// Represents the isolation level of a page or group of pages. This is used +// for process allocation and to selectively enable powerful features such +// as SharedArrayBuffer and Direct Sockets. +// +// Currently, three levels of isolation are represented: +// +// 1. Non-isolated contexts. +// +// 2. Cross-origin isolation, as defined in +// https://html.spec.whatwg.org/#concept-settings-object-cross-origin-isolated-capability. +// This is computed purely by examining Cross-Origin-Opener-Policy and +// Cross-Origin-Embedder-Policy headers on a given response. +// +// 3. Isolated Application contexts, whose requirements are still being +// fleshed out. +// +// TODO(mkwst): Improve the description of the Isolated Application context as +// we work out what it is: https://crbug.com/1206150. +class CONTENT_EXPORT WebExposedIsolationInfo { + public: + static WebExposedIsolationInfo CreateNonIsolated(); + static WebExposedIsolationInfo CreateIsolated(const url::Origin& origin); + static WebExposedIsolationInfo CreateIsolatedApplication( + const url::Origin& origin); + + WebExposedIsolationInfo(const WebExposedIsolationInfo& other); + ~WebExposedIsolationInfo(); + + // Returns `true` for isolated contexts created via `CreateIsolated()` or + // `CreateIsolatedApplication()`, and false for contexts created via + // `CreateNonIsolated()`. + // + // This corresponds to "cross-origin isolation" as defined in HTML: + // https://html.spec.whatwg.org/multipage/webappapis.html#concept-settings-object-cross-origin-isolated-capability + bool is_isolated() const { return origin_.has_value(); } + + // Returns `true` for contexts created via `CreateIsolatedApplication()`, and + // `false` for those created via `CreateNonIsolated()` or `CreatedIsolated()`. + // + // This corresponds to "application isolation", which is not yet defined, but + // will certainly include a superset of "cross-origin isolation"'s + // requirements. + // + // TODO(crbug.com/1206150): Define and specify these restrictions. + bool is_isolated_application() const { + return origin_.has_value() && isolated_application_; + } + + // Returns the top level origin shared across pages with this cross-origin + // isolation status. This only returns a value if is_isolated is true. + const url::Origin& origin() const; + + bool operator==(const WebExposedIsolationInfo& b) const; + bool operator!=(const WebExposedIsolationInfo& b) const; + + // Non-isolated < Isolated < Isolated Application. + // + // All non-isolated contexts are equivalent. + // + // Origin comparisons determine ordering of isolated contexts. + bool operator<(const WebExposedIsolationInfo& b) const; + + private: + WebExposedIsolationInfo(const base::Optional<url::Origin>& origin, + bool isolated_application); + + // |origin_| serve two purposes. If null, it indicates that the page(s) it + // refers to are not isolated, and that the crossOriginIsolated boolean is + // false. If it has a value, all these page(s) share the same top level + // origin. This ensure we can put them in the same process. + base::Optional<url::Origin> origin_; + + // Some applications may require additional isolation above and beyond what + // COOP/COEP-based COI provides. This boolean will be `true` for applications + // that have opted into such a context. + // + // TODO(mkwst): Improve the description of the Isolated Application context as + // we work out what it is: https://crbug.com/1206150. + bool isolated_application_ = false; +}; + +CONTENT_EXPORT std::ostream& operator<<(std::ostream& out, + const WebExposedIsolationInfo& info); +} // namespace content + +#endif // CONTENT_BROWSER_WEB_EXPOSED_ISOLATION_INFO_H_
diff --git a/content/browser/web_exposed_isolation_info_unittest.cc b/content/browser/web_exposed_isolation_info_unittest.cc new file mode 100644 index 0000000..f70ad5da --- /dev/null +++ b/content/browser/web_exposed_isolation_info_unittest.cc
@@ -0,0 +1,92 @@ +// Copyright 2021 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 "content/browser/web_exposed_isolation_info.h" + +#include "base/test/gtest_util.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "url/origin.h" + +namespace content { + +using WebExposedIsolationInfoTest = testing::Test; + +TEST_F(WebExposedIsolationInfoTest, NonIsolated) { + WebExposedIsolationInfo info = WebExposedIsolationInfo::CreateNonIsolated(); + EXPECT_FALSE(info.is_isolated()); + EXPECT_FALSE(info.is_isolated_application()); + ASSERT_DCHECK_DEATH(info.origin()); +} + +TEST_F(WebExposedIsolationInfoTest, Isolated) { + url::Origin origin = + url::Origin::CreateFromNormalizedTuple("https", "example.com", 443); + WebExposedIsolationInfo info = + WebExposedIsolationInfo::CreateIsolated(origin); + + EXPECT_TRUE(info.is_isolated()); + EXPECT_FALSE(info.is_isolated_application()); + EXPECT_EQ(origin, info.origin()); +} + +TEST_F(WebExposedIsolationInfoTest, IsolatedApplication) { + url::Origin origin = + url::Origin::CreateFromNormalizedTuple("https", "example.com", 443); + WebExposedIsolationInfo info = + WebExposedIsolationInfo::CreateIsolatedApplication(origin); + + EXPECT_TRUE(info.is_isolated()); + EXPECT_TRUE(info.is_isolated_application()); + EXPECT_EQ(origin, info.origin()); +} + +TEST_F(WebExposedIsolationInfoTest, Comparisons) { + WebExposedIsolationInfo nonA = WebExposedIsolationInfo::CreateNonIsolated(); + WebExposedIsolationInfo nonB = WebExposedIsolationInfo::CreateNonIsolated(); + + // All non-isolated COII are equivalennt. + EXPECT_EQ(nonA, nonA); + EXPECT_EQ(nonA, nonB); + EXPECT_EQ(nonB, nonA); + EXPECT_FALSE(nonA < nonB); + EXPECT_FALSE(nonB < nonA); + + url::Origin originA = + url::Origin::CreateFromNormalizedTuple("https", "aaa.example", 443); + url::Origin originB = + url::Origin::CreateFromNormalizedTuple("https", "bbb.example", 443); + WebExposedIsolationInfo isolatedA = + WebExposedIsolationInfo::CreateIsolated(originA); + WebExposedIsolationInfo isolatedB = + WebExposedIsolationInfo::CreateIsolated(originB); + + // Isolated == self. + EXPECT_EQ(isolatedA, isolatedA); + // Non-isolated COII are < isolated COII (note that WebExposedIsolationInfo + // only implements <, so we can't use EXPECT_GT here and below). + EXPECT_LT(nonA, isolatedA); + EXPECT_FALSE(isolatedA < nonA); + // Origin comparison for isolated < isolated + EXPECT_LT(isolatedA, isolatedB); + EXPECT_FALSE(isolatedB < isolatedA); + + WebExposedIsolationInfo appA = + WebExposedIsolationInfo::CreateIsolatedApplication(originA); + WebExposedIsolationInfo appB = + WebExposedIsolationInfo::CreateIsolatedApplication(originB); + + // Isolated app == self. + EXPECT_EQ(appA, appA); + // Non-isolated COII are < isolated app COII. + EXPECT_LT(nonA, appA); + EXPECT_FALSE(appA < nonA); + // Non-isolated COII are < isolated app COII. + EXPECT_LT(isolatedA, appA); + EXPECT_FALSE(appA < isolatedA); + // Origin comparison for isolated app < isolated app + EXPECT_LT(appA, appB); + EXPECT_FALSE(appB < appA); +} + +} // namespace content
diff --git a/content/browser/webauth/authenticator_impl_unittest.cc b/content/browser/webauth/authenticator_impl_unittest.cc index 1836c65..7823b5e 100644 --- a/content/browser/webauth/authenticator_impl_unittest.cc +++ b/content/browser/webauth/authenticator_impl_unittest.cc
@@ -3783,7 +3783,6 @@ } static constexpr char kTestPIN[] = "1234"; -static constexpr char16_t kTestPIN16[] = u"1234"; class UVTestAuthenticatorClientDelegate : public AuthenticatorRequestClientDelegate { @@ -3808,7 +3807,8 @@ *collected_pin_ = true; *min_pin_length_ = options.min_pin_length; base::SequencedTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::BindOnce(std::move(provide_pin_cb), kTestPIN16)); + FROM_HERE, + base::BindOnce(std::move(provide_pin_cb), base::UTF8ToUTF16(kTestPIN))); } void StartBioEnrollment(base::OnceClosure next_callback) override { @@ -3933,7 +3933,7 @@ // the PIN to answer with. struct PINExpectation { PINReason reason; - std::u16string pin; + std::string pin; int attempts; uint32_t min_pin_length = device::kMinPinLength; PINError error = PINError::kNoError; @@ -3969,11 +3969,12 @@ DCHECK_EQ(expected_.front().min_pin_length, options.min_pin_length); DCHECK_EQ(expected_.front().reason, options.reason); DCHECK_EQ(expected_.front().error, options.error); - std::u16string pin = std::move(expected_.front().pin); + std::string pin = std::move(expected_.front().pin); expected_.pop_front(); base::SequencedTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::BindOnce(std::move(provide_pin_cb), std::move(pin))); + FROM_HERE, base::BindOnce(std::move(provide_pin_cb), + base::UTF8ToUTF16(std::move(pin)))); } void FinishCollectToken() override {} @@ -4159,13 +4160,12 @@ case kSetPIN: // A single PIN prompt to set a PIN is expected. - test_client_.expected = {{PINReason::kSet, kTestPIN16}}; + test_client_.expected = {{PINReason::kSet, kTestPIN}}; break; case kUsePIN: // A single PIN prompt to get the PIN is expected. - test_client_.expected = { - {PINReason::kChallenge, kTestPIN16, 8}}; + test_client_.expected = {{PINReason::kChallenge, kTestPIN, 8}}; break; default: @@ -4210,10 +4210,10 @@ virtual_device_factory_->mutable_state()->pin_retries = device::kMaxPinRetries; - test_client_.expected = {{PINReason::kChallenge, u"wrong", 8}, - {PINReason::kChallenge, u"wrong", 7, + test_client_.expected = {{PINReason::kChallenge, "wrong", 8}, + {PINReason::kChallenge, "wrong", 7, device::kMinPinLength, PINError::kWrongPIN}, - {PINReason::kChallenge, u"wrong", 6, + {PINReason::kChallenge, "wrong", 6, device::kMinPinLength, PINError::kWrongPIN}}; EXPECT_EQ(AuthenticatorMakeCredential(make_credential_options()).status, AuthenticatorStatus::NOT_ALLOWED_ERROR); @@ -4228,7 +4228,7 @@ virtual_device_factory_->mutable_state()->pin = kTestPIN; virtual_device_factory_->mutable_state()->pin_retries = 1; - test_client_.expected = {{PINReason::kChallenge, u"wrong", 1}}; + test_client_.expected = {{PINReason::kChallenge, "wrong", 1}}; EXPECT_EQ(AuthenticatorMakeCredential().status, AuthenticatorStatus::NOT_ALLOWED_ERROR); EXPECT_EQ(0, virtual_device_factory_->mutable_state()->pin_retries); @@ -4243,8 +4243,8 @@ device::kMaxPinRetries; // Test that we can successfully get a PIN token after a failure. - test_client_.expected = {{PINReason::kChallenge, u"wrong", 8}, - {PINReason::kChallenge, kTestPIN16, 7, + test_client_.expected = {{PINReason::kChallenge, "wrong", 8}, + {PINReason::kChallenge, kTestPIN, 7, device::kMinPinLength, PINError::kWrongPIN}}; EXPECT_EQ(AuthenticatorMakeCredential().status, AuthenticatorStatus::SUCCESS); EXPECT_EQ(static_cast<int>(device::kMaxPinRetries), @@ -4262,7 +4262,7 @@ virtual_device_factory_->mutable_state()->pin_retries = device::kMaxPinRetries; test_client_.expected = { - {PINReason::kChallenge, kTestPIN16, device::kMaxPinRetries}}; + {PINReason::kChallenge, kTestPIN, device::kMaxPinRetries}}; EXPECT_EQ(AuthenticatorMakeCredential().status, AuthenticatorStatus::SUCCESS); EXPECT_EQ(taps, 1); } @@ -4293,7 +4293,7 @@ ->ReplaceDefaultDiscoveryFactoryForTesting(std::move(discovery)); test_client_.expected = { - {PINReason::kChallenge, kTestPIN16, device::kMaxPinRetries}}; + {PINReason::kChallenge, kTestPIN, device::kMaxPinRetries}}; EXPECT_EQ(AuthenticatorMakeCredential().status, AuthenticatorStatus::SUCCESS); EXPECT_EQ(taps, 2); } @@ -4312,7 +4312,7 @@ virtual_device_factory_->SetCtap2Config(config); virtual_device_factory_->mutable_state()->pin = kTestPIN; test_client_.expected = { - {PINReason::kChallenge, kTestPIN16, device::kMaxPinRetries}}; + {PINReason::kChallenge, kTestPIN, device::kMaxPinRetries}}; MakeCredentialResult result = AuthenticatorMakeCredential(make_credential_options( @@ -4365,7 +4365,7 @@ config.ctap2_versions = {device::Ctap2Version::kCtap2_1}; virtual_device_factory_->SetCtap2Config(config); virtual_device_factory_->mutable_state()->min_pin_length = 6; - test_client_.expected = {{PINReason::kSet, u"123456", 0, 6}}; + test_client_.expected = {{PINReason::kSet, "123456", 0, 6}}; MakeCredentialResult result = AuthenticatorMakeCredential(make_credential_options()); @@ -4385,7 +4385,7 @@ virtual_device_factory_->mutable_state()->min_pin_length = 6; virtual_device_factory_->mutable_state()->pin = "123456"; test_client_.expected = { - {PINReason::kChallenge, u"123456", device::kMaxPinRetries, 6}}; + {PINReason::kChallenge, "123456", device::kMaxPinRetries, 6}}; MakeCredentialResult result = AuthenticatorMakeCredential(make_credential_options()); @@ -4408,9 +4408,9 @@ virtual_device_factory_->mutable_state()->pin_retries = device::kMaxPinRetries; virtual_device_factory_->mutable_state()->min_pin_length = 6; - test_client_.expected = {{PINReason::kChallenge, kTestPIN16, + test_client_.expected = {{PINReason::kChallenge, kTestPIN, device::kMaxPinRetries, device::kMinPinLength}, - {PINReason::kChange, u"567890", 0, 6}}; + {PINReason::kChange, "567890", 0, 6}}; MakeCredentialResult result = AuthenticatorMakeCredential(make_credential_options()); @@ -4440,7 +4440,7 @@ // PIN is still required for discoverable credentials, or if the caller // requests it. if (discoverable || request_uv) { - test_client_.expected = {{PINReason::kChallenge, kTestPIN16, + test_client_.expected = {{PINReason::kChallenge, kTestPIN, device::kMaxPinRetries, device::kMinPinLength}}; } else { @@ -4485,10 +4485,10 @@ virtual_device_factory_->SetCtap2Config(config); if (pin_set) { virtual_device_factory_->mutable_state()->pin = kTestPIN; - test_client_.expected = {{PINReason::kChallenge, kTestPIN16, + test_client_.expected = {{PINReason::kChallenge, kTestPIN, device::kMaxPinRetries, device::kMinPinLength}}; } else { - test_client_.expected = {{PINReason::kSet, kTestPIN16, + test_client_.expected = {{PINReason::kSet, kTestPIN, device::kMaxPinRetries, device::kMinPinLength}}; } @@ -4556,8 +4556,7 @@ case kUsePIN: // A single prompt to get the PIN is expected. - test_client_.expected = { - {PINReason::kChallenge, kTestPIN16, 8}}; + test_client_.expected = {{PINReason::kChallenge, kTestPIN, 8}}; break; default: @@ -4604,10 +4603,10 @@ ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( options->allow_credentials[0].id(), kTestRelyingPartyId)); - test_client_.expected = {{PINReason::kChallenge, u"wrong", 8}, - {PINReason::kChallenge, u"wrong", 7, + test_client_.expected = {{PINReason::kChallenge, "wrong", 8}, + {PINReason::kChallenge, "wrong", 7, device::kMinPinLength, PINError::kWrongPIN}, - {PINReason::kChallenge, u"wrong", 6, + {PINReason::kChallenge, "wrong", 6, device::kMinPinLength, PINError::kWrongPIN}}; EXPECT_EQ(AuthenticatorGetAssertion(std::move(options)).status, AuthenticatorStatus::NOT_ALLOWED_ERROR); @@ -4626,7 +4625,7 @@ ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( options->allow_credentials[0].id(), kTestRelyingPartyId)); - test_client_.expected = {{PINReason::kChallenge, u"wrong", 1}}; + test_client_.expected = {{PINReason::kChallenge, "wrong", 1}}; EXPECT_EQ(AuthenticatorGetAssertion(std::move(options)).status, AuthenticatorStatus::NOT_ALLOWED_ERROR); EXPECT_EQ(0, virtual_device_factory_->mutable_state()->pin_retries); @@ -4647,7 +4646,7 @@ ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( options->allow_credentials[0].id(), kTestRelyingPartyId)); test_client_.expected = { - {PINReason::kChallenge, kTestPIN16, device::kMaxPinRetries}}; + {PINReason::kChallenge, kTestPIN, device::kMaxPinRetries}}; EXPECT_EQ(AuthenticatorGetAssertion(std::move(options)).status, AuthenticatorStatus::SUCCESS); EXPECT_EQ(taps, 1); @@ -4682,7 +4681,7 @@ ->ReplaceDefaultDiscoveryFactoryForTesting(std::move(discovery)); test_client_.expected = { - {PINReason::kChallenge, kTestPIN16, device::kMaxPinRetries}}; + {PINReason::kChallenge, kTestPIN, device::kMaxPinRetries}}; EXPECT_EQ(AuthenticatorGetAssertion(std::move(options)).status, AuthenticatorStatus::SUCCESS); EXPECT_EQ(taps, 2); @@ -4702,7 +4701,7 @@ ASSERT_TRUE(virtual_device_factory_->mutable_state()->InjectRegistration( options->allow_credentials[0].id(), kTestRelyingPartyId)); test_client_.expected = { - {PINReason::kChallenge, kTestPIN16, device::kMaxPinRetries}}; + {PINReason::kChallenge, kTestPIN, device::kMaxPinRetries}}; GetAssertionResult result = AuthenticatorGetAssertion(std::move(options)); EXPECT_EQ(result.status, AuthenticatorStatus::SUCCESS); @@ -4773,7 +4772,7 @@ device::kMaxPinRetries; virtual_device_factory_->SetCtap2Config(config); test_client_.expected = { - {PINReason::kChallenge, kTestPIN16, device::kMaxPinRetries}}; + {PINReason::kChallenge, kTestPIN, device::kMaxPinRetries}}; // Since converting to U2F isn't possible, this will trigger a PIN prompt // and succeed because the device does actually support the algorithm. expected_to_succeed = true; @@ -4833,7 +4832,7 @@ // test infrastructure will CHECK if |expected| is set and not used.) options->prf_enable = true; test_client_.expected = { - {PINReason::kChallenge, kTestPIN16, device::kMaxPinRetries}}; + {PINReason::kChallenge, kTestPIN, device::kMaxPinRetries}}; } else { // If PRF is requested, but the authenticator doesn't support it, then we // should still use U2F. @@ -4871,7 +4870,7 @@ device::kMaxPinRetries; test_client_.expected = { - {PINReason::kChallenge, kTestPIN16, device::kMaxPinRetries}}; + {PINReason::kChallenge, kTestPIN, device::kMaxPinRetries}}; // Craft an exclude list that is large enough to trigger batched probing and // includes one match for a credProtect=uvRequired credential. @@ -5480,7 +5479,8 @@ CollectPINOptions options, base::OnceCallback<void(std::u16string)> provide_pin_cb) override { base::SequencedTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::BindOnce(std::move(provide_pin_cb), kTestPIN16)); + FROM_HERE, + base::BindOnce(std::move(provide_pin_cb), base::UTF8ToUTF16(kTestPIN))); } void FinishCollectToken() override {}
diff --git a/content/browser/webrtc/resources/webrtc_internals.js b/content/browser/webrtc/resources/webrtc_internals.js index 9415259..767f40ec9 100644 --- a/content/browser/webrtc/resources/webrtc_internals.js +++ b/content/browser/webrtc/resources/webrtc_internals.js
@@ -343,6 +343,17 @@ 'when attempting to parse the a=extmap-allow-mixed line in the ' + 'SDP remove the line from the SDP during signalling.'); } + if (data.rtcConfiguration.indexOf('sdpSemantics: "plan-b"') !== -1) { + appendChildWithText(deprecationNotices, 'li', + 'Plan B SDP semantics, which is used when constructing an ' + + 'RTCPeerConnection with {sdpSemantics:\"plan-b\"}, is a legacy ' + + 'version of the Session Description Protocol that has severe ' + + 'compatibility issues on modern browsers. The standardized SDP ' + + 'format, \"unified-plan\", has been used by default since M72 ' + + '(January, 2019). Dropping support for Plan B is targeted for ' + + 'M93. See https://www.chromestatus.com/feature/5823036655665152 ' + + 'for more details.'); + } peerConnectionElement.appendChild(deprecationNotices); }
diff --git a/content/browser/webrtc/webrtc_internals_browsertest.cc b/content/browser/webrtc/webrtc_internals_browsertest.cc index aba856a6..8635112 100644 --- a/content/browser/webrtc/webrtc_internals_browsertest.cc +++ b/content/browser/webrtc/webrtc_internals_browsertest.cc
@@ -462,7 +462,7 @@ base::DictionaryValue* dict_dump = static_cast<base::DictionaryValue*>(dump); - EXPECT_EQ((size_t) peer_connection_number, dict_dump->size()); + EXPECT_EQ((size_t)peer_connection_number, dict_dump->DictSize()); base::DictionaryValue::Iterator it(*dict_dump); for (; !it.IsAtEnd(); it.Advance()) { @@ -484,7 +484,7 @@ pc_dump->Get("stats", &value); EXPECT_EQ(base::Value::Type::DICTIONARY, value->type()); base::DictionaryValue* dict = static_cast<base::DictionaryValue*>(value); - EXPECT_EQ((size_t) stats_number, dict->size()); + EXPECT_EQ((size_t)stats_number, dict->DictSize()); } } @@ -511,7 +511,7 @@ base::DictionaryValue* dataSeries = static_cast<base::DictionaryValue*>(value); - EXPECT_EQ(stats.values.size(), dataSeries->size()); + EXPECT_EQ(stats.values.size(), dataSeries->DictSize()); } };
diff --git a/content/browser/webui/web_ui_data_source_unittest.cc b/content/browser/webui/web_ui_data_source_unittest.cc index ffdf3cd..ae07bfa 100644 --- a/content/browser/webui/web_ui_data_source_unittest.cc +++ b/content/browser/webui/web_ui_data_source_unittest.cc
@@ -20,7 +20,7 @@ const int kDummyResourceId = 789; const int kDummyJSResourceId = 790; -const char16_t kDummyString[] = u"foo"; +const char kDummyString[] = "foo"; const char kDummyDefaultResource[] = "<html>foo</html>"; const char kDummyResource[] = "<html>blah</html>"; const char kDummyJSResource[] = "export const bar = 5;"; @@ -31,7 +31,7 @@ std::u16string GetLocalizedString(int message_id) override { if (message_id == kDummyStringId) - return kDummyString; + return base::UTF8ToUTF16(kDummyString); return std::u16string(); }
diff --git a/content/browser/worker_host/dedicated_worker_host.cc b/content/browser/worker_host/dedicated_worker_host.cc index 5b25dfb..dd11b86 100644 --- a/content/browser/worker_host/dedicated_worker_host.cc +++ b/content/browser/worker_host/dedicated_worker_host.cc
@@ -438,7 +438,7 @@ return false; // > 4. If ownerPolicy's report-only value is "require-corp" or - // "cors-or-credentialless" and policy's value is "unsafe-none", then queue a + // "credentialless" and policy's value is "unsafe-none", then queue a // cross-origin embedder policy inheritance violation with response, "worker // initialization", owner's policy's report only reporting endpoint, // "reporting", and owner. @@ -452,7 +452,7 @@ } // > 5. If ownerPolicy's value is "unsafe-none" or policy's value is - // "require-corp" or "cors-or-credentialless", then return true. + // "require-corp" or "credentialless", then return true. if (!network::CompatibleWithCrossOriginIsolated( creator_cross_origin_embedder_policy) || network::CompatibleWithCrossOriginIsolated(
diff --git a/content/browser/worker_host/shared_worker_service_impl.cc b/content/browser/worker_host/shared_worker_service_impl.cc index 35db6fde..a26596ca 100644 --- a/content/browser/worker_host/shared_worker_service_impl.cc +++ b/content/browser/worker_host/shared_worker_service_impl.cc
@@ -296,7 +296,7 @@ // script is loaded so that the process allocation can take COEP header into // account. scoped_refptr<SiteInstanceImpl> site_instance = creator.GetSiteInstance(); - if (site_instance->IsCoopCoepCrossOriginIsolated()) { + if (site_instance->IsCrossOriginIsolated()) { if (is_guest) { site_instance = SiteInstanceImpl::CreateForGuest( partition->browser_context(), @@ -305,7 +305,7 @@ site_instance = SiteInstanceImpl::CreateForUrlInfo( partition->browser_context(), UrlInfo(instance.url(), UrlInfo::OriginIsolationRequest::kNone), - CoopCoepCrossOriginIsolatedInfo::CreateNonIsolated()); + WebExposedIsolationInfo::CreateNonIsolated()); } }
diff --git a/content/browser/worker_host/worker_browsertest.cc b/content/browser/worker_host/worker_browsertest.cc index c478eca2..5fc9b38 100644 --- a/content/browser/worker_host/worker_browsertest.cc +++ b/content/browser/worker_host/worker_browsertest.cc
@@ -337,7 +337,7 @@ RenderFrameHostImpl* page_rfh = static_cast<RenderFrameHostImpl*>( shell()->web_contents()->GetMainFrame()); auto page_lock = page_rfh->GetSiteInstance()->GetProcessLock(); - EXPECT_TRUE(page_lock.coop_coep_cross_origin_isolated_info().is_isolated()); + EXPECT_TRUE(page_lock.web_exposed_isolation_info().is_isolated()); EXPECT_NE(page_rfh->GetCrossOriginIsolationStatus(), RenderFrameHost::CrossOriginIsolationStatus::kNotIsolated); @@ -355,8 +355,7 @@ RenderProcessHost* worker_rph = host->GetProcessHost(); EXPECT_NE(worker_rph, page_rfh->GetProcess()); auto worker_lock = host->site_instance()->GetProcessLock(); - EXPECT_FALSE( - worker_lock.coop_coep_cross_origin_isolated_info().is_isolated()); + EXPECT_FALSE(worker_lock.web_exposed_isolation_info().is_isolated()); } // http://crbug.com/96435
diff --git a/content/common/renderer.mojom b/content/common/renderer.mojom index b0f24d3..d9091b6d 100644 --- a/content/common/renderer.mojom +++ b/content/common/renderer.mojom
@@ -161,6 +161,14 @@ // This property is process global because we ensure that a renderer process // host only cross-origin isolated agents or only non-cross-origin isolated // agents, not both. - // This is called at most once. This is called earlier than any frame commit. + // This is called at most once, prior to committing a navigation. SetIsCrossOriginIsolated(bool value); + + // Direct sockets require isolation above and beyond what "cross-origin + // isolation" provides. This flag corresponds to that set of restrictions. + // Similarly to the `SetIsCrossOriginIsolated()` method above, this flag is + // process global, and called at most once, prior to committing a navigation. + // + // TODO(crbug.com/1206150): We need a specification for this restriction. + SetIsDirectSocketEnabled(bool value); };
diff --git a/content/public/browser/browser_accessibility_state.h b/content/public/browser/browser_accessibility_state.h index df53b0d..60eec69 100644 --- a/content/public/browser/browser_accessibility_state.h +++ b/content/public/browser/browser_accessibility_state.h
@@ -95,6 +95,26 @@ FocusChangedCallback callback) = 0; }; +namespace testing { + +class CONTENT_EXPORT ScopedContentAXModeSetter { + public: + explicit ScopedContentAXModeSetter(ui::AXMode mode) : mode_(mode) { + BrowserAccessibilityState::GetInstance()->AddAccessibilityModeFlags(mode); + } + ~ScopedContentAXModeSetter() { ResetMode(); } + + void ResetMode() { + BrowserAccessibilityState::GetInstance()->RemoveAccessibilityModeFlags( + mode_); + } + + private: + ui::AXMode mode_; +}; + +} // namespace testing + } // namespace content #endif // CONTENT_PUBLIC_BROWSER_BROWSER_ACCESSIBILITY_STATE_H_
diff --git a/content/public/test/browser_test_base.h b/content/public/test/browser_test_base.h index c940e5fd..b8be8df 100644 --- a/content/public/test/browser_test_base.h +++ b/content/public/test/browser_test_base.h
@@ -33,7 +33,7 @@ class BrowserMainParts; class WebContents; -class BrowserTestBase : public testing::Test { +class BrowserTestBase : public ::testing::Test { public: BrowserTestBase(); ~BrowserTestBase() override;
diff --git a/content/public/test/browser_test_utils.cc b/content/public/test/browser_test_utils.cc index 2ef7c06..871303cd 100644 --- a/content/public/test/browser_test_utils.cc +++ b/content/public/test/browser_test_utils.cc
@@ -1649,10 +1649,10 @@ } // namespace -testing::AssertionResult ExecJs(const ToRenderFrameHost& execution_target, - const std::string& script, - int options, - int32_t world_id) { +::testing::AssertionResult ExecJs(const ToRenderFrameHost& execution_target, + const std::string& script, + int options, + int32_t world_id) { CHECK(!(options & EXECUTE_SCRIPT_USE_MANUAL_REPLY)) << "USE_MANUAL_REPLY does not make sense with ExecJs."; @@ -1664,8 +1664,8 @@ // NOTE: |eval_result.value| is intentionally ignored by ExecJs(). if (!eval_result.error.empty()) - return testing::AssertionFailure() << eval_result.error; - return testing::AssertionSuccess(); + return ::testing::AssertionFailure() << eval_result.error; + return ::testing::AssertionSuccess(); } EvalJsResult EvalJs(const ToRenderFrameHost& execution_target, @@ -2205,7 +2205,7 @@ std::wstring(V_BSTR(name.ptr()), SysStringLen(V_BSTR(name.ptr()))))); } - ASSERT_THAT(names, testing::UnorderedElementsAreArray(expected_names)); + ASSERT_THAT(names, ::testing::UnorderedElementsAreArray(expected_names)); } #endif
diff --git a/content/public/test/test_renderer_host.h b/content/public/test/test_renderer_host.h index 23fcd81..a046d09 100644 --- a/content/public/test/test_renderer_host.h +++ b/content/public/test/test_renderer_host.h
@@ -196,7 +196,7 @@ }; // RenderViewHostTestHarness --------------------------------------------------- -class RenderViewHostTestHarness : public testing::Test { +class RenderViewHostTestHarness : public ::testing::Test { public: // Constructs a RenderViewHostTestHarness which uses |traits| to initialize // its BrowserTaskEnvironment.
diff --git a/content/renderer/render_thread_impl.cc b/content/renderer/render_thread_impl.cc index f61d4bb..887a686 100644 --- a/content/renderer/render_thread_impl.cc +++ b/content/renderer/render_thread_impl.cc
@@ -1378,6 +1378,10 @@ blink::SetIsCrossOriginIsolated(value); } +void RenderThreadImpl::SetIsDirectSocketEnabled(bool value) { + blink::SetIsDirectSocketEnabled(value); +} + bool RenderThreadImpl::GetRendererMemoryMetrics( RendererMemoryMetrics* memory_metrics) const { DCHECK(memory_metrics);
diff --git a/content/renderer/render_thread_impl.h b/content/renderer/render_thread_impl.h index ec1f00f..c07c45f3 100644 --- a/content/renderer/render_thread_impl.h +++ b/content/renderer/render_thread_impl.h
@@ -455,6 +455,7 @@ WriteClangProfilingProfileCallback callback) override; #endif void SetIsCrossOriginIsolated(bool value) override; + void SetIsDirectSocketEnabled(bool value) override; void OnMemoryPressure( base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level);
diff --git a/content/renderer/render_view_browsertest.cc b/content/renderer/render_view_browsertest.cc index b000033f..df7e323 100644 --- a/content/renderer/render_view_browsertest.cc +++ b/content/renderer/render_view_browsertest.cc
@@ -2375,7 +2375,8 @@ 0, base::DoNothing()); // Non surrogate pair unicode character. - const std::u16string unicode_composition = u"あいうえお"; + const std::u16string unicode_composition = base::UTF8ToUTF16( + "\xE3\x81\x82\xE3\x81\x84\xE3\x81\x86\xE3\x81\x88\xE3\x81\x8A"); widget_input_handler->ImeSetComposition(unicode_composition, empty_ime_text_span, gfx::Range::InvalidRange(), 0, 0); @@ -2388,7 +2389,8 @@ base::DoNothing()); // Surrogate pair character. - const std::u16string surrogate_pair_char = u"𠮟"; + const std::u16string surrogate_pair_char = + base::UTF8ToUTF16("\xF0\xA0\xAE\x9F"); widget_input_handler->ImeSetComposition(surrogate_pair_char, empty_ime_text_span, gfx::Range::InvalidRange(), 0, 0); @@ -2402,8 +2404,8 @@ // Mixed string. const std::u16string surrogate_pair_mixed_composition = - surrogate_pair_char + u"あ" + surrogate_pair_char + u"b" + - surrogate_pair_char; + surrogate_pair_char + base::UTF8ToUTF16("\xE3\x81\x82") + + surrogate_pair_char + u"b" + surrogate_pair_char; const size_t utf16_length = 8UL; const bool is_surrogate_pair_empty_rect[8] = {false, true, false, false, true, false, false, true};
diff --git a/content/renderer/v8_value_converter_impl_unittest.cc b/content/renderer/v8_value_converter_impl_unittest.cc index c5193dc..4c98c68 100644 --- a/content/renderer/v8_value_converter_impl_unittest.cc +++ b/content/renderer/v8_value_converter_impl_unittest.cc
@@ -280,8 +280,9 @@ converter.ToV8Value(original_root.get(), context).As<v8::Object>(); ASSERT_FALSE(v8_object.IsEmpty()); - EXPECT_EQ(static_cast<const base::DictionaryValue&>(*original_root).size(), - v8_object->GetPropertyNames(context).ToLocalChecked()->Length()); + EXPECT_EQ( + static_cast<const base::DictionaryValue&>(*original_root).DictSize(), + v8_object->GetPropertyNames(context).ToLocalChecked()->Length()); EXPECT_TRUE( v8_object ->Get(context, v8::String::NewFromUtf8( @@ -434,7 +435,7 @@ // http://code.google.com/p/v8/issues/detail?id=1342 // EXPECT_EQ(2u, converted->size()); // EXPECT_TRUE(IsNull(converted.get(), "foo")); - EXPECT_EQ(1u, converted->size()); + EXPECT_EQ(1u, converted->DictSize()); EXPECT_EQ("bar", GetString(converted.get(), "bar")); // Converting to v8 value should not trigger the setter. @@ -540,7 +541,7 @@ std::unique_ptr<base::DictionaryValue> result( base::DictionaryValue::From(converter.FromV8Value(object, context))); ASSERT_TRUE(result.get()); - EXPECT_EQ(0u, result->size()); + EXPECT_EQ(0u, result->DictSize()); } TEST_F(V8ValueConverterImplTest, ObjectPrototypeSetter) { @@ -699,7 +700,7 @@ std::unique_ptr<base::DictionaryValue> result( base::DictionaryValue::From(converter.FromV8Value(object, context))); ASSERT_TRUE(result.get()); - EXPECT_EQ(0u, result->size()); + EXPECT_EQ(0u, result->DictSize()); } TEST_F(V8ValueConverterImplTest, RecursiveObjects) { @@ -732,7 +733,7 @@ std::unique_ptr<base::DictionaryValue> object_result( base::DictionaryValue::From(converter.FromV8Value(object, context))); ASSERT_TRUE(object_result.get()); - EXPECT_EQ(2u, object_result->size()); + EXPECT_EQ(2u, object_result->DictSize()); EXPECT_TRUE(IsNull(object_result.get(), "obj")); v8::Local<v8::Array> array = v8::Array::New(isolate_).As<v8::Array>(); @@ -965,7 +966,7 @@ std::unique_ptr<base::DictionaryValue> result( base::DictionaryValue::From(converter.FromV8Value(object, context))); ASSERT_TRUE(result.get()); - EXPECT_EQ(2u, result->size()); + EXPECT_EQ(2u, result->DictSize()); { base::DictionaryValue* one_dict = nullptr;
diff --git a/content/test/BUILD.gn b/content/test/BUILD.gn index 79d6709..899917c 100644 --- a/content/test/BUILD.gn +++ b/content/test/BUILD.gn
@@ -2140,6 +2140,7 @@ "../browser/web_contents/web_contents_user_data_unittest.cc", "../browser/web_contents/web_contents_view_aura_unittest.cc", "../browser/web_database/web_database_host_impl_unittest.cc", + "../browser/web_exposed_isolation_info_unittest.cc", "../browser/web_package/signed_exchange_cert_fetcher_unittest.cc", "../browser/web_package/signed_exchange_certificate_chain_unittest.cc", "../browser/web_package/signed_exchange_envelope_unittest.cc",
diff --git a/device/bluetooth/bluetooth_adapter_mac.mm b/device/bluetooth/bluetooth_adapter_mac.mm index b56737af..97e7ab4 100644 --- a/device/bluetooth/bluetooth_adapter_mac.mm +++ b/device/bluetooth/bluetooth_adapter_mac.mm
@@ -655,13 +655,13 @@ // https://developer.apple.com/documentation/corebluetooth/cbadvertisementdataserviceuuidskey BluetoothDevice::UUIDList advertised_uuids; NSArray* service_uuids = - [advertisement_data objectForKey:CBAdvertisementDataServiceUUIDsKey]; + advertisement_data[CBAdvertisementDataServiceUUIDsKey]; for (CBUUID* uuid in service_uuids) { advertised_uuids.push_back( BluetoothAdapterMac::BluetoothUUIDWithCBUUID(uuid)); } - NSArray* overflow_service_uuids = [advertisement_data - objectForKey:CBAdvertisementDataOverflowServiceUUIDsKey]; + NSArray* overflow_service_uuids = + advertisement_data[CBAdvertisementDataOverflowServiceUUIDsKey]; for (CBUUID* uuid in overflow_service_uuids) { advertised_uuids.push_back( BluetoothAdapterMac::BluetoothUUIDWithCBUUID(uuid)); @@ -672,9 +672,9 @@ // https://developer.apple.com/documentation/corebluetooth/cbadvertisementdataservicedatakey BluetoothDevice::ServiceDataMap service_data_map; NSDictionary* service_data = - [advertisement_data objectForKey:CBAdvertisementDataServiceDataKey]; + advertisement_data[CBAdvertisementDataServiceDataKey]; for (CBUUID* uuid in service_data) { - NSData* data = [service_data objectForKey:uuid]; + NSData* data = service_data[uuid]; const uint8_t* bytes = static_cast<const uint8_t*>([data bytes]); size_t length = [data length]; service_data_map.emplace(BluetoothAdapterMac::BluetoothUUIDWithCBUUID(uuid), @@ -690,7 +690,7 @@ // BluetoothDevice::ManufacturerDataMap manufacturer_data_map; NSData* manufacturer_data = - [advertisement_data objectForKey:CBAdvertisementDataManufacturerDataKey]; + advertisement_data[CBAdvertisementDataManufacturerDataKey]; const uint8_t* bytes = static_cast<const uint8_t*>([manufacturer_data bytes]); size_t length = [manufacturer_data length]; if (length > 1) { @@ -704,13 +704,11 @@ // 0xXX: -127 to +127 dBm" // Core Specification Supplement (CSS) v7, Part 1.5 // https://developer.apple.com/documentation/corebluetooth/cbadvertisementdatatxpowerlevelkey - NSNumber* tx_power = - [advertisement_data objectForKey:CBAdvertisementDataTxPowerLevelKey]; + NSNumber* tx_power = advertisement_data[CBAdvertisementDataTxPowerLevelKey]; int8_t clamped_tx_power = BluetoothDevice::ClampPower([tx_power intValue]); // Get the Advertising name - NSString* local_name = - [advertisement_data objectForKey:CBAdvertisementDataLocalNameKey]; + NSString* local_name = advertisement_data[CBAdvertisementDataLocalNameKey]; for (auto& observer : observers_) { base::Optional<std::string> device_name_opt = device_mac->GetName();
diff --git a/device/bluetooth/bluetooth_adapter_mac_unittest.mm b/device/bluetooth/bluetooth_adapter_mac_unittest.mm index 7d210bf..18d832a 100644 --- a/device/bluetooth/bluetooth_adapter_mac_unittest.mm +++ b/device/bluetooth/bluetooth_adapter_mac_unittest.mm
@@ -165,7 +165,7 @@ NSDictionary* AdvertisementData() { NSDictionary* advertisement_data = @{ CBAdvertisementDataIsConnectable : @(YES), - CBAdvertisementDataServiceDataKey : [NSDictionary dictionary], + CBAdvertisementDataServiceDataKey : @{}, }; return [advertisement_data retain]; }
diff --git a/device/bluetooth/bluetooth_discovery_manager_mac.mm b/device/bluetooth/bluetooth_discovery_manager_mac.mm index 3331f05..d05ff3c 100644 --- a/device/bluetooth/bluetooth_discovery_manager_mac.mm +++ b/device/bluetooth/bluetooth_discovery_manager_mac.mm
@@ -25,7 +25,8 @@ device::BluetoothDiscoveryManagerMacClassic* _manager; // weak } -- (id)initWithManager:(device::BluetoothDiscoveryManagerMacClassic*)manager; +- (instancetype)initWithManager: + (device::BluetoothDiscoveryManagerMacClassic*)manager; @end @@ -201,8 +202,8 @@ @implementation BluetoothDeviceInquiryDelegate -- (id)initWithManager: - (device::BluetoothDiscoveryManagerMacClassic*)manager { +- (instancetype)initWithManager: + (device::BluetoothDiscoveryManagerMacClassic*)manager { if ((self = [super init])) _manager = manager;
diff --git a/device/bluetooth/bluetooth_l2cap_channel_mac.mm b/device/bluetooth/bluetooth_l2cap_channel_mac.mm index 8e7156c..eb95d62 100644 --- a/device/bluetooth/bluetooth_l2cap_channel_mac.mm +++ b/device/bluetooth/bluetooth_l2cap_channel_mac.mm
@@ -18,13 +18,13 @@ device::BluetoothL2capChannelMac* _channel; // weak } -- (id)initWithChannel:(device::BluetoothL2capChannelMac*)channel; +- (instancetype)initWithChannel:(device::BluetoothL2capChannelMac*)channel; @end @implementation BluetoothL2capChannelDelegate -- (id)initWithChannel:(device::BluetoothL2capChannelMac*)channel { +- (instancetype)initWithChannel:(device::BluetoothL2capChannelMac*)channel { if ((self = [super init])) _channel = channel;
diff --git a/device/bluetooth/bluetooth_low_energy_central_manager_delegate.h b/device/bluetooth/bluetooth_low_energy_central_manager_delegate.h index 5131f18..8ba9713 100644 --- a/device/bluetooth/bluetooth_low_energy_central_manager_delegate.h +++ b/device/bluetooth/bluetooth_low_energy_central_manager_delegate.h
@@ -29,9 +29,10 @@ std::unique_ptr<device::BluetoothLowEnergyCentralManagerBridge> _bridge; } -- (id)initWithDiscoveryManager: - (device::BluetoothLowEnergyDiscoveryManagerMac*)discovery_manager - andAdapter:(device::BluetoothAdapterMac*)adapter; +- (instancetype)initWithDiscoveryManager: + (device::BluetoothLowEnergyDiscoveryManagerMac*) + discovery_manager + andAdapter:(device::BluetoothAdapterMac*)adapter; @end
diff --git a/device/bluetooth/bluetooth_low_energy_central_manager_delegate.mm b/device/bluetooth/bluetooth_low_energy_central_manager_delegate.mm index 12ba10a1..e37a886 100644 --- a/device/bluetooth/bluetooth_low_energy_central_manager_delegate.mm +++ b/device/bluetooth/bluetooth_low_energy_central_manager_delegate.mm
@@ -60,9 +60,10 @@ @implementation BluetoothLowEnergyCentralManagerDelegate -- (id)initWithDiscoveryManager: - (device::BluetoothLowEnergyDiscoveryManagerMac*)discovery_manager - andAdapter:(device::BluetoothAdapterMac*)adapter { +- (instancetype)initWithDiscoveryManager: + (device::BluetoothLowEnergyDiscoveryManagerMac*) + discovery_manager + andAdapter:(device::BluetoothAdapterMac*)adapter { if ((self = [super init])) { _bridge = std::make_unique<device::BluetoothLowEnergyCentralManagerBridge>( discovery_manager, adapter);
diff --git a/device/bluetooth/bluetooth_low_energy_peripheral_delegate.h b/device/bluetooth/bluetooth_low_energy_peripheral_delegate.h index 163b4ec..d394edd 100644 --- a/device/bluetooth/bluetooth_low_energy_peripheral_delegate.h +++ b/device/bluetooth/bluetooth_low_energy_peripheral_delegate.h
@@ -27,7 +27,7 @@ std::unique_ptr<device::BluetoothLowEnergyPeripheralBridge> _bridge; } -- (id)initWithBluetoothLowEnergyDeviceMac: +- (instancetype)initWithBluetoothLowEnergyDeviceMac: (device::BluetoothLowEnergyDeviceMac*)device_mac; @end
diff --git a/device/bluetooth/bluetooth_low_energy_peripheral_delegate.mm b/device/bluetooth/bluetooth_low_energy_peripheral_delegate.mm index cf51e55a..62c83f72 100644 --- a/device/bluetooth/bluetooth_low_energy_peripheral_delegate.mm +++ b/device/bluetooth/bluetooth_low_energy_peripheral_delegate.mm
@@ -69,7 +69,7 @@ @implementation BluetoothLowEnergyPeripheralDelegate -- (id)initWithBluetoothLowEnergyDeviceMac: +- (instancetype)initWithBluetoothLowEnergyDeviceMac: (device::BluetoothLowEnergyDeviceMac*)device_mac { if ((self = [super init])) { _bridge = std::make_unique<device::BluetoothLowEnergyPeripheralBridge>(
diff --git a/device/bluetooth/bluetooth_low_energy_peripheral_manager_delegate.mm b/device/bluetooth/bluetooth_low_energy_peripheral_manager_delegate.mm index d6aa48c4..0f7ceb2 100644 --- a/device/bluetooth/bluetooth_low_energy_peripheral_manager_delegate.mm +++ b/device/bluetooth/bluetooth_low_energy_peripheral_manager_delegate.mm
@@ -46,10 +46,10 @@ std::unique_ptr<device::BluetoothLowEnergyPeripheralManagerBridge> _bridge; } -- (id)initWithAdvertisementManager: - (device::BluetoothLowEnergyAdvertisementManagerMac*) - advertisementManager - andAdapter:(device::BluetoothAdapterMac*)adapter { +- (instancetype) + initWithAdvertisementManager: + (device::BluetoothLowEnergyAdvertisementManagerMac*)advertisementManager + andAdapter:(device::BluetoothAdapterMac*)adapter { if ((self = [super init])) { _bridge = std::make_unique<device::BluetoothLowEnergyPeripheralManagerBridge>(
diff --git a/device/bluetooth/bluetooth_rfcomm_channel_mac.mm b/device/bluetooth/bluetooth_rfcomm_channel_mac.mm index 3a2b3b6..c37c2710 100644 --- a/device/bluetooth/bluetooth_rfcomm_channel_mac.mm +++ b/device/bluetooth/bluetooth_rfcomm_channel_mac.mm
@@ -18,13 +18,13 @@ device::BluetoothRfcommChannelMac* _channel; // weak } -- (id)initWithChannel:(device::BluetoothRfcommChannelMac*)channel; +- (instancetype)initWithChannel:(device::BluetoothRfcommChannelMac*)channel; @end @implementation BluetoothRfcommChannelDelegate -- (id)initWithChannel:(device::BluetoothRfcommChannelMac*)channel { +- (instancetype)initWithChannel:(device::BluetoothRfcommChannelMac*)channel { if ((self = [super init])) _channel = channel;
diff --git a/device/bluetooth/bluetooth_socket_mac.mm b/device/bluetooth/bluetooth_socket_mac.mm index 8ff631a..5af1e38 100644 --- a/device/bluetooth/bluetooth_socket_mac.mm +++ b/device/bluetooth/bluetooth_socket_mac.mm
@@ -50,20 +50,22 @@ IOBluetoothDevice* _device; // weak } -- (id)initWithSocket:(scoped_refptr<device::BluetoothSocketMac>)socket - device:(IOBluetoothDevice*)device - success_callback:(base::OnceClosure)success_callback - error_callback:(BluetoothSocket::ErrorCompletionCallback)error_callback; +- (instancetype)initWithSocket:(scoped_refptr<device::BluetoothSocketMac>)socket + device:(IOBluetoothDevice*)device + success_callback:(base::OnceClosure)success_callback + error_callback: + (BluetoothSocket::ErrorCompletionCallback)error_callback; - (void)sdpQueryComplete:(IOBluetoothDevice*)device status:(IOReturn)status; @end @implementation SDPQueryListener -- (id)initWithSocket:(scoped_refptr<device::BluetoothSocketMac>)socket - device:(IOBluetoothDevice*)device - success_callback:(base::OnceClosure)success_callback - error_callback:(BluetoothSocket::ErrorCompletionCallback)error_callback { +- (instancetype)initWithSocket:(scoped_refptr<device::BluetoothSocketMac>)socket + device:(IOBluetoothDevice*)device + success_callback:(base::OnceClosure)success_callback + error_callback: + (BluetoothSocket::ErrorCompletionCallback)error_callback { if ((self = [super init])) { _socket = socket; _device = device; @@ -94,8 +96,8 @@ IOBluetoothUserNotification* _rfcommNewChannelNotification; // weak } -- (id)initWithSocket:(device::BluetoothSocketMac*)socket - channelID:(BluetoothRFCOMMChannelID)channelID; +- (instancetype)initWithSocket:(device::BluetoothSocketMac*)socket + channelID:(BluetoothRFCOMMChannelID)channelID; - (void)rfcommChannelOpened:(IOBluetoothUserNotification*)notification channel:(IOBluetoothRFCOMMChannel*)rfcommChannel; @@ -103,8 +105,8 @@ @implementation BluetoothRfcommConnectionListener -- (id)initWithSocket:(device::BluetoothSocketMac*)socket - channelID:(BluetoothRFCOMMChannelID)channelID { +- (instancetype)initWithSocket:(device::BluetoothSocketMac*)socket + channelID:(BluetoothRFCOMMChannelID)channelID { if ((self = [super init])) { _socket = socket; @@ -156,8 +158,8 @@ IOBluetoothUserNotification* _l2capNewChannelNotification; // weak } -- (id)initWithSocket:(device::BluetoothSocketMac*)socket - psm:(BluetoothL2CAPPSM)psm; +- (instancetype)initWithSocket:(device::BluetoothSocketMac*)socket + psm:(BluetoothL2CAPPSM)psm; - (void)l2capChannelOpened:(IOBluetoothUserNotification*)notification channel:(IOBluetoothL2CAPChannel*)l2capChannel; @@ -165,8 +167,8 @@ @implementation BluetoothL2capConnectionListener -- (id)initWithSocket:(device::BluetoothSocketMac*)socket - psm:(BluetoothL2CAPPSM)psm { +- (instancetype)initWithSocket:(device::BluetoothSocketMac*)socket + psm:(BluetoothL2CAPPSM)psm { if ((self = [super init])) { _socket = socket; @@ -257,18 +259,17 @@ const int kServiceNameKey = kEnglishLanguageBase + kBluetoothSDPAttributeIdentifierServiceName; NSString* service_name = base::SysUTF8ToNSString(*name); - [service_definition setObject:service_name - forKey:IntToNSString(kServiceNameKey)]; + service_definition[IntToNSString(kServiceNameKey)] = service_name; } const int kUUIDsKey = kBluetoothSDPAttributeIdentifierServiceClassIDList; NSArray* uuids = @[GetIOBluetoothSDPUUID(uuid)]; - [service_definition setObject:uuids forKey:IntToNSString(kUUIDsKey)]; + service_definition[IntToNSString(kUUIDsKey)] = uuids; const int kProtocolDefinitionsKey = kBluetoothSDPAttributeIdentifierProtocolDescriptorList; - [service_definition setObject:protocol_definition - forKey:IntToNSString(kProtocolDefinitionsKey)]; + service_definition[IntToNSString(kProtocolDefinitionsKey)] = + protocol_definition; return service_definition; }
diff --git a/device/bluetooth/test/bluetooth_test_mac.mm b/device/bluetooth/test/bluetooth_test_mac.mm index d2bd7e6..b471b45 100644 --- a/device/bluetooth/test/bluetooth_test_mac.mm +++ b/device/bluetooth/test/bluetooth_test_mac.mm
@@ -61,27 +61,24 @@ }]); if (name) { - [advertisement_data setObject:name forKey:CBAdvertisementDataLocalNameKey]; + advertisement_data[CBAdvertisementDataLocalNameKey] = name; } if (uuids) { - [advertisement_data setObject:uuids - forKey:CBAdvertisementDataServiceUUIDsKey]; + advertisement_data[CBAdvertisementDataServiceUUIDsKey] = uuids; } if (service_data) { - [advertisement_data setObject:service_data - forKey:CBAdvertisementDataServiceDataKey]; + advertisement_data[CBAdvertisementDataServiceDataKey] = service_data; } if (service_data) { - [advertisement_data setObject:manufacturer_data - forKey:CBAdvertisementDataManufacturerDataKey]; + advertisement_data[CBAdvertisementDataManufacturerDataKey] = + manufacturer_data; } if (tx_power) { - [advertisement_data setObject:tx_power - forKey:CBAdvertisementDataTxPowerLevelKey]; + advertisement_data[CBAdvertisementDataTxPowerLevelKey] = tx_power; } return scoped_nsobject<NSDictionary>(advertisement_data, @@ -623,7 +620,7 @@ void BluetoothTestMac::SimulateGattDescriptorReadNSNumberMac( BluetoothRemoteGattDescriptor* descriptor, short value) { - NSNumber* number = [NSNumber numberWithShort:value]; + NSNumber* number = @(value); [GetCBMockDescriptor(descriptor) simulateReadWithValue:number error:nil]; }
diff --git a/device/fido/auth_token_requester_unittest.cc b/device/fido/auth_token_requester_unittest.cc index 1bbcc77d..4111ee2 100644 --- a/device/fido/auth_token_requester_unittest.cc +++ b/device/fido/auth_token_requester_unittest.cc
@@ -34,15 +34,14 @@ device::AuthenticatorSupportedOptions::UserVerificationAvailability; constexpr char kTestPIN[] = "1234"; -constexpr char16_t kTestPIN16[] = u"1234"; -constexpr char16_t kNewPIN[] = u"5678"; +constexpr char kNewPIN[] = "5678"; struct TestExpectation { pin::PINEntryReason reason; pin::PINEntryError error = pin::PINEntryError::kNoError; uint32_t min_pin_length = kMinPinLength; int attempts = 8; - std::u16string pin = kTestPIN16; + std::u16string pin = base::UTF8ToUTF16(kTestPIN); }; struct TestCase { @@ -472,7 +471,7 @@ { .reason = pin::PINEntryReason::kChange, .attempts = 0, - .pin = kNewPIN, + .pin = base::UTF8ToUTF16(kNewPIN), }}}); EXPECT_EQ(*delegate_->result(), AuthTokenRequester::Result::kSuccess); @@ -501,7 +500,7 @@ .reason = pin::PINEntryReason::kChange, .error = pin::PINEntryError::kSameAsCurrentPIN, .attempts = 0, - .pin = kNewPIN, + .pin = base::UTF8ToUTF16(kNewPIN), }}}); EXPECT_EQ(*delegate_->result(), AuthTokenRequester::Result::kSuccess);
diff --git a/device/gamepad/gamepad_platform_data_fetcher_mac.mm b/device/gamepad/gamepad_platform_data_fetcher_mac.mm index a2e0fa8..92734916 100644 --- a/device/gamepad/gamepad_platform_data_fetcher_mac.mm +++ b/device/gamepad/gamepad_platform_data_fetcher_mac.mm
@@ -32,14 +32,10 @@ const uint16_t kMultiAxisUsageNumber = 0x08; NSDictionary* DeviceMatching(uint32_t usage_page, uint32_t usage) { - return [NSDictionary - dictionaryWithObjectsAndKeys:[NSNumber numberWithUnsignedInt:usage_page], - base::mac::CFToNSCast( - CFSTR(kIOHIDDeviceUsagePageKey)), - [NSNumber numberWithUnsignedInt:usage], - base::mac::CFToNSCast( - CFSTR(kIOHIDDeviceUsageKey)), - nil]; + return @{ + base::mac::CFToNSCast(CFSTR(kIOHIDDeviceUsagePageKey)) : @(usage_page), + base::mac::CFToNSCast(CFSTR(kIOHIDDeviceUsageKey)) : @(usage) + }; } } // namespace
diff --git a/docs/README.md b/docs/README.md index 62c64ab..72b2af24 100644 --- a/docs/README.md +++ b/docs/README.md
@@ -160,7 +160,7 @@ ### Testing * [Running and Debugging Web Tests](testing/web_tests.md) -* [On disabling tests](testing/disabling_tests.md) +* [On disabling tests](testing/on_disabling_tests.md) * [Writing Web Tests](testing/writing_web_tests.md) - Web Tests using `content_shell` * [Web Test Expectations and Baselines](testing/web_test_expectations.md) -
diff --git a/extensions/browser/api/diagnostics/diagnostics_api.cc b/extensions/browser/api/diagnostics/diagnostics_api.cc index 53d6d5b..30177dc 100644 --- a/extensions/browser/api/diagnostics/diagnostics_api.cc +++ b/extensions/browser/api/diagnostics/diagnostics_api.cc
@@ -32,7 +32,7 @@ return false; base::DictionaryValue* result = NULL; - if (!parsed_value->GetAsDictionary(&result) || result->size() != 1) + if (!parsed_value->GetAsDictionary(&result) || result->DictSize() != 1) return false; // Returns the first item.
diff --git a/extensions/browser/api/web_request/web_request_api.cc b/extensions/browser/api/web_request/web_request_api.cc index 31a3090..00f74bb 100644 --- a/extensions/browser/api/web_request/web_request_api.cc +++ b/extensions/browser/api/web_request/web_request_api.cc
@@ -2687,7 +2687,7 @@ if (value->HasKey("cancel")) { // Don't allow cancel mixed with other keys. - if (value->size() != 1) { + if (value->DictSize() != 1) { OnError(event_name, sub_event_name, request_id, render_process_id, web_view_instance_id, std::move(response)); return RespondNow(Error(keys::kInvalidBlockingResponse));
diff --git a/extensions/browser/event_router_unittest.cc b/extensions/browser/event_router_unittest.cc index a3e5663..ea84d5ad 100644 --- a/extensions/browser/event_router_unittest.cc +++ b/extensions/browser/event_router_unittest.cc
@@ -455,7 +455,7 @@ const base::DictionaryValue* filtered_events = GetFilteredEvents(kExtensionId); ASSERT_TRUE(filtered_events); - ASSERT_EQ(1u, filtered_events->size()); + ASSERT_EQ(1u, filtered_events->DictSize()); DictionaryValue::Iterator iter(*filtered_events); ASSERT_EQ(kEventName, iter.key());
diff --git a/extensions/browser/value_store/leveldb_value_store_unittest.cc b/extensions/browser/value_store/leveldb_value_store_unittest.cc index a856dcd..fca2a7bc 100644 --- a/extensions/browser/value_store/leveldb_value_store_unittest.cc +++ b/extensions/browser/value_store/leveldb_value_store_unittest.cc
@@ -186,5 +186,5 @@ ASSERT_EQ(ValueStore::DB_RESTORE_REPAIR_SUCCESS, result.status().restore_status); EXPECT_TRUE(result.status().ok()); - EXPECT_EQ(0u, result.settings().size()); + EXPECT_EQ(0u, result.settings().DictSize()); }
diff --git a/extensions/common/permissions/manifest_permission_set.cc b/extensions/common/permissions/manifest_permission_set.cc index 9670766a..0a9fe98 100644 --- a/extensions/common/permissions/manifest_permission_set.cc +++ b/extensions/common/permissions/manifest_permission_set.cc
@@ -68,7 +68,7 @@ if (!permissions->GetString(i, &permission_name)) { const base::DictionaryValue* dict = NULL; // permission should be a string or a single key dict. - if (!permissions->GetDictionary(i, &dict) || dict->size() != 1) { + if (!permissions->GetDictionary(i, &dict) || dict->DictSize() != 1) { if (error) { *error = ErrorUtils::FormatErrorMessageUTF16( errors::kInvalidPermission, base::NumberToString(i));
diff --git a/extensions/common/stack_frame.cc b/extensions/common/stack_frame.cc index 157492d..9ec229bb 100644 --- a/extensions/common/stack_frame.cc +++ b/extensions/common/stack_frame.cc
@@ -13,7 +13,7 @@ namespace extensions { namespace { -const char16_t kAnonymousFunction[] = u"(anonymous function)"; +const char kAnonymousFunction[] = "(anonymous function)"; } StackFrame::StackFrame() : line_number(1), column_number(1) { @@ -33,7 +33,8 @@ : line_number(line_number), column_number(column_number), source(source), - function(function.empty() ? kAnonymousFunction : function) {} + function(function.empty() ? base::UTF8ToUTF16(kAnonymousFunction) + : function) {} StackFrame::~StackFrame() { }
diff --git a/extensions/renderer/extensions_render_frame_observer.cc b/extensions/renderer/extensions_render_frame_observer.cc index 4adc86c..63e85e3 100644 --- a/extensions/renderer/extensions_render_frame_observer.cc +++ b/extensions/renderer/extensions_render_frame_observer.cc
@@ -26,7 +26,7 @@ namespace { // The delimiter for a stack trace provided by WebKit. -const char16_t kStackFrameDelimiter[] = u"\n at "; +const char kStackFrameDelimiter[] = "\n at "; // Get a stack trace from a WebKit console message. // There are three possible scenarios: @@ -46,16 +46,17 @@ std::vector<std::u16string> pieces; size_t index = 0; - if (message->find(kStackFrameDelimiter) != std::u16string::npos) { - pieces = base::SplitStringUsingSubstr(*message, kStackFrameDelimiter, - base::TRIM_WHITESPACE, - base::SPLIT_WANT_ALL); + if (message->find(base::UTF8ToUTF16(kStackFrameDelimiter)) != + std::u16string::npos) { + pieces = base::SplitStringUsingSubstr( + *message, base::UTF8ToUTF16(kStackFrameDelimiter), + base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); *message = pieces[0]; index = 1; } else if (!stack_trace.empty()) { - pieces = base::SplitStringUsingSubstr(stack_trace, kStackFrameDelimiter, - base::TRIM_WHITESPACE, - base::SPLIT_WANT_ALL); + pieces = base::SplitStringUsingSubstr( + stack_trace, base::UTF8ToUTF16(kStackFrameDelimiter), + base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); } // If we got a stack trace, parse each frame from the text.
diff --git a/gpu/command_buffer/service/external_vk_image_factory_unittest.cc b/gpu/command_buffer/service/external_vk_image_factory_unittest.cc index 26fe5ec..a26df7b 100644 --- a/gpu/command_buffer/service/external_vk_image_factory_unittest.cc +++ b/gpu/command_buffer/service/external_vk_image_factory_unittest.cc
@@ -205,7 +205,8 @@ &begin_semaphores, &end_semaphores); context_state_->gr_context()->wait(begin_semaphores.size(), - begin_semaphores.data()); + begin_semaphores.data(), + /*deleteSemaphoresAfterWait=*/false); EXPECT_TRUE(skia_scoped_access); @@ -291,7 +292,8 @@ gpu::SharedImageRepresentation::AllowUnclearedAccess::kYes); SkSurface* dest_surface = skia_scoped_access->surface(); - dest_surface->wait(begin_semaphores.size(), begin_semaphores.data()); + dest_surface->wait(begin_semaphores.size(), begin_semaphores.data(), + /*deleteSemaphoresAfterWait=*/false); SkCanvas* dest_canvas = dest_surface->getCanvas(); // Color the top half blue, and the bottom half green
diff --git a/ios/chrome/app/BUILD.gn b/ios/chrome/app/BUILD.gn index 193be82..27b3998 100644 --- a/ios/chrome/app/BUILD.gn +++ b/ios/chrome/app/BUILD.gn
@@ -36,7 +36,6 @@ testonly = true sources = [ "app_metrics_app_state_agent_unittest.mm", - "chrome_overlay_window_testing.h", "deferred_initialization_runner_unittest.mm", "main_application_delegate_unittest.mm", "safe_mode_app_state_agent_unittest.mm",
diff --git a/ios/chrome/app/chrome_overlay_window.mm b/ios/chrome/app/chrome_overlay_window.mm index da8fa8da..97aef8a6 100644 --- a/ios/chrome/app/chrome_overlay_window.mm +++ b/ios/chrome/app/chrome_overlay_window.mm
@@ -6,7 +6,6 @@ #include "base/check.h" #import "ios/chrome/browser/crash_report/crash_keys_helper.h" -#import "ios/chrome/browser/metrics/size_class_recorder.h" #import "ios/chrome/browser/metrics/user_interface_style_recorder.h" #import "ios/chrome/browser/ui/util/ui_util.h" @@ -18,11 +17,6 @@ @property(nonatomic, strong) UserInterfaceStyleRecorder* userInterfaceStyleRecorder API_AVAILABLE( ios(13.0)); -@property(nonatomic, strong) SizeClassRecorder* sizeClassRecorder; - -// Initializes the size class recorder. On iPad It starts tracking horizontal -// size class changes. -- (void)initializeSizeClassRecorder; // Updates the Breakpad report with the current size class. - (void)updateBreakpad; @@ -35,7 +29,6 @@ self = [super initWithFrame:frame]; if (self) { // When not created via a nib, create the recorders immediately. - [self initializeSizeClassRecorder]; [self updateBreakpad]; if (@available(iOS 13, *)) { _userInterfaceStyleRecorder = [[UserInterfaceStyleRecorder alloc] @@ -47,20 +40,9 @@ - (void)awakeFromNib { [super awakeFromNib]; - // When creating via a nib, wait to be awoken, as the size class is not - // reliable before. - [self initializeSizeClassRecorder]; [self updateBreakpad]; } -- (void)initializeSizeClassRecorder { - DCHECK(!_sizeClassRecorder); - if (IsIPadIdiom()) { - _sizeClassRecorder = [[SizeClassRecorder alloc] - initWithHorizontalSizeClass:self.traitCollection.horizontalSizeClass]; - } -} - - (void)updateBreakpad { crash_keys::SetCurrentHorizontalSizeClass( self.traitCollection.horizontalSizeClass); @@ -87,8 +69,6 @@ [super traitCollectionDidChange:previousTraitCollection]; if (previousTraitCollection.horizontalSizeClass != self.traitCollection.horizontalSizeClass) { - [_sizeClassRecorder - horizontalSizeClassDidChange:self.traitCollection.horizontalSizeClass]; [self updateBreakpad]; } if (@available(iOS 13, *)) { @@ -102,10 +82,4 @@ } } -#pragma mark - Testing methods - -- (void)unsetSizeClassRecorder { - _sizeClassRecorder = nil; -} - @end
diff --git a/ios/chrome/app/chrome_overlay_window_testing.h b/ios/chrome/app/chrome_overlay_window_testing.h deleted file mode 100644 index 662d1b2a..0000000 --- a/ios/chrome/app/chrome_overlay_window_testing.h +++ /dev/null
@@ -1,16 +0,0 @@ -// Copyright 2016 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. - -#ifndef IOS_CHROME_APP_CHROME_OVERLAY_WINDOW_TESTING_H_ -#define IOS_CHROME_APP_CHROME_OVERLAY_WINDOW_TESTING_H_ - -#import "ios/chrome/app/chrome_overlay_window.h" - -@interface ChromeOverlayWindow (ForTesting) - -// Cleans up the size class recorder of main window for testing. -- (void)unsetSizeClassRecorder; - -@end -#endif // IOS_CHROME_APP_CHROME_OVERLAY_WINDOW_TESTING_H_
diff --git a/ios/chrome/app/main_application_delegate_unittest.mm b/ios/chrome/app/main_application_delegate_unittest.mm index 9f74b5e1..671a03c 100644 --- a/ios/chrome/app/main_application_delegate_unittest.mm +++ b/ios/chrome/app/main_application_delegate_unittest.mm
@@ -8,7 +8,6 @@ #import "base/ios/ios_util.h" #import "base/mac/foundation_util.h" -#import "ios/chrome/app/chrome_overlay_window_testing.h" #include "ios/public/provider/chrome/browser/chrome_browser_provider.h" #include "testing/platform_test.h" #import "third_party/ocmock/OCMock/OCMock.h" @@ -41,13 +40,6 @@ [delegate application:application didFinishLaunchingWithOptions:nil]; [delegate applicationDidEnterBackground:application]; - // Clean up the size class recorder, which is created by the main window via - // a previous call to |application:didFinishLaunchingWithOptions:|, to prevent - // it from interfering with subsequent tests. - ChromeOverlayWindow* mainWindow = - base::mac::ObjCCastStrict<ChromeOverlayWindow>([delegate window]); - [mainWindow unsetSizeClassRecorder]; - // Restore both ChromeBrowserProvider to its original value and destroy // instances created by MainController. DCHECK_NE(ios::GetChromeBrowserProvider(), stashed_chrome_browser_provider);
diff --git a/ios/chrome/app/strings/ios_strings.grd b/ios/chrome/app/strings/ios_strings.grd index bbb01ea..912de401 100644 --- a/ios/chrome/app/strings/ios_strings.grd +++ b/ios/chrome/app/strings/ios_strings.grd
@@ -1310,7 +1310,7 @@ Off </message> <message name="IDS_IOS_OPTIONS_ACCOUNTS_SIGN_OUT_TURN_OFF_SYNC" desc="Title of the button to sign out and turn off sync. [iOS only]"> - Sign out and turn off sync + Sign Out and Turn Off Sync... </message> <message name="IDS_IOS_OPTIONS_ADVANCED_TAB_LABEL" desc="The title of the Advanced section of the Settings page. [Length: 20em] [iOS only]"> Advanced
diff --git a/ios/chrome/app/strings/ios_strings_grd/IDS_IOS_OPTIONS_ACCOUNTS_SIGN_OUT_TURN_OFF_SYNC.png.sha1 b/ios/chrome/app/strings/ios_strings_grd/IDS_IOS_OPTIONS_ACCOUNTS_SIGN_OUT_TURN_OFF_SYNC.png.sha1 new file mode 100644 index 0000000..559cac97 --- /dev/null +++ b/ios/chrome/app/strings/ios_strings_grd/IDS_IOS_OPTIONS_ACCOUNTS_SIGN_OUT_TURN_OFF_SYNC.png.sha1
@@ -0,0 +1 @@ +54bc7b549fe1e2143eab522291f1bb0c8d908d24 \ No newline at end of file
diff --git a/ios/chrome/browser/autofill/personal_data_manager_factory.cc b/ios/chrome/browser/autofill/personal_data_manager_factory.cc index f4745fd..f4e5768 100644 --- a/ios/chrome/browser/autofill/personal_data_manager_factory.cc +++ b/ios/chrome/browser/autofill/personal_data_manager_factory.cc
@@ -68,13 +68,16 @@ std::unique_ptr<PersonalDataManager> service( new PersonalDataManager(GetApplicationContext()->GetApplicationLocale(), GetCountryCodeFromVariations())); - auto autofill_db = + auto local_storage = ios::WebDataServiceFactory::GetAutofillWebDataForBrowserState( chrome_browser_state, ServiceAccessType::EXPLICIT_ACCESS); + auto account_storage = + ios::WebDataServiceFactory::GetAutofillWebDataForAccount( + chrome_browser_state, ServiceAccessType::EXPLICIT_ACCESS); auto* history_service = ios::HistoryServiceFactory::GetForBrowserState( chrome_browser_state, ServiceAccessType::EXPLICIT_ACCESS); service->Init( - autofill_db, nullptr, chrome_browser_state->GetPrefs(), + local_storage, account_storage, chrome_browser_state->GetPrefs(), GetApplicationContext()->GetLocalState(), IdentityManagerFactory::GetForBrowserState(chrome_browser_state), AutofillProfileValidatorFactory::GetInstance(), history_service,
diff --git a/ios/chrome/browser/discover_feed/discover_feed_service.h b/ios/chrome/browser/discover_feed/discover_feed_service.h index 8ebbf1f0..bedd3ac 100644 --- a/ios/chrome/browser/discover_feed/discover_feed_service.h +++ b/ios/chrome/browser/discover_feed/discover_feed_service.h
@@ -5,12 +5,12 @@ #ifndef IOS_CHROME_BROWSER_DISCOVER_FEED_DISCOVER_FEED_SERVICE_H_ #define IOS_CHROME_BROWSER_DISCOVER_FEED_DISCOVER_FEED_SERVICE_H_ +#include "base/scoped_observation.h" #include "components/keyed_service/core/keyed_service.h" #include "components/signin/public/identity_manager/identity_manager.h" class ChromeBrowserState; @class DiscoverFeedMetricsRecorder; -class DiscoverFeedProvider; // A browser-context keyed service that is used to keep the Discover Feed data // up to date. @@ -18,7 +18,7 @@ public signin::IdentityManager::Observer { public: // Initializes the service. - DiscoverFeedService(ChromeBrowserState* browser_state); + explicit DiscoverFeedService(ChromeBrowserState* browser_state); ~DiscoverFeedService() override; // Returns the FeedMetricsRecorder to be used by the Feed, a single instance @@ -33,14 +33,13 @@ void OnPrimaryAccountChanged( const signin::PrimaryAccountChangeEvent& event) override; - // Identity manager to observe. - signin::IdentityManager* identity_manager_; - - // Discover Feed provider to notify of changes. - DiscoverFeedProvider* discover_feed_provider_; + // Helper to track registration as an signin::IdentityManager::Observer. + base::ScopedObservation<signin::IdentityManager, + signin::IdentityManager::Observer> + identity_manager_observation_{this}; // Metrics recorder for the DiscoverFeed. - DiscoverFeedMetricsRecorder* discover_feed_metrics_recorder_; + __strong DiscoverFeedMetricsRecorder* discover_feed_metrics_recorder_ = nil; DISALLOW_COPY_AND_ASSIGN(DiscoverFeedService); };
diff --git a/ios/chrome/browser/discover_feed/discover_feed_service.mm b/ios/chrome/browser/discover_feed/discover_feed_service.mm index 30cf3f43..80a5c93 100644 --- a/ios/chrome/browser/discover_feed/discover_feed_service.mm +++ b/ios/chrome/browser/discover_feed/discover_feed_service.mm
@@ -17,20 +17,22 @@ #endif DiscoverFeedService::DiscoverFeedService(ChromeBrowserState* browser_state) { - discover_feed_provider_ = - ios::GetChromeBrowserProvider()->GetDiscoverFeedProvider(); - identity_manager_ = IdentityManagerFactory::GetForBrowserState(browser_state); - if (identity_manager_) { - identity_manager_->AddObserver(this); - } + signin::IdentityManager* identity_manager = + IdentityManagerFactory::GetForBrowserState(browser_state); + if (identity_manager) + identity_manager_observation_.Observe(identity_manager); discover_feed_metrics_recorder_ = [[DiscoverFeedMetricsRecorder alloc] init]; DiscoverFeedConfiguration* discover_config = [[DiscoverFeedConfiguration alloc] init]; discover_config.browserState = browser_state; + discover_config.authService = + AuthenticationServiceFactory::GetForBrowserState(browser_state); + discover_config.prefService = browser_state->GetPrefs(); discover_config.metricsRecorder = discover_feed_metrics_recorder_; - discover_feed_provider_->StartFeed(discover_config); + ios::GetChromeBrowserProvider()->GetDiscoverFeedProvider()->StartFeed( + discover_config); } DiscoverFeedService::~DiscoverFeedService() {} @@ -41,14 +43,17 @@ } void DiscoverFeedService::Shutdown() { - if (identity_manager_) { - identity_manager_->RemoveObserver(this); - } + identity_manager_observation_.Reset(); + // Stop the Discover feed to disconnects its services. ios::GetChromeBrowserProvider()->GetDiscoverFeedProvider()->StopFeed(); + + discover_feed_metrics_recorder_ = nil; } void DiscoverFeedService::OnPrimaryAccountChanged( const signin::PrimaryAccountChangeEvent& event) { - discover_feed_provider_->UpdateFeedForAccountChange(); + ios::GetChromeBrowserProvider() + ->GetDiscoverFeedProvider() + ->UpdateFeedForAccountChange(); }
diff --git a/ios/chrome/browser/flags/about_flags.mm b/ios/chrome/browser/flags/about_flags.mm index 77e94e8..22610d6 100644 --- a/ios/chrome/browser/flags/about_flags.mm +++ b/ios/chrome/browser/flags/about_flags.mm
@@ -739,6 +739,13 @@ flag_descriptions::kUpdateHistoryEntryPointsInIncognitoDescription, flags_ui::kOsIos, FEATURE_VALUE_TYPE(kUpdateHistoryEntryPointsInIncognito)}, + {"enable-autofill-account-wallet-storage", + flag_descriptions::kEnableAutofillAccountWalletStorageName, + flag_descriptions::kEnableAutofillAccountWalletStorageDescription, + flags_ui::kOsIos, + FEATURE_VALUE_TYPE( + autofill::features::kAutofillEnableAccountWalletStorage)}, + }; bool SkipConditionalFeatureEntry(const flags_ui::FeatureEntry& entry) {
diff --git a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc index add5970a..63b45ee 100644 --- a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc +++ b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc
@@ -160,6 +160,11 @@ "Enable iOS_TBA instant session restoration for faster and more " "web session restoration."; +const char kEnableAutofillAccountWalletStorageName[] = + "Enable the account data storage for autofill"; +const char kEnableAutofillAccountWalletStorageDescription[] = + "Enable the ephemeral storage for account data for autofill."; + const char kEnableAutofillAddressSavePromptName[] = "Autofill Address Save Prompts"; const char kEnableAutofillAddressSavePromptDescription[] =
diff --git a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h index 95f99d17..4f932ade 100644 --- a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h +++ b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h
@@ -143,6 +143,9 @@ extern const char kRestoreSessionFromCacheName[]; extern const char kRestoreSessionFromCacheDescription[]; +extern const char kEnableAutofillAccountWalletStorageName[]; +extern const char kEnableAutofillAccountWalletStorageDescription[]; + // Title and description for the flag to enable autofill address save prompts. extern const char kEnableAutofillAddressSavePromptName[]; extern const char kEnableAutofillAddressSavePromptDescription[];
diff --git a/ios/chrome/browser/metrics/BUILD.gn b/ios/chrome/browser/metrics/BUILD.gn index abbdb79..81b11136 100644 --- a/ios/chrome/browser/metrics/BUILD.gn +++ b/ios/chrome/browser/metrics/BUILD.gn
@@ -182,9 +182,6 @@ "first_user_action_recorder.h", "new_tab_page_uma.h", "new_tab_page_uma.mm", - "size_class_recorder.h", - "size_class_recorder.mm", - "size_class_recorder_private.h", "user_interface_style_recorder.h", "user_interface_style_recorder.mm", ] @@ -219,7 +216,6 @@ testonly = true sources = [ "first_user_action_recorder_unittest.cc", - "size_class_recorder_unittest.mm", "tab_usage_recorder_browser_agent_unittest.mm", ] deps = [
diff --git a/ios/chrome/browser/metrics/size_class_recorder.h b/ios/chrome/browser/metrics/size_class_recorder.h deleted file mode 100644 index 1932ebb7d..0000000 --- a/ios/chrome/browser/metrics/size_class_recorder.h +++ /dev/null
@@ -1,28 +0,0 @@ -// Copyright 2015 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. - -#ifndef IOS_CHROME_BROWSER_METRICS_SIZE_CLASS_RECORDER_H_ -#define IOS_CHROME_BROWSER_METRICS_SIZE_CLASS_RECORDER_H_ - -#import <UIKit/UIKit.h> - -// Reports metrics for the size classes uses on iPad iOS 9+. -@interface SizeClassRecorder : NSObject - -- (instancetype)initWithHorizontalSizeClass:(UIUserInterfaceSizeClass)sizeClass - NS_DESIGNATED_INITIALIZER; - -- (instancetype)init NS_UNAVAILABLE; - -// Call this method upon horizontal size class changes to report the used size -// class to UMA. It will be reported under Tab.HorizontalSizeClassUsed. -- (void)horizontalSizeClassDidChange:(UIUserInterfaceSizeClass)newSizeClass; - -// Call this class method when a page has loaded to record the size class at -// that time. It will be reported inder Tab.PageLoadInHorizontalSizeClass. -+ (void)pageLoadedWithHorizontalSizeClass:(UIUserInterfaceSizeClass)sizeClass; - -@end - -#endif // IOS_CHROME_BROWSER_METRICS_SIZE_CLASS_RECORDER_H_
diff --git a/ios/chrome/browser/metrics/size_class_recorder.mm b/ios/chrome/browser/metrics/size_class_recorder.mm deleted file mode 100644 index f3a112c..0000000 --- a/ios/chrome/browser/metrics/size_class_recorder.mm +++ /dev/null
@@ -1,121 +0,0 @@ -// Copyright 2015 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. - -#import "ios/chrome/browser/metrics/size_class_recorder.h" -#import "ios/chrome/browser/metrics/size_class_recorder_private.h" - -#include "base/check.h" -#include "base/metrics/histogram_macros.h" -#import "ios/chrome/browser/ui/util/ui_util.h" - -#if !defined(__has_feature) || !__has_feature(objc_arc) -#error "This file requires ARC support." -#endif - -// Converts a UIKit size class to a size class for reporting. -SizeClassForReporting SizeClassForReportingForUIUserInterfaceSizeClass( - UIUserInterfaceSizeClass sizeClass) { - switch (sizeClass) { - case UIUserInterfaceSizeClassUnspecified: - return SizeClassForReporting::UNSPECIFIED; - case UIUserInterfaceSizeClassCompact: - return SizeClassForReporting::COMPACT; - case UIUserInterfaceSizeClassRegular: - return SizeClassForReporting::REGULAR; - } -} - -namespace { - -// Reports the currently used horizontal size class. -void ReportHorizontalSizeClassUsed(UIUserInterfaceSizeClass sizeClass) { - SizeClassForReporting sizeClassForReporting = - SizeClassForReportingForUIUserInterfaceSizeClass(sizeClass); - UMA_HISTOGRAM_ENUMERATION("Tab.HorizontalSizeClassUsed", - sizeClassForReporting, - SizeClassForReporting::COUNT); -} - -} // namespace - -@interface SizeClassRecorder () -@property(nonatomic, assign) BOOL applicationInBackground; -@property(nonatomic, assign) UIUserInterfaceSizeClass initialSizeClass; -@end - -@implementation SizeClassRecorder - -@synthesize applicationInBackground = _applicationInBackground; -@synthesize initialSizeClass = _initialSizeClass; - -- (instancetype)initWithHorizontalSizeClass: - (UIUserInterfaceSizeClass)sizeClass { - // Size classes change tracking is only available on iPad devices. - DCHECK(IsIPadIdiom()); - self = [super init]; - if (self) { - // Store the initial size class for reporting after the application did - // become active. Otherwise, if this initializer is called before the - // metrics service is started, reporting metrics will fail for the entire - // session. - _initialSizeClass = sizeClass; - [[NSNotificationCenter defaultCenter] - addObserver:self - selector:@selector(applicationDidBecomeActive:) - name:UIApplicationDidBecomeActiveNotification - object:nil]; - [[NSNotificationCenter defaultCenter] - addObserver:self - selector:@selector(applicationDidEnterBackground:) - name:UIApplicationDidEnterBackgroundNotification - object:nil]; - [[NSNotificationCenter defaultCenter] - addObserver:self - selector:@selector(applicationWillEnterForeground:) - name:UIApplicationWillEnterForegroundNotification - object:nil]; - } - return self; -} - -- (void)horizontalSizeClassDidChange:(UIUserInterfaceSizeClass)newSizeClass { - // iOS sometimes changes from Compact to Regular to Compact again when putting - // the application in the background, to update the application screenshot. - // Ignore those changes. - if (self.applicationInBackground) - return; - ReportHorizontalSizeClassUsed(newSizeClass); -} - -+ (void)pageLoadedWithHorizontalSizeClass:(UIUserInterfaceSizeClass)sizeClass { - SizeClassForReporting sizeClassForReporting = - SizeClassForReporting(sizeClass); - UMA_HISTOGRAM_ENUMERATION("Tab.PageLoadInHorizontalSizeClass", - sizeClassForReporting, - SizeClassForReporting::COUNT); -} - -#pragma mark - Application state notifications handlers - -- (void)applicationDidBecomeActive:(NSNotification*)notification { - // This is only needed to report the initial size class. Deregister from this - // notification on the first time it is received. - [[NSNotificationCenter defaultCenter] - removeObserver:self - name:UIApplicationDidBecomeActiveNotification - object:nil]; - ReportHorizontalSizeClassUsed(self.initialSizeClass); - // For good measure, set the initial size class to unspecified. - self.initialSizeClass = UIUserInterfaceSizeClassUnspecified; -} - -- (void)applicationDidEnterBackground:(NSNotification*)notification { - self.applicationInBackground = YES; -} - -- (void)applicationWillEnterForeground:(NSNotification*)notification { - self.applicationInBackground = NO; -} - -@end
diff --git a/ios/chrome/browser/metrics/size_class_recorder_private.h b/ios/chrome/browser/metrics/size_class_recorder_private.h deleted file mode 100644 index b1bdd13..0000000 --- a/ios/chrome/browser/metrics/size_class_recorder_private.h +++ /dev/null
@@ -1,21 +0,0 @@ -// Copyright 2015 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. - -#ifndef IOS_CHROME_BROWSER_METRICS_SIZE_CLASS_RECORDER_PRIVATE_H_ -#define IOS_CHROME_BROWSER_METRICS_SIZE_CLASS_RECORDER_PRIVATE_H_ - -// Reported size classes. -enum class SizeClassForReporting { - UNSPECIFIED = 0, - COMPACT, - REGULAR, - // NOTE: add new size classes above this line. - COUNT -}; - -// Converts a UIKit size class to a size class for reporting. -SizeClassForReporting SizeClassForReportingForUIUserInterfaceSizeClass( - UIUserInterfaceSizeClass sizeClass); - -#endif // IOS_CHROME_BROWSER_METRICS_SIZE_CLASS_RECORDER_PRIVATE_H_
diff --git a/ios/chrome/browser/metrics/size_class_recorder_unittest.mm b/ios/chrome/browser/metrics/size_class_recorder_unittest.mm deleted file mode 100644 index 470ccef..0000000 --- a/ios/chrome/browser/metrics/size_class_recorder_unittest.mm +++ /dev/null
@@ -1,215 +0,0 @@ -// Copyright 2015 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. - -#import "ios/chrome/browser/metrics/size_class_recorder.h" -#import "ios/chrome/browser/metrics/size_class_recorder_private.h" - -#include <memory> - -#include "base/test/metrics/histogram_tester.h" -#import "ios/chrome/browser/ui/util/ui_util.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "testing/platform_test.h" - -#if !defined(__has_feature) || !__has_feature(objc_arc) -#error "This file requires ARC support." -#endif - -namespace { - -const char kSizeClassUsedHistogramName[] = "Tab.HorizontalSizeClassUsed"; - -const char kPageLoadSizeClassHistogramName[] = - "Tab.PageLoadInHorizontalSizeClass"; - -class SizeClassRecorderTest : public PlatformTest { - protected: - void SetUp() override { - PlatformTest::SetUp(); - histogram_tester_.reset(new base::HistogramTester()); - } - - SizeClassRecorder* recorder_; - std::unique_ptr<base::HistogramTester> histogram_tester_; -}; - -TEST_F(SizeClassRecorderTest, Initialization_SizeClassUnspecified) { - // SizeClassRecoder is only available on iPad devices. - if (!IsIPadIdiom()) - return; - - recorder_ = [[SizeClassRecorder alloc] - initWithHorizontalSizeClass:UIUserInterfaceSizeClassUnspecified]; - recorder_ = nil; - - histogram_tester_->ExpectTotalCount(kSizeClassUsedHistogramName, 0); - histogram_tester_->ExpectTotalCount(kPageLoadSizeClassHistogramName, 0); -} - -TEST_F(SizeClassRecorderTest, Initialization_SizeClassCompact) { - // SizeClassRecoder is only available on iPad devices. - if (!IsIPadIdiom()) - return; - - recorder_ = [[SizeClassRecorder alloc] - initWithHorizontalSizeClass:UIUserInterfaceSizeClassCompact]; - recorder_ = nil; - - histogram_tester_->ExpectTotalCount(kSizeClassUsedHistogramName, 0); - histogram_tester_->ExpectTotalCount(kPageLoadSizeClassHistogramName, 0); -} - -TEST_F(SizeClassRecorderTest, Initialization_SizeClassRegular) { - // SizeClassRecoder is only available on iPad devices. - if (!IsIPadIdiom()) - return; - - recorder_ = [[SizeClassRecorder alloc] - initWithHorizontalSizeClass:UIUserInterfaceSizeClassRegular]; - recorder_ = nil; - - histogram_tester_->ExpectTotalCount(kSizeClassUsedHistogramName, 0); - histogram_tester_->ExpectTotalCount(kPageLoadSizeClassHistogramName, 0); -} - -TEST_F(SizeClassRecorderTest, RecordInitialSizeClassOnAppBecomeActive) { - // SizeClassRecoder is only available on iPad devices. - if (!IsIPadIdiom()) - return; - - recorder_ = [[SizeClassRecorder alloc] - initWithHorizontalSizeClass:UIUserInterfaceSizeClassCompact]; - [[NSNotificationCenter defaultCenter] - postNotificationName:UIApplicationDidBecomeActiveNotification - object:nil]; - - histogram_tester_->ExpectUniqueSample( - kSizeClassUsedHistogramName, - static_cast<int>(SizeClassForReporting::COMPACT), 1); - histogram_tester_->ExpectTotalCount(kPageLoadSizeClassHistogramName, 0); -} - -TEST_F(SizeClassRecorderTest, - DontRecordInitialSizeClassSubsequentAppBecomeActive) { - // SizeClassRecoder is only available on iPad devices. - if (!IsIPadIdiom()) - return; - - recorder_ = [[SizeClassRecorder alloc] - initWithHorizontalSizeClass:UIUserInterfaceSizeClassCompact]; - [[NSNotificationCenter defaultCenter] - postNotificationName:UIApplicationDidBecomeActiveNotification - object:nil]; - [[NSNotificationCenter defaultCenter] - postNotificationName:UIApplicationDidBecomeActiveNotification - object:nil]; - - histogram_tester_->ExpectUniqueSample( - kSizeClassUsedHistogramName, - static_cast<int>(SizeClassForReporting::COMPACT), 1); - histogram_tester_->ExpectTotalCount(kPageLoadSizeClassHistogramName, 0); -} - -TEST_F(SizeClassRecorderTest, RecordSizeClassChangeInForeground) { - // SizeClassRecoder is only available on iPad devices. - if (!IsIPadIdiom()) - return; - - recorder_ = [[SizeClassRecorder alloc] - initWithHorizontalSizeClass:UIUserInterfaceSizeClassUnspecified]; - [recorder_ horizontalSizeClassDidChange:UIUserInterfaceSizeClassRegular]; - - histogram_tester_->ExpectUniqueSample( - kSizeClassUsedHistogramName, - static_cast<int>(SizeClassForReporting::REGULAR), 1); - histogram_tester_->ExpectTotalCount(kPageLoadSizeClassHistogramName, 0); -} - -TEST_F(SizeClassRecorderTest, DontRecordSizeClassChangeInBackground) { - // SizeClassRecoder is only available on iPad devices. - if (!IsIPadIdiom()) - return; - - recorder_ = [[SizeClassRecorder alloc] - initWithHorizontalSizeClass:UIUserInterfaceSizeClassUnspecified]; - [[NSNotificationCenter defaultCenter] - postNotificationName:UIApplicationDidEnterBackgroundNotification - object:nil]; - [recorder_ horizontalSizeClassDidChange:UIUserInterfaceSizeClassRegular]; - - histogram_tester_->ExpectTotalCount(kSizeClassUsedHistogramName, 0); - histogram_tester_->ExpectTotalCount(kPageLoadSizeClassHistogramName, 0); -} - -TEST_F(SizeClassRecorderTest, - RecordSizeClassChangeInForegroundAfterBackground) { - // SizeClassRecoder is only available on iPad devices. - if (!IsIPadIdiom()) - return; - - recorder_ = [[SizeClassRecorder alloc] - initWithHorizontalSizeClass:UIUserInterfaceSizeClassUnspecified]; - [[NSNotificationCenter defaultCenter] - postNotificationName:UIApplicationDidEnterBackgroundNotification - object:nil]; - [[NSNotificationCenter defaultCenter] - postNotificationName:UIApplicationWillEnterForegroundNotification - object:nil]; - [recorder_ horizontalSizeClassDidChange:UIUserInterfaceSizeClassCompact]; - - histogram_tester_->ExpectUniqueSample( - kSizeClassUsedHistogramName, - static_cast<int>(SizeClassForReporting::COMPACT), 1); - histogram_tester_->ExpectTotalCount(kPageLoadSizeClassHistogramName, 0); -} - -TEST_F(SizeClassRecorderTest, RecordSizeClassOnPageLoaded_Unspecified) { - // SizeClassRecoder is only available on iPad devices. - if (!IsIPadIdiom()) - return; - - recorder_ = [[SizeClassRecorder alloc] - initWithHorizontalSizeClass:UIUserInterfaceSizeClassUnspecified]; - [[recorder_ class] - pageLoadedWithHorizontalSizeClass:UIUserInterfaceSizeClassUnspecified]; - - histogram_tester_->ExpectTotalCount(kSizeClassUsedHistogramName, 0); - histogram_tester_->ExpectUniqueSample( - kPageLoadSizeClassHistogramName, - static_cast<int>(SizeClassForReporting::UNSPECIFIED), 1); -} - -TEST_F(SizeClassRecorderTest, RecordSizeClassOnPageLoaded_Compact) { - // SizeClassRecoder is only available on iPad devices. - if (!IsIPadIdiom()) - return; - - recorder_ = [[SizeClassRecorder alloc] - initWithHorizontalSizeClass:UIUserInterfaceSizeClassUnspecified]; - [[recorder_ class] - pageLoadedWithHorizontalSizeClass:UIUserInterfaceSizeClassCompact]; - - histogram_tester_->ExpectTotalCount(kSizeClassUsedHistogramName, 0); - histogram_tester_->ExpectUniqueSample( - kPageLoadSizeClassHistogramName, - static_cast<int>(SizeClassForReporting::COMPACT), 1); -} - -TEST_F(SizeClassRecorderTest, RecordSizeClassOnPageLoaded_Regular) { - // SizeClassRecoder is only available on iPad devices. - if (!IsIPadIdiom()) - return; - - recorder_ = [[SizeClassRecorder alloc] - initWithHorizontalSizeClass:UIUserInterfaceSizeClassUnspecified]; - [[recorder_ class] - pageLoadedWithHorizontalSizeClass:UIUserInterfaceSizeClassRegular]; - - histogram_tester_->ExpectTotalCount(kSizeClassUsedHistogramName, 0); - histogram_tester_->ExpectUniqueSample( - kPageLoadSizeClassHistogramName, - static_cast<int>(SizeClassForReporting::REGULAR), 1); -} - -} // namespace
diff --git a/ios/chrome/browser/passwords/well_known_change_password_tab_helper_unittest.mm b/ios/chrome/browser/passwords/well_known_change_password_tab_helper_unittest.mm index 7a01eca7a..e025bbf 100644 --- a/ios/chrome/browser/passwords/well_known_change_password_tab_helper_unittest.mm +++ b/ios/chrome/browser/passwords/well_known_change_password_tab_helper_unittest.mm
@@ -13,15 +13,15 @@ #include "components/password_manager/core/browser/well_known_change_password_util.h" #include "components/password_manager/core/common/password_manager_features.h" #include "components/ukm/test_ukm_recorder.h" +#include "ios/chrome/browser/browser_state/test_chrome_browser_state.h" #include "ios/chrome/browser/passwords/ios_chrome_affiliation_service_factory.h" #include "ios/chrome/browser/passwords/ios_chrome_change_password_url_service_factory.h" +#include "ios/chrome/browser/web/chrome_web_test.h" #import "ios/web/public/navigation/navigation_manager.h" #import "ios/web/public/test/fakes/fake_web_client.h" #import "ios/web/public/test/fakes/fake_web_state_delegate.h" #import "ios/web/public/test/navigation_test_util.h" #include "ios/web/public/test/web_task_environment.h" -#include "ios/web/public/test/web_test.h" -#include "ios/web/public/test/web_test_with_web_state.h" #import "ios/web/public/test/web_view_content_test_util.h" #include "net/cert/x509_certificate.h" #include "net/http/http_status_code.h" @@ -31,7 +31,6 @@ #include "services/metrics/public/cpp/ukm_builders.h" #include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h" #include "services/network/test/test_url_loader_factory.h" -#include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #if !defined(__has_feature) || !__has_feature(objc_arc) @@ -116,13 +115,14 @@ // This test uses a mockserver to simulate different response. To handle the // url_loader requests we also mock the response for the url_loader_factory. class WellKnownChangePasswordTabHelperTest - : public web::FakeWebClient, - public web::WebTestWithWebState, + : public ChromeWebTest, public ::testing::WithParamInterface<bool> { public: using UkmBuilder = ukm::builders::PasswordManager_WellKnownChangePasswordResult; - WellKnownChangePasswordTabHelperTest() { + WellKnownChangePasswordTabHelperTest() + : ChromeWebTest(std::make_unique<web::FakeWebClient>(), + web::WebTaskEnvironment::Options::IO_MAINLOOP) { test_server_->RegisterRequestHandler(base::BindRepeating( &WellKnownChangePasswordTabHelperTest::HandleRequest, base::Unretained(this))); @@ -137,7 +137,7 @@ } void SetUp() override { - web::WebTestWithWebState::SetUp(); + ChromeWebTest::SetUp(); EXPECT_TRUE(test_server_->InitializeAndListen()); test_server_->StartAcceptingConnections(); @@ -164,7 +164,7 @@ web_state()->SetDelegate(&delegate_); password_manager::WellKnownChangePasswordTabHelper::CreateForWebState( web_state()); - SetSharedURLLoaderFactory( + chrome_browser_state_->SetSharedURLLoaderFactory( base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>( &test_url_loader_factory_)); test_recorder_ = std::make_unique<ukm::TestAutoSetUkmRecorder>();
diff --git a/ios/chrome/browser/prefs/browser_prefs.mm b/ios/chrome/browser/prefs/browser_prefs.mm index 9747d2f..f22d914 100644 --- a/ios/chrome/browser/prefs/browser_prefs.mm +++ b/ios/chrome/browser/prefs/browser_prefs.mm
@@ -166,6 +166,8 @@ false); registry->RegisterTimePref(enterprise_reporting::kLastUploadTimestamp, base::Time()); + registry->RegisterTimePref( + enterprise_reporting::kLastUploadSucceededTimestamp, base::Time()); registry->RegisterIntegerPref(kOmniboxGeolocationAuthorizationState, 0); registry->RegisterStringPref(kOmniboxGeolocationLastAuthorizationAlertVersion,
diff --git a/ios/chrome/browser/ui/autofill/chrome_autofill_client_ios.h b/ios/chrome/browser/ui/autofill/chrome_autofill_client_ios.h index 2f531f7..392e9ec3 100644 --- a/ios/chrome/browser/ui/autofill/chrome_autofill_client_ios.h +++ b/ios/chrome/browser/ui/autofill/chrome_autofill_client_ios.h
@@ -95,6 +95,7 @@ void ConfirmSaveAddressProfile( const AutofillProfile& profile, const AutofillProfile* original_profile, + SaveAddressProfilePromptOptions options, AddressProfileSavePromptCallback callback) override; bool HasCreditCardScanFeature() override; void ScanCreditCard(CreditCardScanCallback callback) override;
diff --git a/ios/chrome/browser/ui/autofill/chrome_autofill_client_ios.mm b/ios/chrome/browser/ui/autofill/chrome_autofill_client_ios.mm index 9de2b774..6c1d880b 100644 --- a/ios/chrome/browser/ui/autofill/chrome_autofill_client_ios.mm +++ b/ios/chrome/browser/ui/autofill/chrome_autofill_client_ios.mm
@@ -324,10 +324,12 @@ void ChromeAutofillClientIOS::ConfirmSaveAddressProfile( const AutofillProfile& profile, const AutofillProfile* original_profile, + SaveAddressProfilePromptOptions options, AddressProfileSavePromptCallback callback) { DCHECK(base::FeatureList::IsEnabled( features::kAutofillAddressProfileSavePrompt)); if (IsInfobarOverlayUIEnabled()) { + // TODO(crbug.com/1167062): Respect SaveAddressProfilePromptOptions. auto delegate = std::make_unique<AutofillSaveUpdateAddressProfileDelegateIOS>( profile, original_profile, std::move(callback));
diff --git a/ios/chrome/browser/ui/browser_view/browser_view_controller.mm b/ios/chrome/browser/ui/browser_view/browser_view_controller.mm index b503820..1ac7c92 100644 --- a/ios/chrome/browser/ui/browser_view/browser_view_controller.mm +++ b/ios/chrome/browser/ui/browser_view/browser_view_controller.mm
@@ -44,7 +44,6 @@ #import "ios/chrome/browser/language/url_language_histogram_factory.h" #import "ios/chrome/browser/main/browser.h" #import "ios/chrome/browser/metrics/new_tab_page_uma.h" -#import "ios/chrome/browser/metrics/size_class_recorder.h" #import "ios/chrome/browser/metrics/tab_usage_recorder_browser_agent.h" #import "ios/chrome/browser/ntp/new_tab_page_tab_helper.h" #import "ios/chrome/browser/ntp/new_tab_page_tab_helper_delegate.h" @@ -3987,12 +3986,6 @@ } - (void)webState:(web::WebState*)webState didLoadPageWithSuccess:(BOOL)success { - if ([self canShowTabStrip]) { - UIUserInterfaceSizeClass sizeClass = - self.view.window.traitCollection.horizontalSizeClass; - [SizeClassRecorder pageLoadedWithHorizontalSizeClass:sizeClass]; - } - // If there is no first responder, try to make the webview or the NTP first // responder to have it answer keyboard commands (e.g. space bar to scroll). if (!GetFirstResponder() && self.currentWebState) {
diff --git a/ios/chrome/browser/ui/settings/google_services/manage_sync_settings_command_handler.h b/ios/chrome/browser/ui/settings/google_services/manage_sync_settings_command_handler.h index aa599976..401bb64e 100644 --- a/ios/chrome/browser/ui/settings/google_services/manage_sync_settings_command_handler.h +++ b/ios/chrome/browser/ui/settings/google_services/manage_sync_settings_command_handler.h
@@ -5,8 +5,6 @@ #ifndef IOS_CHROME_BROWSER_UI_SETTINGS_GOOGLE_SERVICES_MANAGE_SYNC_SETTINGS_COMMAND_HANDLER_H_ #define IOS_CHROME_BROWSER_UI_SETTINGS_GOOGLE_SERVICES_MANAGE_SYNC_SETTINGS_COMMAND_HANDLER_H_ -#import <UIKit/UIKit.h> - // Protocol to communicate user actions from the mediator to its coordinator. @protocol ManageSyncSettingsCommandHandler <NSObject> @@ -16,6 +14,9 @@ // Opens the "Data from Chrome sync" web page. - (void)openDataFromChromeSyncWebPage; +// Presents the data options available when turning off Sync. +- (void)showTurnOffSyncOptions; + @end #endif // IOS_CHROME_BROWSER_UI_SETTINGS_GOOGLE_SERVICES_MANAGE_SYNC_SETTINGS_COMMAND_HANDLER_H_
diff --git a/ios/chrome/browser/ui/settings/google_services/manage_sync_settings_constants.h b/ios/chrome/browser/ui/settings/google_services/manage_sync_settings_constants.h index cc80fe5..7bebd50 100644 --- a/ios/chrome/browser/ui/settings/google_services/manage_sync_settings_constants.h +++ b/ios/chrome/browser/ui/settings/google_services/manage_sync_settings_constants.h
@@ -19,6 +19,8 @@ typedef NS_ENUM(NSInteger, SyncSettingsSectionIdentifier) { // Section for all the sync settings. SyncDataTypeSectionIdentifier = kSectionIdentifierEnumZero, + // Sign out options. + SignOutSectionIdentifier, // Advanced settings. AdvancedSettingsSectionIdentifier, // Sync errors. @@ -47,6 +49,8 @@ SettingsDataTypeItemType, // Item for kAutofillWalletImportEnabled. AutocompleteWalletItemType, + // Sign out item, + SignOutItemType, // AdvancedSettingsSectionIdentifier section. // Encryption item. EncryptionItemType,
diff --git a/ios/chrome/browser/ui/settings/google_services/manage_sync_settings_coordinator.mm b/ios/chrome/browser/ui/settings/google_services/manage_sync_settings_coordinator.mm index ecaa8bb..f1da366 100644 --- a/ios/chrome/browser/ui/settings/google_services/manage_sync_settings_coordinator.mm +++ b/ios/chrome/browser/ui/settings/google_services/manage_sync_settings_coordinator.mm
@@ -21,7 +21,9 @@ #include "ios/chrome/browser/sync/sync_observer_bridge.h" #include "ios/chrome/browser/sync/sync_setup_service.h" #include "ios/chrome/browser/sync/sync_setup_service_factory.h" +#import "ios/chrome/browser/ui/alert_coordinator/action_sheet_coordinator.h" #import "ios/chrome/browser/ui/authentication/authentication_flow.h" +#import "ios/chrome/browser/ui/authentication/authentication_ui_util.h" #import "ios/chrome/browser/ui/commands/application_commands.h" #import "ios/chrome/browser/ui/commands/browsing_data_commands.h" #import "ios/chrome/browser/ui/commands/command_dispatcher.h" @@ -75,6 +77,8 @@ // be dismissed and the sync setup flag should not be marked as done. The sync // should be kept undecided, not marked as disabled. @property(nonatomic, assign) BOOL signinInterrupted; +// Displays the sign-out options for a syncing user. +@property(nonatomic, strong) ActionSheetCoordinator* signOutCoordinator; @end @@ -235,6 +239,19 @@ [handler closeSettingsUIAndOpenURL:command]; } +- (void)showTurnOffSyncOptions { + __weak ManageSyncSettingsCoordinator* weakSelf = self; + SignoutActionSheetCoordinatorCompletion completion = + ^(SignoutActionSheetCoordinatorResult result) { + if (result != SignoutActionSheetCoordinatorResultCanceled) { + [weakSelf closeManageSyncSettings]; + } + }; + self.signOutCoordinator = SignoutActionSheetCoordinator( + self.viewController, self.browser, self.viewController.view, completion); + [self.signOutCoordinator start]; +} + #pragma mark - SyncErrorSettingsCommandHandler - (void)openPassphraseDialog {
diff --git a/ios/chrome/browser/ui/settings/google_services/manage_sync_settings_mediator.mm b/ios/chrome/browser/ui/settings/google_services/manage_sync_settings_mediator.mm index 0b5e610..6f7a4d3ea 100644 --- a/ios/chrome/browser/ui/settings/google_services/manage_sync_settings_mediator.mm +++ b/ios/chrome/browser/ui/settings/google_services/manage_sync_settings_mediator.mm
@@ -29,6 +29,7 @@ #import "ios/chrome/browser/ui/table_view/cells/table_view_cells_constants.h" #import "ios/chrome/browser/ui/table_view/cells/table_view_image_item.h" #import "ios/chrome/browser/ui/table_view/cells/table_view_item.h" +#include "ios/chrome/browser/ui/table_view/cells/table_view_text_item.h" #import "ios/chrome/browser/ui/util/uikit_ui_util.h" #import "ios/chrome/common/ui/colors/UIColor+cr_semantic_colors.h" #import "ios/chrome/common/ui/colors/semantic_color_names.h" @@ -296,6 +297,30 @@ } } +#pragma mark - Loads sign out section + +- (void)loadSignOutSection { + // The sign-out section will only apply to kMobileIdentityConsistency. + if (!base::FeatureList::IsEnabled(signin::kMobileIdentityConsistency)) { + return; + } + + // The user must be signed-in and syncing. + if (!self.isAuthenticated || !self.syncSetupService->IsSyncEnabled()) { + return; + } + + TableViewModel* model = self.consumer.tableViewModel; + [model addSectionWithIdentifier:SignOutSectionIdentifier]; + + TableViewTextItem* signOutItem = + [[TableViewTextItem alloc] initWithType:SignOutItemType]; + signOutItem.text = + GetNSString(IDS_IOS_OPTIONS_ACCOUNTS_SIGN_OUT_TURN_OFF_SYNC); + signOutItem.textColor = [UIColor colorNamed:kRedColor]; + [model addItem:signOutItem toSectionWithIdentifier:SignOutSectionIdentifier]; +} + #pragma mark - Private // Creates a SyncSwitchItem instance. @@ -387,6 +412,7 @@ DCHECK_EQ(self.consumer, controller); [self loadSyncErrorsSection]; [self loadSyncDataTypeSection]; + [self loadSignOutSection]; [self loadAdvancedSettingsSection]; } @@ -472,6 +498,7 @@ case AutocompleteWalletItemType: self.autocompleteWalletPreference.value = value; break; + case SignOutItemType: case EncryptionItemType: case GoogleActivityControlsItemType: case DataFromChromeSync: @@ -517,6 +544,9 @@ case SyncNeedsTrustedVaultKeyErrorItemType: [self.syncErrorHandler openTrustedVaultReauth]; break; + case SignOutItemType: + [self.commandHandler showTurnOffSyncOptions]; + break; case SyncEverythingItemType: case AutofillDataTypeItemType: case BookmarksDataTypeItemType:
diff --git a/ios/chrome/browser/ui/webui/policy/policy_ui.mm b/ios/chrome/browser/ui/webui/policy/policy_ui.mm index 65ce478a..c814a6b3 100644 --- a/ios/chrome/browser/ui/webui/policy/policy_ui.mm +++ b/ios/chrome/browser/ui/webui/policy/policy_ui.mm
@@ -74,6 +74,9 @@ {"statusDevice", IDS_POLICY_STATUS_DEVICE}, {"statusMachine", IDS_POLICY_STATUS_MACHINE}, {"statusUser", IDS_POLICY_STATUS_USER}, + {"labelLastCloudReportSentTimestamp", + IDS_POLICY_LABEL_LAST_CLOUD_REPORT_SENT_TIMESTAMP}, + }; source->AddLocalizedStrings(kStrings); source->UseStringsJs();
diff --git a/ios/chrome/browser/web_state_list/web_state_list_metrics_browser_agent.h b/ios/chrome/browser/web_state_list/web_state_list_metrics_browser_agent.h index 3ddf018f..c01dd62 100644 --- a/ios/chrome/browser/web_state_list/web_state_list_metrics_browser_agent.h +++ b/ios/chrome/browser/web_state_list/web_state_list_metrics_browser_agent.h
@@ -12,6 +12,7 @@ #import "ios/chrome/browser/web_state_list/web_state_list_observer.h" #import "ios/web/public/web_state_observer.h" +class AllWebStateObservationForwarder; class SessionMetrics; class WebStateListMetricsBrowserAgent @@ -40,10 +41,6 @@ web::WebState* new_web_state, int active_index, ActiveWebStateChangeReason reason) override; - void WebStateReplacedAt(WebStateList* web_state_list, - web::WebState* old_web_state, - web::WebState* new_web_state, - int index) override; private: WebStateListMetricsBrowserAgent(Browser* browser, @@ -77,6 +74,8 @@ // Whether metric recording is paused (for session restoration). bool metric_collection_paused_ = false; + std::unique_ptr<AllWebStateObservationForwarder> web_state_forwarder_; + DISALLOW_COPY_AND_ASSIGN(WebStateListMetricsBrowserAgent); };
diff --git a/ios/chrome/browser/web_state_list/web_state_list_metrics_browser_agent.mm b/ios/chrome/browser/web_state_list/web_state_list_metrics_browser_agent.mm index 906a8b2f..7c8d173 100644 --- a/ios/chrome/browser/web_state_list/web_state_list_metrics_browser_agent.mm +++ b/ios/chrome/browser/web_state_list/web_state_list_metrics_browser_agent.mm
@@ -14,6 +14,7 @@ #include "ios/chrome/browser/crash_report/crash_loop_detection_util.h" #import "ios/chrome/browser/sessions/session_restoration_browser_agent.h" #include "ios/chrome/browser/ui/util/uikit_ui_util.h" +#include "ios/chrome/browser/web_state_list/all_web_state_observation_forwarder.h" #include "ios/chrome/browser/web_state_list/session_metrics.h" #import "ios/chrome/browser/web_state_list/web_state_list.h" #include "ios/web/public/browser_state.h" @@ -48,10 +49,8 @@ DCHECK(session_metrics_); browser->AddObserver(this); web_state_list_->AddObserver(this); - for (int index = 0; index < web_state_list_->count(); ++index) { - web::WebState* web_state = web_state_list_->GetWebStateAt(index); - web_state->AddObserver(this); - } + web_state_forwarder_.reset( + new AllWebStateObservationForwarder(web_state_list_, this)); SessionRestorationBrowserAgent* restoration_agent = SessionRestorationBrowserAgent::FromBrowser(browser); @@ -75,7 +74,6 @@ web::WebState* web_state, int index, bool activating) { - web_state->AddObserver(this); if (metric_collection_paused_) return; base::RecordAction(base::UserMetricsAction("MobileNewTabOpened")); @@ -86,7 +84,6 @@ WebStateList* web_state_list, web::WebState* web_state, int index) { - web_state->RemoveObserver(this); if (metric_collection_paused_) return; base::RecordAction(base::UserMetricsAction("MobileTabClosed")); @@ -108,15 +105,6 @@ base::RecordAction(base::UserMetricsAction("MobileTabSwitched")); } -void WebStateListMetricsBrowserAgent::WebStateReplacedAt( - WebStateList* web_state_list, - web::WebState* old_web_state, - web::WebState* new_web_state, - int index) { - old_web_state->RemoveObserver(this); - new_web_state->AddObserver(this); -} - // web::WebStateObserver void WebStateListMetricsBrowserAgent::DidStartNavigation( web::WebState* web_state, @@ -181,10 +169,7 @@ if (restoration_agent) restoration_agent->RemoveObserver(this); - for (int index = 0; index < web_state_list_->count(); ++index) { - web::WebState* web_state = web_state_list_->GetWebStateAt(index); - web_state->RemoveObserver(this); - } + web_state_forwarder_.reset(nullptr); web_state_list_->RemoveObserver(this); web_state_list_ = nullptr;
diff --git a/ios/chrome/test/earl_grey/chrome_matchers_app_interface.mm b/ios/chrome/test/earl_grey/chrome_matchers_app_interface.mm index d1381f7..8172812e 100644 --- a/ios/chrome/test/earl_grey/chrome_matchers_app_interface.mm +++ b/ios/chrome/test/earl_grey/chrome_matchers_app_interface.mm
@@ -1083,6 +1083,7 @@ + (id<GREYMatcher>)activityViewHeaderWithURLHost:(NSString*)host title:(NSString*)pageTitle { +#if TARGET_IPHONE_SIMULATOR return grey_allOf( // The title of the activity view starts as the URL, then asynchronously // changes to the page title. Sometimes, the activity view fails to update @@ -1094,6 +1095,15 @@ grey_allOf(grey_accessibilityTrait(UIAccessibilityTraitHeader), grey_kindOfClassName(@"LPLinkView"), nil)), nil); +#else + // Device tests tend to fail more often if the host is allowed in the + // grey_anyOf as above. + return grey_allOf(grey_accessibilityLabel(pageTitle), + grey_ancestor(grey_allOf( + grey_accessibilityTrait(UIAccessibilityTraitHeader), + grey_kindOfClassName(@"LPLinkView"), nil)), + nil); +#endif } + (id<GREYMatcher>)manualFallbackSuggestPasswordMatcher {
diff --git a/ios/public/provider/chrome/browser/discover_feed/discover_feed_configuration.h b/ios/public/provider/chrome/browser/discover_feed/discover_feed_configuration.h index a929c62f..0f54ab4 100644 --- a/ios/public/provider/chrome/browser/discover_feed/discover_feed_configuration.h +++ b/ios/public/provider/chrome/browser/discover_feed/discover_feed_configuration.h
@@ -7,16 +7,24 @@ #import <Foundation/Foundation.h> +class AuthenticationService; class ChromeBrowserState; @class DiscoverFeedMetricsRecorder; +class PrefService; // Configuration object used by the DiscoverFeedProvider. @interface DiscoverFeedConfiguration : NSObject -// BrowserState used by DiscoverFeedProvider; +// BrowserState used by DiscoverFeedProvider. DEPRECATED. @property(nonatomic, assign) ChromeBrowserState* browserState; -// DiscoverFeed metrics recorder used by DiscoverFeedProvider; +// AuthenticationService used by DiscoverFeedProvider. +@property(nonatomic, assign) AuthenticationService* authService; + +// PrefService used by DiscoverFeedProvider. +@property(nonatomic, assign) PrefService* prefService; + +// DiscoverFeed metrics recorder used by DiscoverFeedProvider. @property(nonatomic, strong) DiscoverFeedMetricsRecorder* metricsRecorder; @end
diff --git a/ios/web_view/internal/autofill/web_view_autofill_client_ios.h b/ios/web_view/internal/autofill/web_view_autofill_client_ios.h index d91b9931..2025461 100644 --- a/ios/web_view/internal/autofill/web_view_autofill_client_ios.h +++ b/ios/web_view/internal/autofill/web_view_autofill_client_ios.h
@@ -88,6 +88,7 @@ void ConfirmSaveAddressProfile( const AutofillProfile& profile, const AutofillProfile* original_profile, + SaveAddressProfilePromptOptions options, AddressProfileSavePromptCallback callback) override; bool HasCreditCardScanFeature() override; void ScanCreditCard(CreditCardScanCallback callback) override;
diff --git a/ios/web_view/internal/autofill/web_view_autofill_client_ios.mm b/ios/web_view/internal/autofill/web_view_autofill_client_ios.mm index 329e732..c054bdc 100644 --- a/ios/web_view/internal/autofill/web_view_autofill_client_ios.mm +++ b/ios/web_view/internal/autofill/web_view_autofill_client_ios.mm
@@ -223,6 +223,7 @@ void WebViewAutofillClientIOS::ConfirmSaveAddressProfile( const AutofillProfile& profile, const AutofillProfile* original_profile, + SaveAddressProfilePromptOptions options, AddressProfileSavePromptCallback callback) {} bool WebViewAutofillClientIOS::HasCreditCardScanFeature() {
diff --git a/services/device/public/cpp/bluetooth/bluetooth_utils_unittest.cc b/services/device/public/cpp/bluetooth/bluetooth_utils_unittest.cc index 303645f..21755d2 100644 --- a/services/device/public/cpp/bluetooth/bluetooth_utils_unittest.cc +++ b/services/device/public/cpp/bluetooth/bluetooth_utils_unittest.cc
@@ -21,9 +21,7 @@ constexpr std::array<uint8_t, 6> kAddress = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; constexpr char kName[] = "Foo Bar"; -constexpr char16_t kName16[] = u"Foo Bar"; constexpr char kUnicodeName[] = "❤❤❤❤"; -constexpr char16_t kUnicodeName16[] = u"❤❤❤❤"; constexpr char kEmptyName[] = ""; constexpr char kWhitespaceName[] = " "; constexpr char kUnicodeWhitespaceName[] = " "; @@ -64,7 +62,7 @@ info->address = kAddress; info->name = kName; info->device_type = BluetoothDeviceInfo::DeviceType::kUnknown; - EXPECT_EQ(kName16, GetBluetoothDeviceNameForDisplay(info)); + EXPECT_EQ(base::UTF8ToUTF16(kName), GetBluetoothDeviceNameForDisplay(info)); } TEST(BluetoothUtilsTest, @@ -73,7 +71,7 @@ info->address = kAddress; info->name = kName; info->device_type = BluetoothDeviceInfo::DeviceType::kComputer; - EXPECT_EQ(kName16, GetBluetoothDeviceNameForDisplay(info)); + EXPECT_EQ(base::UTF8ToUTF16(kName), GetBluetoothDeviceNameForDisplay(info)); } TEST(BluetoothUtilsTest, GetBluetoothDeviceNameForDisplay_UnicodeName) { @@ -81,7 +79,8 @@ info->address = kAddress; info->name = kUnicodeName; info->device_type = BluetoothDeviceInfo::DeviceType::kComputer; - EXPECT_EQ(kUnicodeName16, GetBluetoothDeviceNameForDisplay(info)); + EXPECT_EQ(base::UTF8ToUTF16(kUnicodeName), + GetBluetoothDeviceNameForDisplay(info)); } TEST(BluetoothUtilsTest, GetBluetoothDeviceNameForDisplay_EmptyName) { @@ -130,14 +129,15 @@ TEST(BluetoothUtilsTest, GetBluetoothDeviceLabelForAccessibility) { EXPECT_EQ( l10n_util::GetStringFUTF16( - IDS_BLUETOOTH_ACCESSIBILITY_DEVICE_TYPE_COMPUTER, kName16), + IDS_BLUETOOTH_ACCESSIBILITY_DEVICE_TYPE_COMPUTER, + base::UTF8ToUTF16(kName)), LabelFromTypeWithName(BluetoothDeviceInfo::DeviceType::kComputer, kName)); - EXPECT_EQ( - l10n_util::GetStringFUTF16( - IDS_BLUETOOTH_ACCESSIBILITY_DEVICE_TYPE_CAR_AUDIO, kUnicodeName16), - LabelFromTypeWithName(BluetoothDeviceInfo::DeviceType::kCarAudio, - kUnicodeName)); + EXPECT_EQ(l10n_util::GetStringFUTF16( + IDS_BLUETOOTH_ACCESSIBILITY_DEVICE_TYPE_CAR_AUDIO, + base::UTF8ToUTF16(kUnicodeName)), + LabelFromTypeWithName(BluetoothDeviceInfo::DeviceType::kCarAudio, + kUnicodeName)); EXPECT_EQ(l10n_util::GetStringFUTF16( IDS_BLUETOOTH_ACCESSIBILITY_DEVICE_TYPE_KEYBOARD, u"00:00:00:00:00:00"),
diff --git a/services/network/public/cpp/cross_origin_embedder_policy.cc b/services/network/public/cpp/cross_origin_embedder_policy.cc index f2690cc4..7a484ae 100644 --- a/services/network/public/cpp/cross_origin_embedder_policy.cc +++ b/services/network/public/cpp/cross_origin_embedder_policy.cc
@@ -35,7 +35,7 @@ switch (value) { case mojom::CrossOriginEmbedderPolicyValue::kNone: return false; - case mojom::CrossOriginEmbedderPolicyValue::kCorsOrCredentialless: + case mojom::CrossOriginEmbedderPolicyValue::kCredentialless: case mojom::CrossOriginEmbedderPolicyValue::kRequireCorp: return true; }
diff --git a/services/network/public/cpp/cross_origin_embedder_policy_parser.cc b/services/network/public/cpp/cross_origin_embedder_policy_parser.cc index c0ada0a5..00de82a8 100644 --- a/services/network/public/cpp/cross_origin_embedder_policy_parser.cc +++ b/services/network/public/cpp/cross_origin_embedder_policy_parser.cc
@@ -47,9 +47,9 @@ if (base::FeatureList::IsEnabled( features::kCrossOriginEmbedderPolicyCredentialless) && - item->item.GetString() == "cors-or-credentialless") { + item->item.GetString() == "credentialless") { return { - mojom::CrossOriginEmbedderPolicyValue::kCorsOrCredentialless, + mojom::CrossOriginEmbedderPolicyValue::kCredentialless, std::move(endpoint), }; }
diff --git a/services/network/public/cpp/cross_origin_embedder_policy_parser_unittest.cc b/services/network/public/cpp/cross_origin_embedder_policy_parser_unittest.cc index 1b7d2cf..91f06a3 100644 --- a/services/network/public/cpp/cross_origin_embedder_policy_parser_unittest.cc +++ b/services/network/public/cpp/cross_origin_embedder_policy_parser_unittest.cc
@@ -19,8 +19,8 @@ namespace { constexpr auto kNone = mojom::CrossOriginEmbedderPolicyValue::kNone; -constexpr auto kCorsOrCredentialless = - mojom::CrossOriginEmbedderPolicyValue::kCorsOrCredentialless; +constexpr auto kCredentialless = + mojom::CrossOriginEmbedderPolicyValue::kCredentialless; constexpr auto kRequireCorp = mojom::CrossOriginEmbedderPolicyValue::kRequireCorp; const auto kNoHeader = base::Optional<std::string>(); @@ -111,8 +111,7 @@ // Errors {"REQUIRE-CORP", kNoHeader, kNone, kNoEndpoint, kNone, kNoEndpoint}, - {"CORS-OR-CREDENTIALLESS", kNoHeader, kNone, kNoEndpoint, kNone, - kNoEndpoint}, + {"CREDENTIALLESS", kNoHeader, kNone, kNoEndpoint, kNone, kNoEndpoint}, {"credentialless", kNoHeader, kNone, kNoEndpoint, kNone, kNoEndpoint}, {" require-corp; REPORT-TO=\"endpoint\"", kNoHeader, kNone, kNoEndpoint, kNone, kNoEndpoint}, @@ -140,22 +139,20 @@ scoped_feature_list.InitWithFeatures( {}, {features::kCrossOriginEmbedderPolicyCredentialless}); TestCase test_cases[] = { - // COEP: cors-or-credentialless - {"cors-or-credentialless", kNoHeader, kNone, kNoEndpoint, kNone, - kNoEndpoint}, - // COEP-RO: cors-or-credentialless - {kNoHeader, "cors-or-credentialless", kNone, kNoEndpoint, kNone, - kNoEndpoint}, - // COEP: cors-or-credentialless with reporting endpoint - {"cors-or-credentialless; report-to=\"endpoint\"", kNoHeader, kNone, - kNoEndpoint, kNone, kNoEndpoint}, - // COEP-RO: cors-or-credentialless with reporting endpoint - {kNoHeader, "cors-or-credentialless; report-to=\"endpoint\"", kNone, - kNoEndpoint, kNone, kNoEndpoint}, - // With both headers - {"cors-or-credentialless; report-to=\"endpoint1\"", - "cors-or-credentialless; report-to=\"endpoint2\"", kNone, kNoEndpoint, + // COEP: credentialless + {"credentialless", kNoHeader, kNone, kNoEndpoint, kNone, kNoEndpoint}, + // COEP-RO: credentialless + {kNoHeader, "credentialless", kNone, kNoEndpoint, kNone, kNoEndpoint}, + // COEP: credentialless with reporting endpoint + {"credentialless; report-to=\"endpoint\"", kNoHeader, kNone, kNoEndpoint, kNone, kNoEndpoint}, + // COEP-RO: credentialless with reporting endpoint + {kNoHeader, "credentialless; report-to=\"endpoint\"", kNone, kNoEndpoint, + kNone, kNoEndpoint}, + // With both headers + {"credentialless; report-to=\"endpoint1\"", + "credentialless; report-to=\"endpoint2\"", kNone, kNoEndpoint, kNone, + kNoEndpoint}, }; for (const TestCase& test_case : test_cases) CheckTestCase(test_case); @@ -166,22 +163,22 @@ scoped_feature_list.InitWithFeatures( {features::kCrossOriginEmbedderPolicyCredentialless}, {}); TestCase test_cases[] = { - // COEP: cors-or-credentialless - {"cors-or-credentialless", kNoHeader, kCorsOrCredentialless, kNoEndpoint, - kNone, kNoEndpoint}, - // COEP-RO: cors-or-credentialless - {kNoHeader, "cors-or-credentialless", kNone, kNoEndpoint, - kCorsOrCredentialless, kNoEndpoint}, - // COEP: cors-or-credentialless with reporting endpoint - {"cors-or-credentialless; report-to=\"endpoint\"", kNoHeader, - kCorsOrCredentialless, "endpoint", kNone, kNoEndpoint}, - // COEP-RO: cors-or-credentialless with reporting endpoint - {kNoHeader, "cors-or-credentialless; report-to=\"endpoint\"", kNone, - kNoEndpoint, kCorsOrCredentialless, "endpoint"}, + // COEP: credentialless + {"credentialless", kNoHeader, kCredentialless, kNoEndpoint, kNone, + kNoEndpoint}, + // COEP-RO: credentialless + {kNoHeader, "credentialless", kNone, kNoEndpoint, kCredentialless, + kNoEndpoint}, + // COEP: credentialless with reporting endpoint + {"credentialless; report-to=\"endpoint\"", kNoHeader, kCredentialless, + "endpoint", kNone, kNoEndpoint}, + // COEP-RO: credentialless with reporting endpoint + {kNoHeader, "credentialless; report-to=\"endpoint\"", kNone, kNoEndpoint, + kCredentialless, "endpoint"}, // With both headers - {"cors-or-credentialless; report-to=\"endpoint1\"", - "cors-or-credentialless; report-to=\"endpoint2\"", kCorsOrCredentialless, - "endpoint1", kCorsOrCredentialless, "endpoint2"}, + {"credentialless; report-to=\"endpoint1\"", + "credentialless; report-to=\"endpoint2\"", kCredentialless, "endpoint1", + kCredentialless, "endpoint2"}, }; for (const TestCase& test_case : test_cases)
diff --git a/services/network/public/cpp/cross_origin_resource_policy.cc b/services/network/public/cpp/cross_origin_resource_policy.cc index b9d5d631..d700cc0 100644 --- a/services/network/public/cpp/cross_origin_resource_policy.cc +++ b/services/network/public/cpp/cross_origin_resource_policy.cc
@@ -156,7 +156,7 @@ bool require_corp = embedder_policy == mojom::CrossOriginEmbedderPolicyValue::kRequireCorp || (embedder_policy == - mojom::CrossOriginEmbedderPolicyValue::kCorsOrCredentialless && + mojom::CrossOriginEmbedderPolicyValue::kCredentialless && request_mode == mojom::RequestMode::kNavigate); // COEP https://mikewest.github.io/corpp/#corp-check
diff --git a/services/network/public/cpp/features.cc b/services/network/public/cpp/features.cc index 6fc7fa3..f6485867 100644 --- a/services/network/public/cpp/features.cc +++ b/services/network/public/cpp/features.cc
@@ -76,7 +76,7 @@ "ProactivelyThrottleLowPriorityRequests", base::FEATURE_DISABLED_BY_DEFAULT}; -// Enables Cross-Origin-Embedder-Policy: cors-or-credentialless. +// Enables Cross-Origin-Embedder-Policy: credentialless. // https://github.com/mikewest/credentiallessness COMPONENT_EXPORT(NETWORK_CPP) extern const base::Feature kCrossOriginEmbedderPolicyCredentialless{
diff --git a/services/network/public/mojom/cross_origin_embedder_policy.mojom b/services/network/public/mojom/cross_origin_embedder_policy.mojom index da25025..92b3958 100644 --- a/services/network/public/mojom/cross_origin_embedder_policy.mojom +++ b/services/network/public/mojom/cross_origin_embedder_policy.mojom
@@ -10,7 +10,7 @@ // https://mikewest.github.io/corpp/#integration-html enum CrossOriginEmbedderPolicyValue { kNone, - kCorsOrCredentialless, + kCredentialless, kRequireCorp, };
diff --git a/services/network/url_loader.cc b/services/network/url_loader.cc index 45f952a2..ac7b971b6 100644 --- a/services/network/url_loader.cc +++ b/services/network/url_loader.cc
@@ -2410,10 +2410,8 @@ ? factory_params_->client_security_state->cross_origin_embedder_policy .value : mojom::CrossOriginEmbedderPolicyValue::kNone; - if (coep_policy != - mojom::CrossOriginEmbedderPolicyValue::kCorsOrCredentialless) { + if (coep_policy != mojom::CrossOriginEmbedderPolicyValue::kCredentialless) return true; - } DCHECK(base::FeatureList::IsEnabled( features::kCrossOriginEmbedderPolicyCredentialless));
diff --git a/services/network/url_loader.h b/services/network/url_loader.h index b288af6..916cb43 100644 --- a/services/network/url_loader.h +++ b/services/network/url_loader.h
@@ -400,7 +400,7 @@ // Returns whether sending/storing credentials is allowed by COEP. // |url| is the latest request URL, either the original URL or // `redirect_info.new_url`. - // When Cross-Origin-Embedder-Policy: cors-or-credentialless is set, do not + // When Cross-Origin-Embedder-Policy: credentialless is set, do not // send or store credentials for no-cors cross-origin request. bool CoepAllowCredentials(const GURL& url);
diff --git a/testing/buildbot/chromium.fyi.json b/testing/buildbot/chromium.fyi.json index a1ebe6e..e693269 100644 --- a/testing/buildbot/chromium.fyi.json +++ b/testing/buildbot/chromium.fyi.json
@@ -60249,15 +60249,13 @@ "dimension_sets": [ { "cpu": "x86-64", - "gpu": "8086:0a2e", - "hidpi": "0", "machine_type": "n1-standard-4", "os": "Mac-11|Mac-10.16" } ], - "hard_timeout": 1800, + "hard_timeout": 4500, "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 12 + "shards": 5 }, "test_id_prefix": "ninja://:blink_web_tests/" }
diff --git a/testing/buildbot/chromium.mac.json b/testing/buildbot/chromium.mac.json index 1e763db1..74cb47c 100644 --- a/testing/buildbot/chromium.mac.json +++ b/testing/buildbot/chromium.mac.json
@@ -10789,7 +10789,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -10808,7 +10808,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -10830,7 +10830,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -10850,7 +10850,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -10869,7 +10869,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -10888,7 +10888,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -10907,7 +10907,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -10926,7 +10926,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -10945,7 +10945,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -10964,7 +10964,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -10984,7 +10984,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11003,7 +11003,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11022,7 +11022,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11045,8 +11045,9 @@ "os": "Mac-11|Mac-10.16" } ], + "hard_timeout": 4500, "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 10 + "shards": 8 }, "test": "browser_tests", "test_id_prefix": "ninja://chrome/test:browser_tests/" @@ -11064,7 +11065,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11083,7 +11084,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11102,7 +11103,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11121,7 +11122,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11140,7 +11141,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11159,7 +11160,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11178,7 +11179,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11201,8 +11202,9 @@ "os": "Mac-11|Mac-10.16" } ], + "hard_timeout": 4500, "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 6 + "shards": 2 }, "test": "content_browsertests", "test_id_prefix": "ninja://content/test:content_browsertests/" @@ -11217,7 +11219,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11236,7 +11238,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11255,7 +11257,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11274,7 +11276,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11293,7 +11295,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11312,7 +11314,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11331,7 +11333,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11350,7 +11352,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11369,7 +11371,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11388,7 +11390,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11407,7 +11409,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11426,7 +11428,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11445,7 +11447,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11464,7 +11466,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11483,7 +11485,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11502,7 +11504,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11521,7 +11523,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11540,7 +11542,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11559,7 +11561,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11578,7 +11580,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11597,12 +11599,11 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-highcpu-4", + "machine_type": "n1-standard-4", "os": "Mac-11|Mac-10.16" } ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 6 + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "interactive_ui_tests", "test_id_prefix": "ninja://chrome/test:interactive_ui_tests/" @@ -11617,7 +11618,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11636,7 +11637,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11655,7 +11656,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11674,7 +11675,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11693,7 +11694,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11712,7 +11713,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11731,7 +11732,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11750,7 +11751,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11769,7 +11770,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11788,7 +11789,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11807,7 +11808,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11826,7 +11827,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11845,7 +11846,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11864,7 +11865,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11883,7 +11884,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11902,7 +11903,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11921,7 +11922,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11940,7 +11941,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11959,7 +11960,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11978,7 +11979,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -11997,7 +11998,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -12016,7 +12017,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -12035,7 +12036,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -12054,7 +12055,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -12073,7 +12074,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -12092,7 +12093,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -12130,7 +12131,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -12149,7 +12150,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -12168,7 +12169,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -12187,7 +12188,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -12206,7 +12207,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -12225,7 +12226,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -12244,7 +12245,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -12263,7 +12264,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -12283,7 +12284,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -12302,7 +12303,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -12328,7 +12329,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -12361,8 +12362,9 @@ "os": "Mac-11|Mac-10.16" } ], + "hard_timeout": 4500, "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 12 + "shards": 5 }, "test_id_prefix": "ninja://:blink_web_tests/" }, @@ -12384,7 +12386,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -12404,7 +12406,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -12429,7 +12431,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -12453,7 +12455,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -12477,7 +12479,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -12500,7 +12502,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -12520,7 +12522,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -12543,7 +12545,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -12566,7 +12568,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -12589,7 +12591,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ], @@ -12621,8 +12623,7 @@ } ], "idempotent": false, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 12 + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test_id_prefix": "ninja://chrome/test:telemetry_perf_unittests/" }, @@ -12650,8 +12651,7 @@ } ], "idempotent": false, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 8 + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test_id_prefix": "ninja://chrome/test:telemetry_unittests/" }, @@ -12672,7 +12672,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "machine_type": "n1-standard-4", + "machine_type": "n1-highcpu-4", "os": "Mac-11|Mac-10.16" } ],
diff --git a/testing/buildbot/mixins.pyl b/testing/buildbot/mixins.pyl index 4919fb19..93b76fef 100644 --- a/testing/buildbot/mixins.pyl +++ b/testing/buildbot/mixins.pyl
@@ -614,13 +614,6 @@ 'dimensions': { 'cpu': 'x86-64', 'os': 'Mac-11|Mac-10.16', - # TODO(crbug.com/1176803): The Mac 11 pool seems to be an odd - # mix of machines where some of them are 3x slower than others, - # which really messes with the scheduling. Until we can figure - # out what to do about that, we'll just have those machines for - # one test suite, and run all of the other test suites on the - # faster machines. - 'machine_type': 'n1-standard-4', }, }, },
diff --git a/testing/buildbot/test_suite_exceptions.pyl b/testing/buildbot/test_suite_exceptions.pyl index f19e5b0..9bb3df0 100644 --- a/testing/buildbot/test_suite_exceptions.pyl +++ b/testing/buildbot/test_suite_exceptions.pyl
@@ -290,6 +290,19 @@ 'shards': 25, }, }, + 'Mac11 Tests': { + # TODO(crbug.com/1206401): Restore to defaults when there is + # enough capacity. + 'swarming': { + 'dimension_sets': [ + { + 'machine_type': 'n1-standard-4', + }, + ], + 'hard_timeout': 4500, + 'shards': 5, + }, + }, 'ToTFuchsia x64': { 'args': [ '--platform=fuchsia', @@ -504,10 +517,16 @@ }, }, 'mac11.0-blink-rel-dummy': { + # TODO(crbug.com/1206401): Restore to defaults when there is + # enough capacity. 'swarming': { - # Increase timeout and reduce shards. - 'shards': 12, - 'hard_timeout': 1800, + 'dimension_sets': [ + { + 'machine_type': 'n1-standard-4', + }, + ], + 'hard_timeout': 4500, + 'shards': 5, }, }, 'win10-blink-rel-dummy': { @@ -632,6 +651,19 @@ '--test-launcher-filter-file=../../testing/buildbot/filters/mac.mac-rel.browser_tests.filter', ], }, + 'Mac11 Tests': { + # TODO(crbug.com/1206401): Restore to defaults when there is enough + # capacity. + 'swarming': { + 'dimension_sets': [ + { + 'machine_type': 'n1-standard-4', + } + ], + 'hard_timeout': 4500, + 'shards': 8, + }, + }, 'ToTWin(dbg)': { 'swarming': { 'shards': 20, @@ -1215,6 +1247,19 @@ '--test-launcher-filter-file=../../testing/buildbot/filters/android.lollipop_tablet_tester.content_browsertests.filter', ], }, + 'Mac11 Tests': { + # TODO(crbug.com/1206401): Restore to defaults when there is enough + # capacity. + 'swarming': { + 'dimension_sets': [ + { + 'machine_type': 'n1-standard-4', + } + ], + 'hard_timeout': 4500, + 'shards': 2, + }, + }, 'Marshmallow Tablet Tester': { 'args': [ '--test-launcher-filter-file=../../testing/buildbot/filters/android.marshmallow_tablet_tester.content_browsertests.filter', @@ -1771,19 +1816,15 @@ }, }, 'Mac11 Tests': { + # TODO(crbug.com/1206401): Restore to defaults when there is enough + # capacity. 'swarming': { - 'shards': 6, - 'dimension_sets': [{ - 'os': 'Mac-11|Mac-10.16', - 'cpu': 'x86-64', - # TODO(crbug.com/1176803): The Mac 11 pool seems to be an odd - # mix of machines where some of them are 3x slower than others, - # which really messes with the scheduling. Until we can figure - # out what to do about that, we'll just have those machines for - # one test suite, and run all of the other test suites on the - # faster machines. - 'machine_type': 'n1-highcpu-4', - }], + 'dimension_sets': [ + { + 'machine_type': 'n1-standard-4', + }, + ], + 'shards': 1, }, }, 'ToTLinuxTSan': { @@ -2639,6 +2680,18 @@ '--gtest_filter=-*', ], }, + 'Mac11 Tests': { + # TODO(crbug.com/1206401): Restore to defaults when there is enough + # capacity. + 'swarming': { + 'dimension_sets': [ + { + 'machine_type': 'n1-standard-4', + } + ], + 'shards': 1, + }, + }, 'ToTLinuxTSan': { 'swarming': { 'shards': 6, @@ -2758,6 +2811,18 @@ '--jobs=1', ], }, + 'Mac11 Tests': { + # TODO(crbug.com/1206401): Restore to defaults when there is enough + # capacity. + 'swarming': { + 'dimension_sets': [ + { + 'machine_type': 'n1-standard-4', + }, + ], + 'shards': 1, + }, + }, 'Win7 Tests (dbg)(1)': { 'args': [ '--jobs=1', @@ -2821,6 +2886,18 @@ }, 'telemetry_unittests': { 'modifications': { + # TODO(crbug.com/1206401): Restore to defaults when there is + # enough capacity. + 'Mac11 Tests': { + 'swarming': { + 'dimension_sets': [ + { + 'machine_type': 'n1-standard-4', + }, + ], + 'shards': 1, + }, + }, 'Win10 Tests x64 (dbg)': { 'experiment_percentage': 100, # crbug.com/870673 },
diff --git a/testing/buildbot/waterfalls.pyl b/testing/buildbot/waterfalls.pyl index c5f9ee1..29ecf50 100644 --- a/testing/buildbot/waterfalls.pyl +++ b/testing/buildbot/waterfalls.pyl
@@ -3500,15 +3500,6 @@ 'mixins': [ 'mac_11_x64', ], - 'swarming': { - 'dimension_sets': [ - { - 'gpu': '8086:0a2e', - 'hidpi': '0', - }, - ], - 'hard_timeout': 900, - }, 'test_suites': { 'isolated_scripts': 'chromium_webkit_isolated_scripts', }, @@ -5270,6 +5261,19 @@ 'mixins': [ 'mac_11_x64', ], + # TODO(crbug.com/1176803): The Mac 11 pool seems to be an odd + # mix of machines where some of them are 3x slower than others, + # which really messes with the scheduling. Until we can figure + # out what to do about that, we'll just run most of the test suites + # on the slow bots (because they are fast) and run the big test + # suites on the faster machines. + 'swarming': { + 'dimension_sets': [ + { + 'machine_type': 'n1-highcpu-4', + }, + ], + }, 'test_suites': { 'gtest_tests': 'chromium_mac_gtests_no_nacl', 'isolated_scripts': 'chromium_mac_rel_isolated_scripts',
diff --git a/third_party/blink/common/page_state/page_state_serialization_unittest.cc b/third_party/blink/common/page_state/page_state_serialization_unittest.cc index da6ef99..3ed40254 100644 --- a/third_party/blink/common/page_state/page_state_serialization_unittest.cc +++ b/third_party/blink/common/page_state/page_state_serialization_unittest.cc
@@ -197,8 +197,8 @@ frame_state->document_sequence_number = 456; frame_state->page_scale_factor = 2.0f; - frame_state->document_state.push_back( - u"\n\r?% WebKit serialized form state version 8 \n\r=&"); + frame_state->document_state.push_back(base::UTF8ToUTF16( + "\n\r?% WebKit serialized form state version 8 \n\r=&")); frame_state->document_state.push_back(u"form key"); frame_state->document_state.push_back(u"1"); frame_state->document_state.push_back(u"foo"); @@ -459,8 +459,9 @@ ExplodedPageState input; PopulateFrameState(&input.top); - input.top.scroll_anchor_selector = - std::u16string(kMaxScrollAnchorSelectorLength + 1, u'a'); + std::string excessive_length_string(kMaxScrollAnchorSelectorLength + 1, 'a'); + + input.top.scroll_anchor_selector = base::UTF8ToUTF16(excessive_length_string); std::string encoded; EncodePageState(input, &encoded);
diff --git a/third_party/blink/public/mojom/web_feature/web_feature.mojom b/third_party/blink/public/mojom/web_feature/web_feature.mojom index 50f61f3..40a4ddb 100644 --- a/third_party/blink/public/mojom/web_feature/web_feature.mojom +++ b/third_party/blink/public/mojom/web_feature/web_feature.mojom
@@ -3193,7 +3193,7 @@ kPrefixedStorageQuotaThirdPartyContext = 3878, kRequestedFileSystemPersistentThirdPartyContext = 3879, kPrefixedStorageInfoThirdPartyContext = 3880, - kCrossOriginEmbedderPolicyCorsOrCredentialless = 3881, + kCrossOriginEmbedderPolicyCredentialless = 3881, kPostMessageFromSecureToSecure = 3882, kPostMessageFromInsecureToInsecure = 3883, kWebAppManifestProtocolHandlers = 3884,
diff --git a/third_party/blink/public/web/blink.h b/third_party/blink/public/web/blink.h index 27d0174..0786d214 100644 --- a/third_party/blink/public/web/blink.h +++ b/third_party/blink/public/web/blink.h
@@ -113,6 +113,15 @@ // This is called at most once. This is called earlier than any frame commit. BLINK_EXPORT void SetIsCrossOriginIsolated(bool value); BLINK_EXPORT bool IsCrossOriginIsolated(); + +// Direct sockets require isolation above and beyond what "cross-origin +// isolation" provides. This flag corresponds to that set of restrictions. +// Similarly to the `SetIsCrossOriginIsolated()` method above, this flag is +// process global, and called at most once, prior to committing a frame. +// +// TODO(mkwst): We need a specification for this restriction. +BLINK_EXPORT void SetIsDirectSocketEnabled(bool value); +BLINK_EXPORT bool IsDirectSocketEnabled(); } // namespace blink #endif // THIRD_PARTY_BLINK_PUBLIC_WEB_BLINK_H_
diff --git a/third_party/blink/renderer/controller/blink_initializer.cc b/third_party/blink/renderer/controller/blink_initializer.cc index 6ed47dd..f7bdcb9a 100644 --- a/third_party/blink/renderer/controller/blink_initializer.cc +++ b/third_party/blink/renderer/controller/blink_initializer.cc
@@ -193,6 +193,16 @@ return Agent::IsCrossOriginIsolated(); } +// Function defined in third_party/blink/public/web/blink.h. +void SetIsDirectSocketEnabled(bool value) { + Agent::SetIsDirectSocketEnabled(value); +} + +// Function defined in third_party/blink/public/web/blink.h. +bool IsDirectSocketEnabled() { + return Agent::IsDirectSocketEnabled(); +} + void BlinkInitializer::RegisterInterfaces(mojo::BinderMap& binders) { ModulesInitializer::RegisterInterfaces(binders); Thread* main_thread = Thread::MainThread();
diff --git a/third_party/blink/renderer/core/css/style_engine.cc b/third_party/blink/renderer/core/css/style_engine.cc index 42cdbdf..d9decb6d 100644 --- a/third_party/blink/renderer/core/css/style_engine.cc +++ b/third_party/blink/renderer/core/css/style_engine.cc
@@ -2290,6 +2290,7 @@ kLocalStyleChange, StyleChangeReasonForTracing::Create( style_change_reason::kPlatformColorChange)); UpdateColorScheme(); + UpdateColorSchemeBackground(); } void StyleEngine::UpdateColorSchemeBackground(bool color_scheme_changed) {
diff --git a/third_party/blink/renderer/core/css/style_engine_test.cc b/third_party/blink/renderer/core/css/style_engine_test.cc index 077436a..d51b06b1 100644 --- a/third_party/blink/renderer/core/css/style_engine_test.cc +++ b/third_party/blink/renderer/core/css/style_engine_test.cc
@@ -3309,6 +3309,36 @@ EXPECT_EQ(Color::kWhite, light_document->View()->BaseBackgroundColor()); } +TEST_F(StyleEngineSimTest, ColorSchemeBaseBackgroundWhileRenderBlocking) { + SimRequest main_resource("https://example.com", "text/html"); + SimSubresourceRequest css_resource("https://example.com/slow.css", + "text/css"); + + LoadURL("https://example.com"); + + main_resource.Write(R"HTML( + <!doctype html> + <meta name="color-scheme" content="dark"> + <link rel="stylesheet" href="slow.css"> + Some content + )HTML"); + + css_resource.Start(); + test::RunPendingTasks(); + + // No rendering updates should have happened yet. + ASSERT_TRUE(GetDocument().documentElement()); + ASSERT_FALSE(GetDocument().documentElement()->GetComputedStyle()); + EXPECT_TRUE(Compositor().DeferMainFrameUpdate()); + + // The dark color-scheme meta should affect the canvas color. + EXPECT_EQ(Color(0x12, 0x12, 0x12), + GetDocument().View()->BaseBackgroundColor()); + + main_resource.Finish(); + css_resource.Finish(); +} + namespace { void SetDependsOnContainerQueries(Element& element) {
diff --git a/third_party/blink/renderer/core/execution_context/agent.cc b/third_party/blink/renderer/core/execution_context/agent.cc index f78f0e7..57a95a0 100644 --- a/third_party/blink/renderer/core/execution_context/agent.cc +++ b/third_party/blink/renderer/core/execution_context/agent.cc
@@ -12,9 +12,11 @@ namespace { bool is_cross_origin_isolated = false; +bool is_direct_socket_potentially_available = false; #if DCHECK_IS_ON() bool is_cross_origin_isolated_set = false; +bool is_direct_socket_potentially_available_set = false; #endif } // namespace @@ -52,6 +54,21 @@ is_cross_origin_isolated = value; } +// static +bool Agent::IsDirectSocketEnabled() { + return is_direct_socket_potentially_available; +} + +// static +void Agent::SetIsDirectSocketEnabled(bool value) { +#if DCHECK_IS_ON() + if (is_direct_socket_potentially_available_set) + DCHECK_EQ(is_direct_socket_potentially_available, value); + is_direct_socket_potentially_available_set = true; +#endif + is_direct_socket_potentially_available = value; +} + bool Agent::IsOriginKeyed() { if (IsCrossOriginIsolated()) { return true;
diff --git a/third_party/blink/renderer/core/execution_context/agent.h b/third_party/blink/renderer/core/execution_context/agent.h index 1affb2d..914f11c 100644 --- a/third_party/blink/renderer/core/execution_context/agent.h +++ b/third_party/blink/renderer/core/execution_context/agent.h
@@ -63,6 +63,15 @@ // Only called from blink::SetIsCrossOriginIsolated. static void SetIsCrossOriginIsolated(bool value); + // Represents adherence to an additional set of restrictions above and beyond + // "cross-origin isolated". + // + // TODO(mkwst): We need a specification for these restrictions: + // https://crbug.com/1206150. + static bool IsDirectSocketEnabled(); + // Only called from blink::SetIsDirectSocketEnabled. + static void SetIsDirectSocketEnabled(bool value); + // Representing agent cluster's "is origin-keyed" concept: // https://html.spec.whatwg.org/C/#is-origin-keyed //
diff --git a/third_party/blink/renderer/core/frame/deprecation.cc b/third_party/blink/renderer/core/frame/deprecation.cc index f7f8c12..d34271f 100644 --- a/third_party/blink/renderer/core/frame/deprecation.cc +++ b/third_party/blink/renderer/core/frame/deprecation.cc
@@ -75,6 +75,7 @@ kM94 = 94, kM95 = 95, kM96 = 96, + kM97 = 97, }; // Returns estimated milestone dates as milliseconds since January 1, 1970. @@ -140,11 +141,13 @@ case kM93: return {2021, 8, 0, 31, 4}; case kM94: - return {2021, 10, 0, 12, 4}; + return {2021, 9, 0, 21, 4}; case kM95: - return {2021, 11, 0, 30, 4}; + return {2021, 10, 0, 19, 4}; case kM96: - return {2022, 1, 0, 25, 4}; + return {2022, 11, 0, 16, 4}; + case kM97: + return {2022, 1, 0, 4, 4}; } NOTREACHED(); @@ -575,19 +578,19 @@ "compatibility issues on modern browsers. The standardized SDP " "format, \"unified-plan\", has been used by default since M72 " "(January, 2019). Dropping support for Plan B is targeted for " - "M93 (Canary: July 15, 2021; Stable: August 24, 2021)."}; + "M93. See https://www.chromestatus.com/feature/5823036655665152 " + "for more details."}; case WebFeature::kRTCPeerConnectionSdpSemanticsPlanBWithReverseOriginTrial: - return {"RTCPeerConnectionSdpSemanticsPlanBWithReverseOriginTrial", kM96, + return {"RTCPeerConnectionSdpSemanticsPlanBWithReverseOriginTrial", kM97, "Plan B SDP semantics, which is used when constructing an " "RTCPeerConnection with {sdpSemantics:\"plan-b\"}, is a legacy " "version of the Session Description Protocol that has severe " "compatibility issues on modern browsers. The standardized SDP " "format, \"unified-plan\", has been used by default since M72 " "(January, 2019). Dropping support for Plan B is targeted for " - "M93 (Canary: July 15, 2021; Stable: August 24, 2021), but " - "because you have opted in to the Reverse Origin Trial, you have " - "until M96 (Canary: November, 2021; Stable: January, 2022)."}; + "M93, but this page may extend the deadline until M97 due to the " + "'RTCPeerConnection Plan B SDP Semantics' deprecation trial."}; case WebFeature::kAddressSpaceUnknownNonSecureContextEmbeddedPrivate: case WebFeature::kAddressSpaceUnknownNonSecureContextEmbeddedLocal:
diff --git a/third_party/blink/renderer/core/html/build.gni b/third_party/blink/renderer/core/html/build.gni index eabf572..c6fa064 100644 --- a/third_party/blink/renderer/core/html/build.gni +++ b/third_party/blink/renderer/core/html/build.gni
@@ -601,6 +601,7 @@ "parser/html_view_source_parser.cc", "parser/html_view_source_parser.h", "parser/input_stream_preprocessor.h", + "parser/literal_buffer.h", "parser/markup_tokenizer_inlines.h", "parser/nesting_level_incrementer.h", "parser/parser_scripting_flag_policy.h", @@ -688,6 +689,7 @@ "media/video_wake_lock_test.cc", "parser/atomic_html_token_test.cc", "parser/compact_html_token_test.cc", + "parser/literal_buffer_test.cc", "parser/html_document_parser_loading_test.cc", "parser/html_document_parser_test.cc", "parser/html_entity_parser_test.cc",
diff --git a/third_party/blink/renderer/core/html/html_view_source_document.cc b/third_party/blink/renderer/core/html/html_view_source_document.cc index 0b4d0a6..35fd136 100644 --- a/third_party/blink/renderer/core/html/html_view_source_document.cc +++ b/third_party/blink/renderer/core/html/html_view_source_document.cc
@@ -181,7 +181,7 @@ HTMLToken& token) { current_ = AddSpanWithClassName("html-tag"); - AtomicString tag_name(token.GetName()); + AtomicString tag_name = token.GetName().AsAtomicString(); unsigned index = 0; HTMLToken::AttributeList::const_iterator iter = token.Attributes().begin();
diff --git a/third_party/blink/renderer/core/html/parser/atomic_html_token.h b/third_party/blink/renderer/core/html/parser/atomic_html_token.h index 0142b43..912f26a 100644 --- a/third_party/blink/renderer/core/html/parser/atomic_html_token.h +++ b/third_party/blink/renderer/core/html/parser/atomic_html_token.h
@@ -109,7 +109,7 @@ NOTREACHED(); break; case HTMLToken::DOCTYPE: - name_ = AtomicString(token.GetName()); + name_ = token.GetName().AsAtomicString(); doctype_data_ = token.ReleaseDoctypeData(); break; case HTMLToken::kEndOfFile: @@ -121,16 +121,16 @@ lookupHTMLTag(token.GetName().data(), token.GetName().size())) name_ = tag_name; else - name_ = AtomicString(token.GetName()); + name_ = token.GetName().AsAtomicString(); InitializeAttributes(token.Attributes()); break; } case HTMLToken::kCharacter: case HTMLToken::kComment: if (token.IsAll8BitData()) - data_ = String::Make8BitFrom16BitSource(token.Data()); + data_ = token.Data().AsString8(); else - data_ = String(token.Data()); + data_ = token.Data().AsString(); break; } } @@ -231,14 +231,14 @@ attributes_.clear(); attributes_.ReserveInitialCapacity(size); for (const auto& attribute : attributes) { - if (attribute.NameAsVector().IsEmpty()) + if (attribute.NameIsEmpty()) continue; attribute.NameRange().CheckValid(); attribute.ValueRange().CheckValid(); - AtomicString value(attribute.ValueAsVector()); - // attribute.ValueAsVector.data() is null for attributes with no values, but + AtomicString value(attribute.GetValue()); + // The string pointer in |value| is null for attributes with no values, but // the null atom is used to represent absence of attributes; attributes with // no values have the value set to an empty atom instead. if (value == g_null_atom) {
diff --git a/third_party/blink/renderer/core/html/parser/html_parser_idioms.h b/third_party/blink/renderer/core/html/parser/html_parser_idioms.h index cfa5f6a..a06c05e 100644 --- a/third_party/blink/renderer/core/html/parser/html_parser_idioms.h +++ b/third_party/blink/renderer/core/html/parser/html_parser_idioms.h
@@ -27,6 +27,7 @@ #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/dom/qualified_name.h" +#include "third_party/blink/renderer/core/html/parser/literal_buffer.h" #include "third_party/blink/renderer/platform/wtf/decimal.h" #include "third_party/blink/renderer/platform/wtf/forward.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" @@ -132,6 +133,13 @@ template <wtf_size_t inlineCapacity> inline static String AttemptStaticStringCreation( + const LiteralBuffer<UChar, inlineCapacity>& vector, + CharacterWidth width) { + return AttemptStaticStringCreation(vector.data(), vector.size(), width); +} + +template <wtf_size_t inlineCapacity> +inline static String AttemptStaticStringCreation( const Vector<UChar, inlineCapacity>& vector, CharacterWidth width) { return AttemptStaticStringCreation(vector.data(), vector.size(), width);
diff --git a/third_party/blink/renderer/core/html/parser/html_preload_scanner.cc b/third_party/blink/renderer/core/html/parser/html_preload_scanner.cc index 84ff6ed..95976703 100644 --- a/third_party/blink/renderer/core/html/parser/html_preload_scanner.cc +++ b/third_party/blink/renderer/core/html/parser/html_preload_scanner.cc
@@ -86,7 +86,7 @@ } const StringImpl* TagImplFor(const HTMLToken::DataVector& data) { - AtomicString tag_name(data); + AtomicString tag_name = data.AsAtomicString(); const StringImpl* result = tag_name.Impl(); if (result->IsStatic()) return result;
diff --git a/third_party/blink/renderer/core/html/parser/html_token.h b/third_party/blink/renderer/core/html/parser/html_token.h index 944b8f1..f6bac9cd 100644 --- a/third_party/blink/renderer/core/html/parser/html_token.h +++ b/third_party/blink/renderer/core/html/parser/html_token.h
@@ -33,6 +33,7 @@ #include "base/macros.h" #include "third_party/blink/renderer/core/dom/attribute.h" #include "third_party/blink/renderer/core/html/parser/html_parser_idioms.h" +#include "third_party/blink/renderer/core/html/parser/literal_buffer.h" #include "third_party/blink/renderer/platform/wtf/forward.h" namespace blink { @@ -113,22 +114,22 @@ int end; }; - AtomicString GetName() const { return AtomicString(name_); } + AtomicString GetName() const { return name_.AsAtomicString(); } + AtomicString GetValue() const { return value_.AsAtomicString(); } + String NameAttemptStaticStringCreation() const { return AttemptStaticStringCreation(name_, kLikely8Bit); } - const Vector<UChar, 32>& NameAsVector() const { return name_; } - const Vector<UChar, 32>& ValueAsVector() const { return value_; } - void AppendToName(UChar c) { name_.push_back(c); } + bool NameIsEmpty() const { return name_.IsEmpty(); } + void AppendToName(UChar c) { name_.AddChar(c); } scoped_refptr<StringImpl> Value8BitIfNecessary() const { - return StringImpl::Create8BitIfPossible(value_); + return StringImpl::Create8BitIfPossible(value_.data(), value_.size()); } - String Value() const { return String(value_); } + String Value() const { return String(value_.data(), value_.size()); } - void AppendToValue(UChar c) { value_.push_back(c); } - void AppendToValue(const String& value) { value.AppendTo(value_); } + void AppendToValue(UChar c) { value_.AddChar(c); } void ClearValue() { value_.clear(); } const Range& NameRange() const { return name_range_; } @@ -137,8 +138,10 @@ Range& MutableValueRange() { return value_range_; } private: - Vector<UChar, 32> name_; - Vector<UChar, 32> value_; + // TODO(chromium:1204030): Do a more rigorous study and select a + // better-informed inline capacity. + LiteralBuffer<UChar, 32> name_; + LiteralBuffer<UChar, 32> value_; Range name_range_; Range value_range_; }; @@ -148,7 +151,9 @@ // By using an inline capacity of 256, we avoid spilling over into an malloced // buffer approximately 99% of the time based on a non-scientific browse // around a number of popular web sites on 23 May 2013. - typedef Vector<UChar, 256> DataVector; + // TODO(chromium:1204030): Do a more rigorous study and select a + // better-informed inline capacity. + typedef LiteralBuffer<UChar, 256> DataVector; HTMLToken() { Clear(); } @@ -157,12 +162,7 @@ range_.Clear(); range_.start = 0; base_offset_ = 0; - // Don't call Vector::clear() as that would destroy the - // alloced VectorBuffer. If the innerHTML'd content has - // two 257 character text nodes in a row, we'll needlessly - // thrash malloc. When we finally finish the parse the - // HTMLToken will be destroyed and the VectorBuffer released. - data_.Shrink(0); + data_.clear(); or_all_data_ = 0; } @@ -199,7 +199,7 @@ void AppendToName(UChar character) { DCHECK(type_ == kStartTag || type_ == kEndTag || type_ == DOCTYPE); DCHECK(character); - data_.push_back(character); + data_.AddChar(character); or_all_data_ |= character; } @@ -224,7 +224,7 @@ void BeginDOCTYPE(UChar character) { DCHECK(character); BeginDOCTYPE(); - data_.push_back(character); + data_.AddChar(character); or_all_data_ |= character; } @@ -290,7 +290,7 @@ current_attribute_ = nullptr; attributes_.clear(); - data_.push_back(character); + data_.AddChar(character); or_all_data_ |= character; } @@ -301,17 +301,17 @@ current_attribute_ = nullptr; attributes_.clear(); - data_.push_back(character); + data_.AddChar(character); } - void BeginEndTag(const Vector<LChar, 32>& characters) { + void BeginEndTag(const LiteralBuffer<LChar, 32>& characters) { DCHECK_EQ(type_, kUninitialized); type_ = kEndTag; self_closing_ = false; current_attribute_ = nullptr; attributes_.clear(); - data_.AppendVector(characters); + data_.AppendLiteral(characters); } void AddNewAttribute() { @@ -360,12 +360,6 @@ current_attribute_->AppendToValue(character); } - void AppendToAttributeValue(wtf_size_t i, const String& value) { - DCHECK(!value.IsEmpty()); - DCHECK(type_ == kStartTag || type_ == kEndTag); - attributes_[i].AppendToValue(value); - } - const AttributeList& Attributes() const { DCHECK(type_ == kStartTag || type_ == kEndTag); return attributes_; @@ -395,18 +389,18 @@ void AppendToCharacter(char character) { DCHECK_EQ(type_, kCharacter); - data_.push_back(character); + data_.AddChar(character); } void AppendToCharacter(UChar character) { DCHECK_EQ(type_, kCharacter); - data_.push_back(character); + data_.AddChar(character); or_all_data_ |= character; } - void AppendToCharacter(const Vector<LChar, 32>& characters) { + void AppendToCharacter(const LiteralBuffer<LChar, 32>& characters) { DCHECK_EQ(type_, kCharacter); - data_.AppendVector(characters); + data_.AppendLiteral(characters); } /* Comment Tokens */ @@ -424,7 +418,7 @@ void AppendToComment(UChar character) { DCHECK(character); DCHECK_EQ(type_, kComment); - data_.push_back(character); + data_.AddChar(character); or_all_data_ |= character; }
diff --git a/third_party/blink/renderer/core/html/parser/html_tokenizer.cc b/third_party/blink/renderer/core/html/parser/html_tokenizer.cc index 0dbfe99..3bd2080 100644 --- a/third_party/blink/renderer/core/html/parser/html_tokenizer.cc +++ b/third_party/blink/renderer/core/html/parser/html_tokenizer.cc
@@ -47,7 +47,7 @@ return cc | (IsASCIIUpper(cc) ? 0x20 : 0); } -static inline bool VectorEqualsString(const Vector<LChar, 32>& vector, +static inline bool VectorEqualsString(const LiteralBuffer<LChar, 32>& vector, const String& string) { if (vector.size() != string.length()) return false; @@ -308,7 +308,7 @@ HTML_BEGIN_STATE(kRCDATAEndTagOpenState) { if (IsASCIIAlpha(cc)) { - temporary_buffer_.push_back(static_cast<LChar>(cc)); + temporary_buffer_.AddChar(static_cast<LChar>(cc)); AddToPossibleEndTag(static_cast<LChar>(ToLowerCase(cc))); HTML_ADVANCE_PAST_NON_NEWLINE_TO(kRCDATAEndTagNameState); } else { @@ -321,23 +321,23 @@ HTML_BEGIN_STATE(kRCDATAEndTagNameState) { if (IsASCIIAlpha(cc)) { - temporary_buffer_.push_back(static_cast<LChar>(cc)); + temporary_buffer_.AddChar(static_cast<LChar>(cc)); AddToPossibleEndTag(static_cast<LChar>(ToLowerCase(cc))); HTML_CONSUME_NON_NEWLINE(kRCDATAEndTagNameState); } else { if (IsTokenizerWhitespace(cc)) { if (IsAppropriateEndTag()) { - temporary_buffer_.push_back(static_cast<LChar>(cc)); + temporary_buffer_.AddChar(static_cast<LChar>(cc)); FLUSH_AND_ADVANCE_TO(kBeforeAttributeNameState); } } else if (cc == '/') { if (IsAppropriateEndTag()) { - temporary_buffer_.push_back(static_cast<LChar>(cc)); + temporary_buffer_.AddChar(static_cast<LChar>(cc)); FLUSH_AND_ADVANCE_TO(kSelfClosingStartTagState); } } else if (cc == '>') { if (IsAppropriateEndTag()) { - temporary_buffer_.push_back(static_cast<LChar>(cc)); + temporary_buffer_.AddChar(static_cast<LChar>(cc)); return FlushEmitAndResumeIn(source, HTMLTokenizer::kDataState); } } @@ -365,7 +365,7 @@ HTML_BEGIN_STATE(kRAWTEXTEndTagOpenState) { if (IsASCIIAlpha(cc)) { - temporary_buffer_.push_back(static_cast<LChar>(cc)); + temporary_buffer_.AddChar(static_cast<LChar>(cc)); AddToPossibleEndTag(static_cast<LChar>(ToLowerCase(cc))); HTML_ADVANCE_PAST_NON_NEWLINE_TO(kRAWTEXTEndTagNameState); } else { @@ -378,23 +378,23 @@ HTML_BEGIN_STATE(kRAWTEXTEndTagNameState) { if (IsASCIIAlpha(cc)) { - temporary_buffer_.push_back(static_cast<LChar>(cc)); + temporary_buffer_.AddChar(static_cast<LChar>(cc)); AddToPossibleEndTag(static_cast<LChar>(ToLowerCase(cc))); HTML_CONSUME_NON_NEWLINE(kRAWTEXTEndTagNameState); } else { if (IsTokenizerWhitespace(cc)) { if (IsAppropriateEndTag()) { - temporary_buffer_.push_back(static_cast<LChar>(cc)); + temporary_buffer_.AddChar(static_cast<LChar>(cc)); FLUSH_AND_ADVANCE_TO(kBeforeAttributeNameState); } } else if (cc == '/') { if (IsAppropriateEndTag()) { - temporary_buffer_.push_back(static_cast<LChar>(cc)); + temporary_buffer_.AddChar(static_cast<LChar>(cc)); FLUSH_AND_ADVANCE_TO(kSelfClosingStartTagState); } } else if (cc == '>') { if (IsAppropriateEndTag()) { - temporary_buffer_.push_back(static_cast<LChar>(cc)); + temporary_buffer_.AddChar(static_cast<LChar>(cc)); return FlushEmitAndResumeIn(source, HTMLTokenizer::kDataState); } } @@ -426,7 +426,7 @@ HTML_BEGIN_STATE(kScriptDataEndTagOpenState) { if (IsASCIIAlpha(cc)) { - temporary_buffer_.push_back(static_cast<LChar>(cc)); + temporary_buffer_.AddChar(static_cast<LChar>(cc)); AddToPossibleEndTag(static_cast<LChar>(ToLowerCase(cc))); HTML_ADVANCE_PAST_NON_NEWLINE_TO(kScriptDataEndTagNameState); } else { @@ -439,23 +439,23 @@ HTML_BEGIN_STATE(kScriptDataEndTagNameState) { if (IsASCIIAlpha(cc)) { - temporary_buffer_.push_back(static_cast<LChar>(cc)); + temporary_buffer_.AddChar(static_cast<LChar>(cc)); AddToPossibleEndTag(static_cast<LChar>(ToLowerCase(cc))); HTML_CONSUME_NON_NEWLINE(kScriptDataEndTagNameState); } else { if (IsTokenizerWhitespace(cc)) { if (IsAppropriateEndTag()) { - temporary_buffer_.push_back(static_cast<LChar>(cc)); + temporary_buffer_.AddChar(static_cast<LChar>(cc)); FLUSH_AND_ADVANCE_TO(kBeforeAttributeNameState); } } else if (cc == '/') { if (IsAppropriateEndTag()) { - temporary_buffer_.push_back(static_cast<LChar>(cc)); + temporary_buffer_.AddChar(static_cast<LChar>(cc)); FLUSH_AND_ADVANCE_TO(kSelfClosingStartTagState); } } else if (cc == '>') { if (IsAppropriateEndTag()) { - temporary_buffer_.push_back(static_cast<LChar>(cc)); + temporary_buffer_.AddChar(static_cast<LChar>(cc)); return FlushEmitAndResumeIn(source, HTMLTokenizer::kDataState); } } @@ -547,7 +547,7 @@ BufferCharacter('<'); BufferCharacter(cc); temporary_buffer_.clear(); - temporary_buffer_.push_back(static_cast<LChar>(ToLowerCase(cc))); + temporary_buffer_.AddChar(static_cast<LChar>(ToLowerCase(cc))); HTML_ADVANCE_PAST_NON_NEWLINE_TO(kScriptDataDoubleEscapeStartState); } else { BufferCharacter('<'); @@ -558,7 +558,7 @@ HTML_BEGIN_STATE(kScriptDataEscapedEndTagOpenState) { if (IsASCIIAlpha(cc)) { - temporary_buffer_.push_back(static_cast<LChar>(cc)); + temporary_buffer_.AddChar(static_cast<LChar>(cc)); AddToPossibleEndTag(static_cast<LChar>(ToLowerCase(cc))); HTML_ADVANCE_PAST_NON_NEWLINE_TO(kScriptDataEscapedEndTagNameState); } else { @@ -571,23 +571,23 @@ HTML_BEGIN_STATE(kScriptDataEscapedEndTagNameState) { if (IsASCIIAlpha(cc)) { - temporary_buffer_.push_back(static_cast<LChar>(cc)); + temporary_buffer_.AddChar(static_cast<LChar>(cc)); AddToPossibleEndTag(static_cast<LChar>(ToLowerCase(cc))); HTML_CONSUME_NON_NEWLINE(kScriptDataEscapedEndTagNameState); } else { if (IsTokenizerWhitespace(cc)) { if (IsAppropriateEndTag()) { - temporary_buffer_.push_back(static_cast<LChar>(cc)); + temporary_buffer_.AddChar(static_cast<LChar>(cc)); FLUSH_AND_ADVANCE_TO(kBeforeAttributeNameState); } } else if (cc == '/') { if (IsAppropriateEndTag()) { - temporary_buffer_.push_back(static_cast<LChar>(cc)); + temporary_buffer_.AddChar(static_cast<LChar>(cc)); FLUSH_AND_ADVANCE_TO(kSelfClosingStartTagState); } } else if (cc == '>') { if (IsAppropriateEndTag()) { - temporary_buffer_.push_back(static_cast<LChar>(cc)); + temporary_buffer_.AddChar(static_cast<LChar>(cc)); return FlushEmitAndResumeIn(source, HTMLTokenizer::kDataState); } } @@ -610,7 +610,7 @@ HTML_ADVANCE_TO(kScriptDataEscapedState); } else if (IsASCIIAlpha(cc)) { BufferCharacter(cc); - temporary_buffer_.push_back(static_cast<LChar>(ToLowerCase(cc))); + temporary_buffer_.AddChar(static_cast<LChar>(ToLowerCase(cc))); HTML_CONSUME_NON_NEWLINE(kScriptDataDoubleEscapeStartState); } else HTML_RECONSUME_IN(kScriptDataEscapedState); @@ -693,7 +693,7 @@ HTML_ADVANCE_TO(kScriptDataDoubleEscapedState); } else if (IsASCIIAlpha(cc)) { BufferCharacter(cc); - temporary_buffer_.push_back(static_cast<LChar>(ToLowerCase(cc))); + temporary_buffer_.AddChar(static_cast<LChar>(ToLowerCase(cc))); HTML_CONSUME_NON_NEWLINE(kScriptDataDoubleEscapeEndState); } else HTML_RECONSUME_IN(kScriptDataDoubleEscapedState); @@ -1496,7 +1496,7 @@ inline void HTMLTokenizer::AddToPossibleEndTag(LChar cc) { DCHECK(IsEndTagBufferingState(state_)); - buffered_end_tag_name_.push_back(cc); + buffered_end_tag_name_.AddChar(cc); } inline bool HTMLTokenizer::IsAppropriateEndTag() {
diff --git a/third_party/blink/renderer/core/html/parser/html_tokenizer.h b/third_party/blink/renderer/core/html/parser/html_tokenizer.h index e040f2b..7ff835a 100644 --- a/third_party/blink/renderer/core/html/parser/html_tokenizer.h +++ b/third_party/blink/renderer/core/html/parser/html_tokenizer.h
@@ -263,15 +263,15 @@ // http://www.whatwg.org/specs/web-apps/current-work/#preprocessing-the-input-stream InputStreamPreprocessor<HTMLTokenizer> input_stream_preprocessor_; - Vector<UChar, 32> appropriate_end_tag_name_; + LiteralBuffer<UChar, 32> appropriate_end_tag_name_; // http://www.whatwg.org/specs/web-apps/current-work/#temporary-buffer - Vector<LChar, 32> temporary_buffer_; + LiteralBuffer<LChar, 32> temporary_buffer_; // We occationally want to emit both a character token and an end tag // token (e.g., when lexing script). We buffer the name of the end tag // token here so we remember it next time we re-enter the tokenizer. - Vector<LChar, 32> buffered_end_tag_name_; + LiteralBuffer<LChar, 32> buffered_end_tag_name_; HTMLParserOptions options_;
diff --git a/third_party/blink/renderer/core/html/parser/literal_buffer.h b/third_party/blink/renderer/core/html/parser/literal_buffer.h new file mode 100644 index 0000000..e0bad99 --- /dev/null +++ b/third_party/blink/renderer/core/html/parser/literal_buffer.h
@@ -0,0 +1,178 @@ +// Copyright 2021 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. + +#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_HTML_PARSER_LITERAL_BUFFER_H_ +#define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_PARSER_LITERAL_BUFFER_H_ + +#include <algorithm> +#include <memory> +#include <type_traits> +#include "base/bits.h" +#include "base/compiler_specific.h" +#include "base/macros.h" +#include "third_party/blink/renderer/platform/wtf/allocator/partitions.h" +#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" +#include "third_party/blink/renderer/platform/wtf/wtf_size_t.h" + +// For ASAN builds, disable inline buffers completely as they cause various +// issues. +#ifdef ANNOTATE_CONTIGUOUS_CONTAINER +#define BUFFER_INLINE_CAPACITY 0 +#else +#define BUFFER_INLINE_CAPACITY kInlineSize +#endif + +// LiteralBuffer is an optimized version of Vector for LChar and UChar +// characters. In particular `AddChar` is faster than `push_back`, since +// it avoids unnecessary register spills. See https://crbug.com/1205338. +template <typename T, wtf_size_t kInlineSize> +class LiteralBuffer { + static_assert(std::is_same<LChar, T>::value || std::is_same<UChar, T>::value, + "T must be a character type"); + + public: + LiteralBuffer() = default; + LiteralBuffer(const LiteralBuffer& other) { *this = other; } + LiteralBuffer(LiteralBuffer&& other) { *this = std::move(other); } + + ~LiteralBuffer() { + if (!is_stored_inline()) + WTF::Partitions::BufferFree(begin_); + } + + template <wtf_size_t kOtherInlineSize> + LiteralBuffer& operator=(const LiteralBuffer<T, kOtherInlineSize>& other) { + if (this->begin_ == other.data()) + return *this; + wtf_size_t other_size = other.size(); + if (capacity() < other_size) { + // Create large-enough heap-allocated storage. + if (!is_stored_inline()) + WTF::Partitions::BufferFree(begin_); + begin_ = static_cast<T*>(WTF::Partitions::BufferMalloc( + AllocationSize(other_size), "LiteralBuffer")); + end_of_storage_ = begin_ + other_size; + } + std::copy_n(other.data(), other_size, begin_); + end_ = begin_ + other_size; + return *this; + } + + LiteralBuffer& operator=(LiteralBuffer&& other) { + if (this == &other) + return *this; + if (!other.is_stored_inline()) { + if (!is_stored_inline()) + WTF::Partitions::BufferFree(begin_); + begin_ = other.begin_; + end_ = other.end_; + end_of_storage_ = other.end_of_storage_; + other.begin_ = &other.inline_storage[0]; + other.end_ = other.begin_; + other.end_of_storage_ = other.begin_ + BUFFER_INLINE_CAPACITY; + } else { + DCHECK_GE(capacity(), other.size()); // Sanity check. + wtf_size_t other_size = other.size(); + std::copy_n(other.data(), other_size, begin_); + end_ = begin_ + other_size; + } + return *this; + } + + ALWAYS_INLINE const T* data() const { return begin_; } + ALWAYS_INLINE size_t size() const { return end_ - begin_; } + + ALWAYS_INLINE bool IsEmpty() const { return size() == 0; } + + ALWAYS_INLINE const T& operator[](wtf_size_t index) const { + CHECK_GT(size(), index); + return begin_[index]; + } + + // Clear without freeing any storage. + ALWAYS_INLINE void clear() { end_ = begin_; } + + ALWAYS_INLINE void AddChar(T val) { + if (UNLIKELY(end_ == end_of_storage_)) + end_ = Grow(); + *end_++ = val; + } + + template <typename OtherT, wtf_size_t kOtherSize> + void AppendLiteral(const LiteralBuffer<OtherT, kOtherSize>& val) { + static_assert(sizeof(T) >= sizeof(OtherT), + "T is not big enough to contain OtherT"); + size_t count = val.size(); + size_t new_size = size() + count; + if (capacity() < new_size) + Grow(new_size); + std::copy_n(val.data(), count, end_); + end_ += count; + } + + String AsString() const { return String(data(), size()); } + + String AsString8() const { + if (std::is_same<T, LChar>::value) + return AsString(); + return String::Make8BitFrom16BitSource(data(), size()); + } + + AtomicString AsAtomicString() const { return AtomicString(data(), size()); } + + private: + // NOTE: we use pointers to the beginning and the end of the buffer, instead + // of tuple (begin, size, capacity). This makes access of the next characters + // faster when `AddChar` is inlined, since `end_` is readily available in a + // register. + T* begin_ = &inline_storage[0]; + T* end_ = begin_; + T* end_of_storage_ = begin_ + BUFFER_INLINE_CAPACITY; + T inline_storage[BUFFER_INLINE_CAPACITY]; + + size_t AllocationSize(size_t capacity) { + return WTF::PartitionAllocator::QuantizedSize<T>(capacity); + } + + ALWAYS_INLINE size_t capacity() const { return end_of_storage_ - begin_; } + + ALWAYS_INLINE bool is_stored_inline() const { + return begin_ == &inline_storage[0]; + } + + size_t RoundUpToPowerOfTwo(size_t value) { + constexpr size_t digits = 8 * sizeof(size_t); + static_assert(digits == 32 || digits == 64, + "size_t must be either 32 or 64 bits"); + DCHECK_LE(value, size_t{1} << (digits - 1)); + if (value) + --value; + return size_t{1} << (digits - base::bits::CountLeadingZeroBits(value)); + } + + // Grows the backing store by a factor of two. Returns the new end of the used + // storage (this reduces binary size). + NOINLINE T* Grow() { return Grow(0); } + + // Grows the backing store by a factor of two, and at least to `min_capacity`. + NOINLINE T* Grow(size_t min_capacity) { + DCHECK_GE(end_, begin_); + size_t in_use = end_ - begin_; + size_t new_capacity = + RoundUpToPowerOfTwo(std::max(min_capacity, 2 * capacity())); + T* new_storage = static_cast<T*>(WTF::Partitions::BufferMalloc( + AllocationSize(new_capacity), "LiteralBuffer")); + std::copy_n(begin_, in_use, new_storage); + if (!is_stored_inline()) + WTF::Partitions::BufferFree(begin_); + begin_ = new_storage; + end_ = new_storage + in_use; + end_of_storage_ = new_storage + new_capacity; + return end_; + } +}; + +#undef BUFFER_INLINE_CAPACITY + +#endif // THIRD_PARTY_BLINK_RENDERER_CORE_HTML_PARSER_LITERAL_BUFFER_H_
diff --git a/third_party/blink/renderer/core/html/parser/literal_buffer_test.cc b/third_party/blink/renderer/core/html/parser/literal_buffer_test.cc new file mode 100644 index 0000000..8d428ac8 --- /dev/null +++ b/third_party/blink/renderer/core/html/parser/literal_buffer_test.cc
@@ -0,0 +1,96 @@ +// Copyright 2021 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/html/parser/literal_buffer.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace blink { + +namespace { + +TEST(LiteralBufferTest, Empty) { + LiteralBuffer<LChar, 16> buf; + EXPECT_TRUE(buf.IsEmpty()); + EXPECT_EQ(0ul, buf.size()); +} + +TEST(LiteralBufferTest, AddAndClear) { + LiteralBuffer<LChar, 16> buf; + buf.AddChar('a'); + buf.AddChar('b'); + buf.AddChar('c'); + EXPECT_FALSE(buf.IsEmpty()); + EXPECT_EQ(3ul, buf.size()); + EXPECT_EQ(buf[0], 'a'); + EXPECT_EQ(buf[1], 'b'); + EXPECT_EQ(buf[2], 'c'); + + buf.clear(); + EXPECT_TRUE(buf.IsEmpty()); + EXPECT_EQ(0ul, buf.size()); +} + +TEST(LiteralBufferTest, AppendLiteral) { + LiteralBuffer<LChar, 16> lit; + lit.AddChar('a'); + lit.AddChar('b'); + lit.AddChar('c'); + + LiteralBuffer<UChar, 4> buf; + buf.AddChar('d'); + buf.AddChar('e'); + buf.AddChar('f'); + + buf.AppendLiteral(lit); + + EXPECT_EQ(6ul, buf.size()); + EXPECT_EQ(memcmp(buf.data(), u"defabc", buf.size()), 0); +} + +TEST(LiteralBufferTest, Copy) { + LiteralBuffer<LChar, 16> lit; + lit.AddChar('a'); + lit.AddChar('b'); + lit.AddChar('c'); + + LiteralBuffer<LChar, 2> buf; + buf = lit; + + EXPECT_FALSE(buf.IsEmpty()); + EXPECT_EQ(3ul, buf.size()); + EXPECT_EQ(buf[0], 'a'); + EXPECT_EQ(buf[1], 'b'); + EXPECT_EQ(buf[2], 'c'); + + EXPECT_NE(lit.data(), buf.data()); + EXPECT_EQ(lit.size(), buf.size()); + + EXPECT_FALSE(lit.IsEmpty()); + EXPECT_EQ(lit[0], 'a'); + EXPECT_EQ(lit[1], 'b'); + EXPECT_EQ(lit[2], 'c'); +} + +TEST(LiteralBufferTest, Move) { + LiteralBuffer<LChar, 2> lit; + lit.AddChar('a'); + lit.AddChar('b'); + lit.AddChar('c'); + + LiteralBuffer<LChar, 2> buf(std::move(lit)); + + EXPECT_FALSE(buf.IsEmpty()); + EXPECT_EQ(3ul, buf.size()); + EXPECT_EQ(buf[0], 'a'); + EXPECT_EQ(buf[1], 'b'); + EXPECT_EQ(buf[2], 'c'); + + EXPECT_TRUE(lit.IsEmpty()); + EXPECT_EQ(0ul, lit.size()); +} + +} // anonymous namespace + +} // namespace blink
diff --git a/third_party/blink/renderer/core/layout/layout_text.cc b/third_party/blink/renderer/core/layout/layout_text.cc index 49a0486..851c9c51 100644 --- a/third_party/blink/renderer/core/layout/layout_text.cc +++ b/third_party/blink/renderer/core/layout/layout_text.cc
@@ -668,16 +668,34 @@ if (UNLIKELY(HasFlippedBlocksWritingMode())) block_for_flipping = ContainingBlock(); NGInlineCursor cursor; + bool is_last_end_included = false; for (cursor.MoveTo(*this); cursor; cursor.MoveToNextForSameLayoutObject()) { - const NGTextOffset offset = cursor.Current().TextOffset(); - if (start > offset.end || end < offset.start) + const NGFragmentItem& item = *cursor.Current(); + DCHECK(item.IsText()); + bool is_collapsed = false; + PhysicalRect rect; + if (!item.IsGeneratedText()) { + const NGTextOffset& offset = item.TextOffset(); + if (start > offset.end || end < offset.start) { + is_last_end_included = false; + continue; + } + is_last_end_included = offset.end <= end; + const unsigned clamped_start = std::max(start, offset.start); + const unsigned clamped_end = std::min(end, offset.end); + rect = cursor.CurrentLocalRect(clamped_start, clamped_end); + is_collapsed = clamped_start >= clamped_end; + } else if (item.IsEllipsis()) { continue; - const unsigned clamped_start = std::max(start, offset.start); - const unsigned clamped_end = std::min(end, offset.end); - PhysicalRect rect = cursor.CurrentLocalRect(clamped_start, clamped_end); + } else { + // Hyphens. Include if the last end was included. + if (!is_last_end_included) + continue; + rect = item.LocalRect(); + } rect.Move(cursor.CurrentOffsetInBlockFlow()); const FloatQuad quad = LocalRectToAbsoluteQuad(rect); - if (clamped_start < clamped_end) { + if (!is_collapsed) { quads.push_back(quad); found_non_collapsed_quad = true; } else {
diff --git a/third_party/blink/renderer/core/layout/ng/inline/ng_fragment_item.cc b/third_party/blink/renderer/core/layout/ng/inline/ng_fragment_item.cc index cded22b..95ee74c 100644 --- a/third_party/blink/renderer/core/layout/ng/inline/ng_fragment_item.cc +++ b/third_party/blink/renderer/core/layout/ng/inline/ng_fragment_item.cc
@@ -343,13 +343,15 @@ rect_ = unscaled_rect; } -FloatRect NGFragmentItem::FloatRectInContainerFragment() const { +FloatRect NGFragmentItem::ObjectBoundingBox() const { if (Type() != kSVGText) return FloatRect(rect_); const float scaling_factor = To<LayoutSVGInlineText>(GetLayoutObject())->ScalingFactor(); DCHECK_GT(scaling_factor, 0.0f); FloatRect item_rect = SVGFragmentData()->rect; + if (HasSVGTransformForBoundingBox()) + item_rect = BuildSVGTransformForBoundingBox().MapRect(item_rect); item_rect.Scale(1 / scaling_factor); return item_rect; }
diff --git a/third_party/blink/renderer/core/layout/ng/inline/ng_fragment_item.h b/third_party/blink/renderer/core/layout/ng/inline/ng_fragment_item.h index 24048cd..1e24daeb 100644 --- a/third_party/blink/renderer/core/layout/ng/inline/ng_fragment_item.h +++ b/third_party/blink/renderer/core/layout/ng/inline/ng_fragment_item.h
@@ -191,10 +191,11 @@ void SetDeltaToNextForSameLayoutObject(wtf_size_t delta) const; const PhysicalRect& RectInContainerFragment() const { return rect_; } - // This function returns a FloatRect with higher precision for kSVGText + // This function returns a transformed unscaled FloatRect for kSVGText // type, and returns a FloatRect just converted from - // RectInContainerFragment() otherwise. - FloatRect FloatRectInContainerFragment() const; + // RectInContainerFragment() for other types. + FloatRect ObjectBoundingBox() const; + const PhysicalOffset& OffsetInContainerFragment() const { return rect_.offset; }
diff --git a/third_party/blink/renderer/core/layout/ng/inline/ng_inline_layout_algorithm.cc b/third_party/blink/renderer/core/layout/ng/inline/ng_inline_layout_algorithm.cc index ac9a217e..119c4d11 100644 --- a/third_party/blink/renderer/core/layout/ng/inline/ng_inline_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/ng/inline/ng_inline_layout_algorithm.cc
@@ -417,7 +417,10 @@ // Up until this point, children are placed so that the dominant baseline is // at 0. Move them to the final baseline position, and set the logical top of // the line box to the line top. - line_box->MoveInBlockDirection(line_box_metrics.ascent); + // + // For SVG <text>, the initial 'current text position' should be (0, 0). + if (!Node().IsSVGText()) + line_box->MoveInBlockDirection(line_box_metrics.ascent); LayoutUnit block_offset = line_info->BfcOffset().block_offset; if (Node().HasRuby()) {
diff --git a/third_party/blink/renderer/core/layout/ng/svg/layout_ng_svg_text.cc b/third_party/blink/renderer/core/layout/ng/svg/layout_ng_svg_text.cc index 5a08b3d..4a45426 100644 --- a/third_party/blink/renderer/core/layout/ng/svg/layout_ng_svg_text.cc +++ b/third_party/blink/renderer/core/layout/ng/svg/layout_ng_svg_text.cc
@@ -128,10 +128,7 @@ continue; // Do not use item.RectInContainerFragment() in order to avoid // precision loss. - FloatRect item_rect = item.FloatRectInContainerFragment(); - if (item.HasSVGTransformForBoundingBox()) - item_rect = item.BuildSVGTransformForBoundingBox().MapRect(item_rect); - bbox.Unite(item_rect); + bbox.Unite(item.ObjectBoundingBox()); } } bounding_box_ = bbox;
diff --git a/third_party/blink/renderer/core/layout/svg/layout_svg_inline.cc b/third_party/blink/renderer/core/layout/svg/layout_svg_inline.cc index 504c5f74..d89c4ed 100644 --- a/third_party/blink/renderer/core/layout/svg/layout_svg_inline.cc +++ b/third_party/blink/renderer/core/layout/svg/layout_svg_inline.cc
@@ -82,12 +82,8 @@ for (cursor.MoveToIncludingCulledInline(*this); cursor; cursor.MoveToNextForSameLayoutObject()) { const NGFragmentItem& item = *cursor.CurrentItem(); - if (item.Type() != NGFragmentItem::kSVGText) - continue; - FloatRect item_rect = item.FloatRectInContainerFragment(); - if (item.HasSVGTransformForBoundingBox()) - item_rect = item.BuildSVGTransformForBoundingBox().MapRect(item_rect); - bounds.Unite(item_rect); + if (item.Type() == NGFragmentItem::kSVGText) + bounds.Unite(item.ObjectBoundingBox()); } return bounds; } @@ -134,7 +130,7 @@ if (item.Type() == NGFragmentItem::kSVGText) { quads.push_back( LocalToAbsoluteQuad(SVGLayoutSupport::ExtendTextBBoxWithStroke( - *this, item.FloatRectInContainerFragment()), + *this, item.ObjectBoundingBox()), mode)); } }
diff --git a/third_party/blink/renderer/core/typed_arrays/dom_shared_array_buffer.cc b/third_party/blink/renderer/core/typed_arrays/dom_shared_array_buffer.cc index 38e9ff1bb..fa660a2a 100644 --- a/third_party/blink/renderer/core/typed_arrays/dom_shared_array_buffer.cc +++ b/third_party/blink/renderer/core/typed_arrays/dom_shared_array_buffer.cc
@@ -13,8 +13,12 @@ DCHECK(!DOMDataStore::ContainsWrapper(this, script_state->GetIsolate())); const WrapperTypeInfo* wrapper_type_info = GetWrapperTypeInfo(); - v8::Local<v8::SharedArrayBuffer> wrapper = v8::SharedArrayBuffer::New( - script_state->GetIsolate(), Content()->BackingStore()); + v8::Local<v8::SharedArrayBuffer> wrapper; + { + v8::Context::Scope context_scope(script_state->GetContext()); + wrapper = v8::SharedArrayBuffer::New(script_state->GetIsolate(), + Content()->BackingStore()); + } return AssociateWithWrapper(script_state->GetIsolate(), wrapper_type_info, wrapper); }
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc index 3149a6b..e75070b5 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc +++ b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc
@@ -309,21 +309,28 @@ if (configuration->hasSdpSemantics()) { if (configuration->sdpSemantics() == "plan-b") { web_configuration.sdp_semantics = webrtc::SdpSemantics::kPlanB; - if (!RuntimeEnabledFeatures::RTCExtendDeadlineForPlanBRemovalEnabled( - context)) { - // TODO(https://crbug.com/857004): In M93, replace this deprecation - // warning with the throwing of an exception (Reverse Origin Trial is - // required to continue to use Plan B). - Deprecation::CountDeprecation( - context, WebFeature::kRTCPeerConnectionSdpSemanticsPlanB); - } else { - // TODO(https://crbug.com/857004): In M96, replace this deprecation + // Extend the Plan B deprecation deadline if + // RTCExtendDeadlineForPlanBRemoval is enabled, i.e. if the page has opted + // in to the 'RTCPeerConnection Plan B SDP Semantics' Deprecation Trial or + // if --enable-blink-features=RTCExtendDeadlineForPlanBRemoval was used. + // Local files also get the extended deadline beecause "file://" URLs + // cannot sign up for Origin Trials. + if (RuntimeEnabledFeatures::RTCExtendDeadlineForPlanBRemovalEnabled( + context) || + context->Url().IsLocalFile()) { + // TODO(https://crbug.com/857004): In M97, replace this deprecation // warning with the throwing of an exception (Reverse Origin Trial has // ended). Deprecation::CountDeprecation( context, WebFeature:: kRTCPeerConnectionSdpSemanticsPlanBWithReverseOriginTrial); + } else { + // The deadline is not being extended. + // TODO(https://crbug.com/857004): In M93, replace this deprecation + // warning with the throwing of an exception. + Deprecation::CountDeprecation( + context, WebFeature::kRTCPeerConnectionSdpSemanticsPlanB); } } else { DCHECK_EQ(configuration->sdpSemantics(), "unified-plan");
diff --git a/third_party/blink/renderer/platform/scheduler/BUILD.gn b/third_party/blink/renderer/platform/scheduler/BUILD.gn index 9b65415..fd501f1a 100644 --- a/third_party/blink/renderer/platform/scheduler/BUILD.gn +++ b/third_party/blink/renderer/platform/scheduler/BUILD.gn
@@ -240,7 +240,6 @@ "main_thread/frame_task_queue_controller_unittest.cc", "main_thread/idle_time_estimator_unittest.cc", "main_thread/main_thread_metrics_helper_unittest.cc", - "main_thread/main_thread_perftest.cc", "main_thread/main_thread_scheduler_impl_unittest.cc", "main_thread/main_thread_unittest.cc", "main_thread/memory_purge_manager_unittest.cc",
diff --git a/third_party/blink/renderer/platform/scheduler/DEPS b/third_party/blink/renderer/platform/scheduler/DEPS index 5bc12c5..94505c5f 100644 --- a/third_party/blink/renderer/platform/scheduler/DEPS +++ b/third_party/blink/renderer/platform/scheduler/DEPS
@@ -8,7 +8,6 @@ # Dependencies. "+base/atomic_sequence_num.h", "+base/atomicops.h", - "+base/barrier_closure.h", "+base/callback_helpers.h", "+base/cancelable_callback.h", "+base/command_line.h",
diff --git a/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_perftest.cc b/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_perftest.cc deleted file mode 100644 index 23d35949..0000000 --- a/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_perftest.cc +++ /dev/null
@@ -1,90 +0,0 @@ -// Copyright 2021 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 "base/barrier_closure.h" -#include "base/run_loop.h" -#include "base/time/time.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "testing/perf/perf_result_reporter.h" -#include "third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.h" -#include "third_party/blink/renderer/platform/testing/scoped_scheduler_overrider.h" - -// Too slow with TSAN. -#if !defined(THREAD_SANITIZER) - -namespace blink { -namespace scheduler { -namespace { - -constexpr char kMetricPrefix[] = "MainThreadSchedulerPerfTest."; -// Includes time to |PostTask()|. -constexpr char kTimePerTask[] = "time_per_task"; -// Time to |PostTask()|. -constexpr char kTimePerPostTask[] = "time_per_post_task"; -// |time_per_task| - |time_per_post_task|. -constexpr char kTimePerTaskRun[] = "time_per_task_run"; - -class MainThreadPerfTest : public testing::Test { - public: - MainThreadPerfTest() = default; - ~MainThreadPerfTest() override = default; - - void SetUp() override { - scheduler_ = std::make_unique<MainThreadSchedulerImpl>( - base::sequence_manager::CreateSequenceManagerOnCurrentThreadWithPump( - base::MessagePump::Create(base::MessagePumpType::DEFAULT), - base::sequence_manager::SequenceManager::Settings::Builder() - .Build()), - base::nullopt); - scheduler_overrider_ = - std::make_unique<ScopedSchedulerOverrider>(scheduler_.get()); - } - - void TearDown() override { scheduler_->Shutdown(); } - - protected: - std::unique_ptr<MainThreadSchedulerImpl> scheduler_; - std::unique_ptr<ScopedSchedulerOverrider> scheduler_overrider_; - - DISALLOW_COPY_AND_ASSIGN(MainThreadPerfTest); -}; - -TEST_F(MainThreadPerfTest, PostTaskPerformance) { - const int kTaskCount = 1000000; - base::RunLoop run_loop; - auto counter_closure = - base::BarrierClosure(kTaskCount, run_loop.QuitClosure()); - - base::TimeTicks before = base::TimeTicks::Now(); - for (int i = 0; i < kTaskCount; i++) { - scheduler_->DefaultTaskRunner()->PostTask(FROM_HERE, counter_closure); - } - base::TimeTicks after_post_task = base::TimeTicks::Now(); - run_loop.Run(); - base::TimeTicks after = base::TimeTicks::Now(); - - perf_test::PerfResultReporter reporter(kMetricPrefix, - "main_thread_post_task"); - reporter.RegisterImportantMetric(kTimePerPostTask, "ns/iteration"); - reporter.RegisterImportantMetric(kTimePerTask, "ns/iteration"); - reporter.RegisterImportantMetric(kTimePerTaskRun, "ns/iteration"); - - size_t ns_per_post_task = static_cast<size_t>( - (after_post_task - before).InNanoseconds() / kTaskCount); - reporter.AddResult(kTimePerPostTask, ns_per_post_task); - - size_t ns_per_iteration = - static_cast<size_t>((after - before).InNanoseconds() / kTaskCount); - reporter.AddResult(kTimePerTask, ns_per_iteration); - - size_t ns_per_task_iteration = static_cast<size_t>( - (after - after_post_task).InNanoseconds() / kTaskCount); - reporter.AddResult(kTimePerTaskRun, ns_per_task_iteration); -} - -} // namespace -} // namespace scheduler -} // namespace blink - -#endif // defined(THREAD_SANITIZER)
diff --git a/third_party/blink/renderer/platform/widget/compositing/layer_tree_view.cc b/third_party/blink/renderer/platform/widget/compositing/layer_tree_view.cc index c711dca..49cc124 100644 --- a/third_party/blink/renderer/platform/widget/compositing/layer_tree_view.cc +++ b/third_party/blink/renderer/platform/widget/compositing/layer_tree_view.cc
@@ -382,6 +382,13 @@ void LayerTreeView::DidLoseLayerTreeFrameSink() {} +void LayerTreeView::ScheduleAnimationForWebTests() { + if (!delegate_) + return; + + delegate_->ScheduleAnimationForWebTests(); +} + void LayerTreeView::AddPresentationCallback( uint32_t frame_token, base::OnceCallback<void(base::TimeTicks)> callback) {
diff --git a/third_party/blink/renderer/platform/widget/compositing/layer_tree_view.h b/third_party/blink/renderer/platform/widget/compositing/layer_tree_view.h index e49efed..4a17a42 100644 --- a/third_party/blink/renderer/platform/widget/compositing/layer_tree_view.h +++ b/third_party/blink/renderer/platform/widget/compositing/layer_tree_view.h
@@ -114,6 +114,7 @@ // cc::LayerTreeHostSingleThreadClient implementation. void DidSubmitCompositorFrame() override; void DidLoseLayerTreeFrameSink() override; + void ScheduleAnimationForWebTests() override; // cc::LayerTreeHostSchedulingClient implementation. void DidScheduleBeginMainFrame() override;
diff --git a/third_party/blink/renderer/platform/widget/compositing/layer_tree_view_delegate.h b/third_party/blink/renderer/platform/widget/compositing/layer_tree_view_delegate.h index d21c055a..01877e8 100644 --- a/third_party/blink/renderer/platform/widget/compositing/layer_tree_view_delegate.h +++ b/third_party/blink/renderer/platform/widget/compositing/layer_tree_view_delegate.h
@@ -106,7 +106,11 @@ virtual void WillBeginMainFrame() = 0; virtual void RunPaintBenchmark(int repeat_count, - cc::PaintBenchmarkResult& result) {} + cc::PaintBenchmarkResult& result) = 0; + + // Used in web tests without threaded compositing, to indicate that a new + // commit needs to be scheduled. Has no effect in any other mode. + virtual void ScheduleAnimationForWebTests() = 0; protected: virtual ~LayerTreeViewDelegate() {}
diff --git a/third_party/blink/renderer/platform/widget/compositing/test/stub_layer_tree_view_delegate.h b/third_party/blink/renderer/platform/widget/compositing/test/stub_layer_tree_view_delegate.h index 9dc29b68..cca220a 100644 --- a/third_party/blink/renderer/platform/widget/compositing/test/stub_layer_tree_view_delegate.h +++ b/third_party/blink/renderer/platform/widget/compositing/test/stub_layer_tree_view_delegate.h
@@ -51,6 +51,9 @@ void EndUpdateLayers() override {} void UpdateVisualState() override {} void WillBeginMainFrame() override {} + void RunPaintBenchmark(int repeat_count, + cc::PaintBenchmarkResult& result) override {} + void ScheduleAnimationForWebTests() override {} }; } // namespace blink
diff --git a/third_party/blink/renderer/platform/widget/widget_base.cc b/third_party/blink/renderer/platform/widget/widget_base.cc index dc6ae1a..a4bc9ac 100644 --- a/third_party/blink/renderer/platform/widget/widget_base.cc +++ b/third_party/blink/renderer/platform/widget/widget_base.cc
@@ -761,6 +761,10 @@ client_->RunPaintBenchmark(repeat_count, result); } +void WidgetBase::ScheduleAnimationForWebTests() { + client_->ScheduleAnimationForWebTests(); +} + void WidgetBase::SetCompositorVisible(bool visible) { if (never_composited_) return;
diff --git a/third_party/blink/renderer/platform/widget/widget_base.h b/third_party/blink/renderer/platform/widget/widget_base.h index 0e6f7f5..563c9e6 100644 --- a/third_party/blink/renderer/platform/widget/widget_base.h +++ b/third_party/blink/renderer/platform/widget/widget_base.h
@@ -162,6 +162,7 @@ void WillBeginMainFrame() override; void RunPaintBenchmark(int repeat_count, cc::PaintBenchmarkResult& result) override; + void ScheduleAnimationForWebTests() override; cc::AnimationHost* AnimationHost() const; cc::LayerTreeHost* LayerTreeHost() const;
diff --git a/third_party/blink/renderer/platform/wtf/text/atomic_string.h b/third_party/blink/renderer/platform/wtf/text/atomic_string.h index 84bf1741..a533ffaa 100644 --- a/third_party/blink/renderer/platform/wtf/text/atomic_string.h +++ b/third_party/blink/renderer/platform/wtf/text/atomic_string.h
@@ -77,10 +77,6 @@ AtomicString(const UChar* chars, unsigned length); AtomicString(const UChar* chars); - template <wtf_size_t inlineCapacity> - explicit AtomicString(const Vector<UChar, inlineCapacity>& vector) - : AtomicString(vector.data(), vector.size()) {} - // Constructing an AtomicString from a String / StringImpl can be expensive if // the StringImpl is not already atomic. explicit AtomicString(StringImpl* impl) : string_(Add(impl)) {}
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index e5efb2e..1bfc479c 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -1095,6 +1095,7 @@ crbug.com/874051 virtual/layout_ng_block_frag/external/wpt/css/css-multicol/multicol-span-all-fieldset-002.html [ Failure Crash ] crbug.com/1130451 virtual/layout_ng_block_frag/external/wpt/css/css-multicol/multicol-span-all-list-item-001.html [ Failure ] crbug.com/1130451 virtual/layout_ng_block_frag/external/wpt/css/css-multicol/multicol-span-all-list-item-002.html [ Failure ] +crbug.com/1058792 virtual/layout_ng_block_frag/fast/multicol/composited-opacity-2nd-and-3rd-column.html [ Failure ] crbug.com/1151880 virtual/layout_ng_block_frag/fast/multicol/dynamic/relpos-becomes-static-has-abspos.html [ Failure ] crbug.com/1151880 virtual/layout_ng_block_frag/fast/multicol/dynamic/remove-column-content-next-to-abspos-between-spanners.html [ Failure ] crbug.com/1079031 virtual/layout_ng_block_frag/fast/multicol/dynamic/static-becomes-relpos-has-abspos.html [ Failure ] @@ -1936,8 +1937,6 @@ crbug.com/694525 external/wpt/content-security-policy/navigation/to-javascript-parent-initiated-child-csp.html [ Skip ] crbug.com/694525 external/wpt/content-security-policy/unsafe-eval/eval-blocked-in-about-blank-iframe.sub.html [ Skip ] -crbug.com/1199754 virtual/plz-dedicated-worker/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/dedicated-worker.tentative.https.html [ Timeout ] - # These tests will be added back soon: crbug.com/706350 external/wpt/html/browsers/browsing-the-web/history-traversal/window-name-after-cross-origin-aux-frame-navigation.sub.html [ Skip ] crbug.com/706350 external/wpt/html/browsers/browsing-the-web/history-traversal/window-name-after-cross-origin-main-frame-navigation.sub.html [ Skip ] @@ -4264,8 +4263,6 @@ crbug.com/1179585 virtual/layout_ng_svg_text/paint/invalidation/svg/use-detach.svg [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/paint/invalidation/svg/use-event-handler-on-use-element.svg [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/animations/animate-text-nested-transforms.html [ Timeout ] -crbug.com/1179585 virtual/layout_ng_svg_text/svg/batik/paints/patternRegions.svg [ Failure ] -crbug.com/1179585 virtual/layout_ng_svg_text/svg/batik/paints/patternRegions-positioned-objects.svg [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/batik/text/longTextOnPath.svg [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/batik/text/smallFonts.svg [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/batik/text/textAnchor2.svg [ Failure ] @@ -4282,7 +4279,6 @@ crbug.com/1179585 virtual/layout_ng_svg_text/svg/batik/text/textOnPath2.svg [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/batik/text/textOnPath3.svg [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/batik/text/textOnPathSpaces.svg [ Failure ] -crbug.com/1179585 virtual/layout_ng_svg_text/svg/batik/text/textPCDATA.svg [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/batik/text/textProperties.svg [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/batik/text/verticalText.svg [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/batik/text/verticalTextOnPath.svg [ Failure Crash ] @@ -4385,7 +4381,6 @@ crbug.com/1179585 virtual/layout_ng_svg_text/svg/text/non-invertible-matrix-text.svg [ Pass Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/text/obb-paintserver.html [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/text/removing-id-on-path.html [ Failure ] -crbug.com/1179585 virtual/layout_ng_svg_text/svg/text/scaling-font-with-geometric-precision.html [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/text/selection-background-color.xhtml [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/text/selection-doubleclick.svg [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/text/selection-dragging-outside-1.html [ Failure ] @@ -4419,8 +4414,6 @@ crbug.com/1179585 virtual/layout_ng_svg_text/svg/text/select-x-list-with-tspans-2.svg [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/text/select-x-list-with-tspans-3.svg [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/text/select-x-list-with-tspans-4.svg [ Failure ] -crbug.com/1179585 virtual/layout_ng_svg_text/svg/text/small-fonts.svg [ Failure ] -crbug.com/1179585 virtual/layout_ng_svg_text/svg/text/small-fonts-2.svg [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/text/surrogate-pair-attribute-positions.html [ Pass Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/text/surrogate-pair-queries.html [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/text/svgtextcontentelement-glyphqueries-rtl.html [ Failure ] @@ -4507,29 +4500,10 @@ crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-I18N/tspan-dirRTL-ubOverride-in-default-context.svg [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-I18N/tspan-dirRTL-ubOverride-in-ltr-context.svg [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-I18N/tspan-dirRTL-ubOverride-in-rtl-context.svg [ Failure ] -crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-24-t.svg [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-36-t.svg [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-39-t.svg [ Failure ] -crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-41-t.svg [ Failure ] -crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-60-t.svg [ Failure ] -crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-61-t.svg [ Failure ] -crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-62-t.svg [ Failure ] -crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-63-t.svg [ Failure ] -crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-64-t.svg [ Failure ] -crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-65-t.svg [ Failure ] -crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-66-t.svg [ Failure ] -crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-67-t.svg [ Failure ] -crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-68-t.svg [ Failure ] -crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-69-t.svg [ Failure ] -crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-70-t.svg [ Failure ] -crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-78-t.svg [ Failure ] -crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-84-t.svg [ Failure ] -crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-85-t.svg [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/filters-example-01-b.svg [ Failure ] -crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/fonts-elem-03-b.svg [ Failure ] -crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/fonts-elem-04-b.svg [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/fonts-elem-07-b.svg [ Failure ] -crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/interact-zoom-01-t.svg [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/masking-mask-01-b.svg [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/masking-path-04-b.svg [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/pservers-grad-08-b.svg [ Failure ] @@ -4537,9 +4511,6 @@ crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/pservers-pattern-01-b.svg [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/render-elems-07-t.svg [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/render-elems-08-t.svg [ Failure ] -crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/struct-group-03-t.svg [ Failure ] -crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/struct-use-01-t.svg [ Failure ] -crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/text-align-01-b.svg [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/text-align-02-b.svg [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/text-align-04-b.svg [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/text-align-05-b.svg [ Failure ] @@ -4549,17 +4520,12 @@ crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/text-path-01-b.svg [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/text-spacing-01-b.svg [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/text-text-03-b.svg [ Failure ] -crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/text-text-04-t.svg [ Failure ] -crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/text-text-06-t.svg [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/text-text-08-b.svg [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/text-tselect-02-f.svg [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1-SE/filters-image-03-f.svg [ Failure ] -crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1-SE/filters-image-05-f.svg [ Failure ] -crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1-SE/painting-marker-05-f.svg [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1-SE/pservers-pattern-03-f.svg [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1-SE/struct-use-14-f.svg [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1-SE/svgdom-over-01-f.svg [ Failure ] -crbug.com/1179585 virtual/layout_ng_svg_text/svg/W3C-SVG-1.1-SE/text-tspan-02-b.svg [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/zoom/page/zoom-zoom-coords.xhtml [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/zoom/text/lowdpi-zoom-text.html [ Failure ] crbug.com/1179585 virtual/layout_ng_svg_text/svg/zoom/zoomed-text-in-clippath.html [ Failure ] @@ -6240,6 +6206,9 @@ # Sheriff 2020-09-21 crbug.com/1130500 [ Mac10.13 Debug ] virtual/plz-dedicated-worker/external/wpt/xhr/xhr-timeout-longtask.any.worker.html [ Pass Failure ] +# Temporarily disabled to unblock https://crrev.com/c/2878734 +crbug.com/1159307 inspector-protocol/debugger/wasm-compiled-streaming-breaks.js [ Pass Failure ] + # Sheriff 2020-09-22 crbug.com/1130533 [ Mac ] external/wpt/xhr/xhr-timeout-longtask.any.html [ Pass Failure ]
diff --git a/third_party/blink/web_tests/android/ChromeWPTOverrideExpectations b/third_party/blink/web_tests/android/ChromeWPTOverrideExpectations index ae5b317e..7e8c2716 100644 --- a/third_party/blink/web_tests/android/ChromeWPTOverrideExpectations +++ b/third_party/blink/web_tests/android/ChromeWPTOverrideExpectations
@@ -879,13 +879,13 @@ crbug.com/1050754 external/wpt/html/canvas/offscreen/text/2d.text.measure.fontBoundingBox.html [ Failure ] crbug.com/1050754 external/wpt/html/canvas/offscreen/text/2d.text.measure.fontBoundingBox.worker.html [ Failure ] crbug.com/1050754 external/wpt/html/canvas/offscreen/the-offscreen-canvas/2d.getcontext.extraargs.worker.html [ Pass ] -crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/fetch.tentative.https.html [ Failure Pass ] -crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/iframe.tentative.html [ Failure Pass ] -crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/image.tentative.https.html [ Crash Failure Pass ] -crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/link.tentative.https.html [ Crash Failure Pass ] -crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/redirect.tentative.html [ Failure Pass ] -crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/script.tentative.https.html [ Crash Failure Pass ] -crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/video.tentative.https.html [ Crash Timeout ] +crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/credentialless/fetch.tentative.https.html [ Failure Pass ] +crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/credentialless/iframe.tentative.html [ Failure Pass ] +crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/credentialless/image.tentative.https.html [ Crash Failure Pass ] +crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/credentialless/link.tentative.https.html [ Crash Failure Pass ] +crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/credentialless/redirect.tentative.html [ Failure Pass ] +crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/credentialless/script.tentative.https.html [ Crash Failure Pass ] +crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/credentialless/video.tentative.https.html [ Crash Timeout ] crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/reporting-navigation.https.html [ Failure Pass ] crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/reporting-subresource-corp.https.html [ Crash Failure ] crbug.com/1050754 external/wpt/html/cross-origin-opener-policy/coep-navigate-popup.https.html?0-1 [ Timeout ]
diff --git a/third_party/blink/web_tests/android/WebLayerWPTOverrideExpectations b/third_party/blink/web_tests/android/WebLayerWPTOverrideExpectations index 0e57f7f..e1abd74 100644 --- a/third_party/blink/web_tests/android/WebLayerWPTOverrideExpectations +++ b/third_party/blink/web_tests/android/WebLayerWPTOverrideExpectations
@@ -946,16 +946,16 @@ crbug.com/1050754 external/wpt/html/canvas/offscreen/text/2d.text.measure.fontBoundingBox.html [ Failure ] crbug.com/1050754 external/wpt/html/canvas/offscreen/text/2d.text.measure.fontBoundingBox.worker.html [ Failure ] crbug.com/1050754 external/wpt/html/canvas/offscreen/the-offscreen-canvas/2d.getcontext.extraargs.worker.html [ Pass ] -crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/cross-origin-isolated.html [ Pass Timeout ] -crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/fetch.tentative.https.html [ Failure Pass ] -crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/iframe.tentative.html [ Pass Timeout ] -crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/image.tentative.https.html [ Failure Pass ] -crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/link.tentative.https.html [ Failure Pass ] -crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/redirect.tentative.html [ Failure Pass Timeout ] -crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/script.tentative.https.html [ Failure Pass ] -crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/service-worker.tentative.https.html [ Failure Pass ] -crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/shared-worker.tentative.https.html [ Pass Timeout ] -crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/video.tentative.https.html [ Timeout ] +crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/cors-or-credentialless/cross-origin-isolated.html [ Pass Timeout ] +crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/cors-or-credentialless/fetch.tentative.https.html [ Failure Pass ] +crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/cors-or-credentialless/iframe.tentative.html [ Pass Timeout ] +crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/cors-or-credentialless/image.tentative.https.html [ Failure Pass ] +crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/cors-or-credentialless/link.tentative.https.html [ Failure Pass ] +crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/cors-or-credentialless/redirect.tentative.html [ Failure Pass Timeout ] +crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/cors-or-credentialless/script.tentative.https.html [ Failure Pass ] +crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/cors-or-credentialless/service-worker.tentative.https.html [ Failure Pass ] +crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/cors-or-credentialless/shared-worker.tentative.https.html [ Pass Timeout ] +crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/cors-or-credentialless/video.tentative.https.html [ Timeout ] crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/multi-globals/workers-coep-report.https.html [ Failure ] crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/none.https.html [ Pass Timeout ] crbug.com/1050754 external/wpt/html/cross-origin-embedder-policy/reporting-navigation.https.html [ Failure Pass ]
diff --git a/third_party/blink/web_tests/external/wpt/css/cssom-view/getBoundingClientRect-shy.html b/third_party/blink/web_tests/external/wpt/css/cssom-view/getBoundingClientRect-shy.html new file mode 100644 index 0000000..b27a7884 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/cssom-view/getBoundingClientRect-shy.html
@@ -0,0 +1,93 @@ +<!DOCTYPE html> +<link rel="help" href="https://drafts.csswg.org/cssom-view/#dom-element-getboundingclientrect"> +<link rel="author" title="Koji Ishii" href="mailto:kojii@chromium.org"> +<link rel="stylesheet" type="text/css" href="/fonts/ahem.css"> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<style> +#container { + font-family: Ahem; + font-size: 10px; + line-height: 1; + width: 10ch; +} +</style> +<body> + <div id="container"> + <div id="test1">123456­789012</div> + <div id="test2">123456­789012­345678­901234</div> + <div id="test3">12­456­789012</div> + <div>123<span id="test4">­</span>456<span id="test5">­</span>789012</div> + </div> +<script> +function getBoundingClientRect(node, start, end) { + const range = document.createRange(); + range.setStart(node, start); + range.setEnd(node, end); + const rect = range.getBoundingClientRect(); + return rect; +} + +test(() => { + const rect = getBoundingClientRect(test1.firstChild, 0, 5); + assert_equals(rect.width, 50); +}, "Range 0-5 should not include the hyphen."); + +test(() => { + const rect = getBoundingClientRect(test1.firstChild, 1, 5); + assert_equals(rect.width, 40); +}, "Range 1-5 should not include the hyphen."); + +test(() => { + const rect = getBoundingClientRect(test1.firstChild, 0, 6); + assert_equals(rect.width, 60); +}, "Range 0-6 should not include the hyphen."); + +test(() => { + const rect = getBoundingClientRect(test1.firstChild, 1, 6); + assert_equals(rect.width, 50); +}, "Range 1-6 should not include the hyphen."); + +test(() => { + const rect = getBoundingClientRect(test1.firstChild, 0, 7); + assert_equals(rect.width, 70); +}, "Range 0-7 should include the hyphen."); + +test(() => { + const rect = getBoundingClientRect(test1.firstChild, 1, 7); + assert_equals(rect.width, 60); +}, "Range 1-7 should include the hyphen."); + +test(() => { + const rect = getBoundingClientRect(test1.firstChild, 0, 8); + assert_equals(rect.width, 70); + assert_equals(rect.height, 20); +}, "Range 0-8 should include the hyphen."); + +test(() => { + const rect = getBoundingClientRect(test2.firstChild, 0, 8); + assert_equals(rect.width, 70); + assert_equals(rect.height, 20); +}, "Range 0-8 should include only the first hyphen."); + +test(() => { + const rect = getBoundingClientRect(test3.firstChild, 2, 3); + assert_equals(rect.width, 0); +}, "Collapsed soft-hyphen should be 0 width."); + +test(() => { + const rect = getBoundingClientRect(test3.firstChild, 6, 7); + assert_equals(rect.width, 10); +}, "Rendered soft-hyphen should have a width."); + +test(() => { + const rect = getBoundingClientRect(test4.firstChild, 0, 1); + assert_equals(rect.width, 0); +}, "Collapsed soft-hyphen in a span should be 0 width."); + +test(() => { + const rect = getBoundingClientRect(test5.firstChild, 0, 1); + assert_equals(rect.width, 10); +}, "Rendered soft-hyphen in a span should have a width."); +</script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/full-credentialless/cookie.tentative.https-expected.txt b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/anonymous-iframe/cookie.tentative.https-expected.txt similarity index 100% rename from third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/full-credentialless/cookie.tentative.https-expected.txt rename to third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/anonymous-iframe/cookie.tentative.https-expected.txt
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/full-credentialless/cookie.tentative.https.html b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/anonymous-iframe/cookie.tentative.https.html similarity index 96% rename from third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/full-credentialless/cookie.tentative.https.html rename to third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/anonymous-iframe/cookie.tentative.https.html index acd60c5..43282dd 100644 --- a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/full-credentialless/cookie.tentative.https.html +++ b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/anonymous-iframe/cookie.tentative.https.html
@@ -2,9 +2,9 @@ <script src="/resources/testharnessreport.js"></script> <script src="/common/get-host-info.sub.js"></script> <script src="/common/utils.js"></script> +<script src="../credentialless/resources/common.js"></script> +<script src="../credentialless/resources/dispatcher.js"></script> <script src="./resources/common.js"></script> -<script src="../resources/common.js"></script> -<script src="../resources/dispatcher.js"></script> <script> const same_origin = get_host_info().HTTPS_ORIGIN;
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/full-credentialless/local-storage.tentative.https-expected.txt b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/anonymous-iframe/local-storage.tentative.https-expected.txt similarity index 100% rename from third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/full-credentialless/local-storage.tentative.https-expected.txt rename to third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/anonymous-iframe/local-storage.tentative.https-expected.txt
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/full-credentialless/local-storage.tentative.https.html b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/anonymous-iframe/local-storage.tentative.https.html similarity index 93% rename from third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/full-credentialless/local-storage.tentative.https.html rename to third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/anonymous-iframe/local-storage.tentative.https.html index 28b7c78..a49eac7 100644 --- a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/full-credentialless/local-storage.tentative.https.html +++ b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/anonymous-iframe/local-storage.tentative.https.html
@@ -2,9 +2,9 @@ <script src="/resources/testharnessreport.js"></script> <script src="/common/get-host-info.sub.js"></script> <script src="/common/utils.js"></script> +<script src="../credentialless/resources/common.js"></script> +<script src="../credentialless/resources/dispatcher.js"></script> <script src="./resources/common.js"></script> -<script src="../resources/common.js"></script> -<script src="../resources/dispatcher.js"></script> <script> const same_origin = get_host_info().HTTPS_ORIGIN;
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/full-credentialless/resources/common.js b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/anonymous-iframe/resources/common.js similarity index 100% rename from third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/full-credentialless/resources/common.js rename to third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/anonymous-iframe/resources/common.js
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/cross-origin-isolated.html b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cross-origin-isolated.html similarity index 94% rename from third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/cross-origin-isolated.html rename to third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cross-origin-isolated.html index 37f07581..86d30cdb 100644 --- a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/cross-origin-isolated.html +++ b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cross-origin-isolated.html
@@ -2,8 +2,8 @@ <script src="/resources/testharnessreport.js"></script> <script src="/common/get-host-info.sub.js"></script> <script src="/common/utils.js"></script> -<script src="../resources/common.js"></script> -<script src="../resources/dispatcher.js"></script> +<script src="./resources/common.js"></script> +<script src="./resources/dispatcher.js"></script> <script> const http = get_host_info().HTTP_ORIGIN;
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/dedicated-worker.tentative.https-expected.txt b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/dedicated-worker.tentative.https-expected.txt similarity index 90% rename from third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/dedicated-worker.tentative.https-expected.txt rename to third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/dedicated-worker.tentative.https-expected.txt index 000a3b27..6998fdc 100644 --- a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/dedicated-worker.tentative.https-expected.txt +++ b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/dedicated-worker.tentative.https-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -PASS CORS or Credentialless and dedicated worker +PASS dedicated-worker PASS fetch same-origin + credentialless worker FAIL fetch same-origin assert_equals: coep:credentialless => expected "Worker blocked" but got "same_origin" FAIL fetch cross-origin assert_equals: coep:credentialless => expected (string) "Worker blocked" but got (undefined) undefined
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/dedicated-worker.tentative.https.html b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/dedicated-worker.tentative.https.html similarity index 96% rename from third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/dedicated-worker.tentative.https.html rename to third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/dedicated-worker.tentative.https.html index e02620e..33e6e17 100644 --- a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/dedicated-worker.tentative.https.html +++ b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/dedicated-worker.tentative.https.html
@@ -1,12 +1,11 @@ <!doctype html> -<title>CORS or Credentialless and dedicated worker</title> <meta name="timeout" content="long"> <script src=/resources/testharness.js></script> <script src=/resources/testharnessreport.js></script> <script src="/common/get-host-info.sub.js"></script> <script src="/common/utils.js"></script> -<script src="../resources/common.js"></script> -<script src="../resources/dispatcher.js"></script> +<script src="./resources/common.js"></script> +<script src="./resources/dispatcher.js"></script> <script> const same_origin = get_host_info().HTTPS_ORIGIN;
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/fetch.tentative.https.html b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/fetch.tentative.https.html similarity index 97% rename from third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/fetch.tentative.https.html rename to third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/fetch.tentative.https.html index befad16..b6c84a8e 100644 --- a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/fetch.tentative.https.html +++ b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/fetch.tentative.https.html
@@ -2,8 +2,8 @@ <script src="/resources/testharnessreport.js"></script> <script src="/common/get-host-info.sub.js"></script> <script src="/common/utils.js"></script> -<script src="../resources/common.js"></script> -<script src="../resources/dispatcher.js"></script> +<script src="./resources/common.js"></script> +<script src="./resources/dispatcher.js"></script> <script> promise_test(async test => {
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/iframe-coep-credentialless.tentative.https.html b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/iframe-coep-credentialless.tentative.https.html similarity index 95% rename from third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/iframe-coep-credentialless.tentative.https.html rename to third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/iframe-coep-credentialless.tentative.https.html index 606093c..85d2be9 100644 --- a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/iframe-coep-credentialless.tentative.https.html +++ b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/iframe-coep-credentialless.tentative.https.html
@@ -2,8 +2,8 @@ <script src="/resources/testharnessreport.js"></script> <script src="/common/get-host-info.sub.js"></script> <script src="/common/utils.js"></script> -<script src="../resources/common.js"></script> -<script src="../resources/dispatcher.js"></script> +<script src="./resources/common.js"></script> +<script src="./resources/dispatcher.js"></script> <script src="./resources/iframeTest.js"></script> <script>
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/iframe-coep-none.tentative.https.html b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/iframe-coep-none.tentative.https.html similarity index 91% rename from third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/iframe-coep-none.tentative.https.html rename to third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/iframe-coep-none.tentative.https.html index 570454ef..ad28c3a 100644 --- a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/iframe-coep-none.tentative.https.html +++ b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/iframe-coep-none.tentative.https.html
@@ -2,8 +2,8 @@ <script src="/resources/testharnessreport.js"></script> <script src="/common/get-host-info.sub.js"></script> <script src="/common/utils.js"></script> -<script src="../resources/common.js"></script> -<script src="../resources/dispatcher.js"></script> +<script src="./resources/common.js"></script> +<script src="./resources/dispatcher.js"></script> <script src="./resources/iframeTest.js"></script> <script>
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/iframe-coep-require-corp.tentative.https.html b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/iframe-coep-require-corp.tentative.https.html similarity index 95% rename from third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/iframe-coep-require-corp.tentative.https.html rename to third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/iframe-coep-require-corp.tentative.https.html index 08f9642..622676d 100644 --- a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/iframe-coep-require-corp.tentative.https.html +++ b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/iframe-coep-require-corp.tentative.https.html
@@ -2,8 +2,8 @@ <script src="/resources/testharnessreport.js"></script> <script src="/common/get-host-info.sub.js"></script> <script src="/common/utils.js"></script> -<script src="../resources/common.js"></script> -<script src="../resources/dispatcher.js"></script> +<script src="./resources/common.js"></script> +<script src="./resources/dispatcher.js"></script> <script src="./resources/iframeTest.js"></script> <script>
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/iframe.tentative.html b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/iframe.tentative.html similarity index 86% rename from third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/iframe.tentative.html rename to third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/iframe.tentative.html index b023cce..2b6c839 100644 --- a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/iframe.tentative.html +++ b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/iframe.tentative.html
@@ -3,8 +3,8 @@ <script src="/resources/testharnessreport.js"></script> <script src="/common/get-host-info.sub.js"></script> <script src="/common/utils.js"></script> -<script src="../resources/common.js"></script> -<script src="../resources/dispatcher.js"></script> +<script src="./resources/common.js"></script> +<script src="./resources/dispatcher.js"></script> <script> const same_origin = get_host_info().HTTPS_ORIGIN; @@ -13,14 +13,14 @@ const cookie_same_origin = "same_origin"; const cookie_cross_origin = "cross_origin"; -// Operate on a window with COEP:cors-or-credentialless. +// Operate on a window with COEP:credentialless. const w_token = token(); const w_url = same_origin + executor_path + coep_credentialless + `&uuid=${w_token}` const w = window.open(w_url); add_completion_callback(() => w.close()); -// Check whether COEP:cors-or-credentialless applies to navigation request. It +// Check whether COEP:credentialless applies to navigation request. It // shouldn't. const iframeTest = function(name, origin, expected_cookies) { promise_test_parallel(async test => {
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/image.tentative.https.html b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/image.tentative.https.html similarity index 96% rename from third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/image.tentative.https.html rename to third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/image.tentative.https.html index f1419e15..68783f4 100644 --- a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/image.tentative.https.html +++ b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/image.tentative.https.html
@@ -2,8 +2,8 @@ <script src="/resources/testharnessreport.js"></script> <script src="/common/get-host-info.sub.js"></script> <script src="/common/utils.js"></script> -<script src="../resources/common.js"></script> -<script src="../resources/dispatcher.js"></script> +<script src="./resources/common.js"></script> +<script src="./resources/dispatcher.js"></script> <script>
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/link.tentative.https.html b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/link.tentative.https.html similarity index 96% rename from third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/link.tentative.https.html rename to third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/link.tentative.https.html index 9fc6492..c76c2dca 100644 --- a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/link.tentative.https.html +++ b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/link.tentative.https.html
@@ -2,8 +2,8 @@ <script src="/resources/testharnessreport.js"></script> <script src="/common/get-host-info.sub.js"></script> <script src="/common/utils.js"></script> -<script src="../resources/common.js"></script> -<script src="../resources/dispatcher.js"></script> +<script src="./resources/common.js"></script> +<script src="./resources/dispatcher.js"></script> <script>
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/redirect.tentative.html b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/redirect.tentative.html similarity index 92% rename from third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/redirect.tentative.html rename to third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/redirect.tentative.html index 0aa8b2d..f4c0a4d 100644 --- a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/redirect.tentative.html +++ b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/redirect.tentative.html
@@ -3,8 +3,8 @@ <script src="/resources/testharnessreport.js"></script> <script src="/common/get-host-info.sub.js"></script> <script src="/common/utils.js"></script> -<script src="../resources/common.js"></script> -<script src="../resources/dispatcher.js"></script> +<script src="./resources/common.js"></script> +<script src="./resources/dispatcher.js"></script> <script> const same_origin = get_host_info().HTTPS_ORIGIN; @@ -13,7 +13,7 @@ const cookie_same_origin = "same_origin"; const cookie_cross_origin = "cross_origin"; -// Operate on a window with COEP:cors-or-credentialless. +// Operate on a window with COEP:credentialless.: const w_token = token(); const w_url = same_origin + executor_path + coep_credentialless + `&uuid=${w_token}`
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/resources/common.js b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/resources/common.js index 62f27ae..f203a82b 100644 --- a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/resources/common.js +++ b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/resources/common.js
@@ -6,13 +6,13 @@ const coep_none = '|header(Cross-Origin-Embedder-Policy,none)'; const coep_credentialless = - '|header(Cross-Origin-Embedder-Policy,cors-or-credentialless)'; + '|header(Cross-Origin-Embedder-Policy,credentialless)'; const coep_require_corp = '|header(Cross-Origin-Embedder-Policy,require-corp)'; // COEP-Report-Only const coep_report_only_credentialless = - '|header(Cross-Origin-Embedder-Policy-Report-Only,cors-or-credentialless)'; + '|header(Cross-Origin-Embedder-Policy-Report-Only,credentialless)'; // COOP const coop_same_origin =
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/resources/iframeTest.js b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/resources/iframeTest.js similarity index 100% rename from third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/resources/iframeTest.js rename to third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/resources/iframeTest.js
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/script.tentative.https.html b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/script.tentative.https.html similarity index 96% rename from third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/script.tentative.https.html rename to third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/script.tentative.https.html index cbed45d..cac1d46 100644 --- a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/script.tentative.https.html +++ b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/script.tentative.https.html
@@ -2,8 +2,8 @@ <script src="/resources/testharnessreport.js"></script> <script src="/common/get-host-info.sub.js"></script> <script src="/common/utils.js"></script> -<script src="../resources/common.js"></script> -<script src="../resources/dispatcher.js"></script> +<script src="./resources/common.js"></script> +<script src="./resources/dispatcher.js"></script> <script>
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/service-worker.tentative.https.html b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/service-worker.tentative.https.html similarity index 96% rename from third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/service-worker.tentative.https.html rename to third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/service-worker.tentative.https.html index 14f6331..377bcceb 100644 --- a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/service-worker.tentative.https.html +++ b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/service-worker.tentative.https.html
@@ -1,13 +1,12 @@ <!doctype html> -<title>CORS or Credentialless and service worker</title> <meta name="timeout" content="long"> <script src=/resources/testharness.js></script> <script src=/resources/testharnessreport.js></script> <script src="/common/get-host-info.sub.js"></script> <script src="/common/utils.js"></script> <script src="/service-workers/service-worker/resources/test-helpers.sub.js"></script> -<script src="../resources/common.js"></script> -<script src="../resources/dispatcher.js"></script> +<script src="./resources/common.js"></script> +<script src="./resources/dispatcher.js"></script> <script> const same_origin = get_host_info().HTTPS_ORIGIN;
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/shared-worker.tentative.https-expected.txt b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/shared-worker.tentative.https-expected.txt similarity index 86% copy from third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/shared-worker.tentative.https-expected.txt copy to third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/shared-worker.tentative.https-expected.txt index e51dcf0..19699d9 100644 --- a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/shared-worker.tentative.https-expected.txt +++ b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/shared-worker.tentative.https-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -PASS CORS or Credentialless and Shared worker +PASS shared-worker PASS fetch same-origin PASS fetch same-origin + credentialless worker PASS fetch cross-origin
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/shared-worker.tentative.https.html b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/shared-worker.tentative.https.html similarity index 85% rename from third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/shared-worker.tentative.https.html rename to third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/shared-worker.tentative.https.html index 0f13b9b..7d0bc80 100644 --- a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/shared-worker.tentative.https.html +++ b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/shared-worker.tentative.https.html
@@ -1,12 +1,11 @@ <!doctype html> -<title>CORS or Credentialless and Shared worker</title> <meta name="timeout" content="long"> <script src=/resources/testharness.js></script> <script src=/resources/testharnessreport.js></script> <script src="/common/get-host-info.sub.js"></script> <script src="/common/utils.js"></script> -<script src="../resources/common.js"></script> -<script src="../resources/dispatcher.js"></script> +<script src="./resources/common.js"></script> +<script src="./resources/dispatcher.js"></script> <script> const same_origin = get_host_info().HTTPS_ORIGIN; @@ -76,9 +75,9 @@ }, `fetch ${description}`) }; - // TODO(https://crbug.com/1200233). A COEP:cors-or-credentialless document - // shouldn't be able to load COEP:none SharedWorker. The sharedWorkerTest - // should listen for worker.onerror events and the expectations updated. + // TODO(https://crbug.com/1200233). A COEP:credentialless document shouldn't + // be able to load COEP:none SharedWorker. The sharedWorkerTest should listen + // for worker.onerror events and the expectations updated. sharedWorkerTest("same-origin", same_origin, coep_none, cookie_same_origin, @@ -89,9 +88,9 @@ cookie_same_origin, cookie_same_origin); - // TODO(https://crbug.com/1200233). A COEP:cors-or-credentialless document - // shouldn't be able to load COEP:none SharedWorker. The sharedWorkerTest - // should listen for worker.onerror events and the expectations updated. + // TODO(https://crbug.com/1200233). A COEP:credentialless document shouldn't + // be able to load COEP:none SharedWorker. The sharedWorkerTest should listen + // for worker.onerror events and the expectations updated. sharedWorkerTest("cross-origin", cross_origin, coep_none, cookie_cross_origin,
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/video.tentative.https.html b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/video.tentative.https.html similarity index 96% rename from third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/video.tentative.https.html rename to third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/video.tentative.https.html index 8658ba9..47a4024 100644 --- a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/video.tentative.https.html +++ b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/video.tentative.https.html
@@ -2,8 +2,8 @@ <script src="/resources/testharnessreport.js"></script> <script src="/common/get-host-info.sub.js"></script> <script src="/common/utils.js"></script> -<script src="../resources/common.js"></script> -<script src="../resources/dispatcher.js"></script> +<script src="./resources/common.js"></script> +<script src="./resources/dispatcher.js"></script> <script>
diff --git a/third_party/blink/web_tests/external/wpt/lint.ignore b/third_party/blink/web_tests/external/wpt/lint.ignore index f382f138..bc33666 100644 --- a/third_party/blink/web_tests/external/wpt/lint.ignore +++ b/third_party/blink/web_tests/external/wpt/lint.ignore
@@ -746,7 +746,7 @@ AHEM SYSTEM FONT: acid/acid3/test.html AHEM SYSTEM FONT: resource-timing/entry-attributes.html AHEM SYSTEM FONT: resource-timing/font-timestamps.html -AHEM SYSTEM FONT: resource-timing/resources/all_resource_types.htm +AHEM SYSTEM FONT: resource-timing/resources/all_resource_types.html AHEM SYSTEM FONT: resource-timing/resources/iframe-reload-TAO.sub.html AHEM SYSTEM FONT: html/canvas/element/drawing-text-to-the-canvas/2d.text.measure.fontBoundingBox.ahem.html AHEM SYSTEM FONT: css/css-font-loading/fontface-override-descriptors.html
diff --git a/third_party/blink/web_tests/external/wpt/resource-timing/resource_TAO_match_origin.htm b/third_party/blink/web_tests/external/wpt/resource-timing/resource_TAO_match_origin.html similarity index 100% rename from third_party/blink/web_tests/external/wpt/resource-timing/resource_TAO_match_origin.htm rename to third_party/blink/web_tests/external/wpt/resource-timing/resource_TAO_match_origin.html
diff --git a/third_party/blink/web_tests/external/wpt/resource-timing/resource_TAO_match_wildcard.htm b/third_party/blink/web_tests/external/wpt/resource-timing/resource_TAO_match_wildcard.html similarity index 100% rename from third_party/blink/web_tests/external/wpt/resource-timing/resource_TAO_match_wildcard.htm rename to third_party/blink/web_tests/external/wpt/resource-timing/resource_TAO_match_wildcard.html
diff --git a/third_party/blink/web_tests/external/wpt/resource-timing/resource_TAO_multi.htm b/third_party/blink/web_tests/external/wpt/resource-timing/resource_TAO_multi.html similarity index 100% rename from third_party/blink/web_tests/external/wpt/resource-timing/resource_TAO_multi.htm rename to third_party/blink/web_tests/external/wpt/resource-timing/resource_TAO_multi.html
diff --git a/third_party/blink/web_tests/external/wpt/resource-timing/resource_TAO_null.htm b/third_party/blink/web_tests/external/wpt/resource-timing/resource_TAO_null.html similarity index 100% rename from third_party/blink/web_tests/external/wpt/resource-timing/resource_TAO_null.htm rename to third_party/blink/web_tests/external/wpt/resource-timing/resource_TAO_null.html
diff --git a/third_party/blink/web_tests/external/wpt/resource-timing/resource_TAO_origin.htm b/third_party/blink/web_tests/external/wpt/resource-timing/resource_TAO_origin.html similarity index 100% rename from third_party/blink/web_tests/external/wpt/resource-timing/resource_TAO_origin.htm rename to third_party/blink/web_tests/external/wpt/resource-timing/resource_TAO_origin.html
diff --git a/third_party/blink/web_tests/external/wpt/resource-timing/resource_TAO_origin_uppercase.htm b/third_party/blink/web_tests/external/wpt/resource-timing/resource_TAO_origin_uppercase.html similarity index 100% rename from third_party/blink/web_tests/external/wpt/resource-timing/resource_TAO_origin_uppercase.htm rename to third_party/blink/web_tests/external/wpt/resource-timing/resource_TAO_origin_uppercase.html
diff --git a/third_party/blink/web_tests/external/wpt/resource-timing/resource_TAO_space.htm b/third_party/blink/web_tests/external/wpt/resource-timing/resource_TAO_space.html similarity index 100% rename from third_party/blink/web_tests/external/wpt/resource-timing/resource_TAO_space.htm rename to third_party/blink/web_tests/external/wpt/resource-timing/resource_TAO_space.html
diff --git a/third_party/blink/web_tests/external/wpt/resource-timing/resource_TAO_wildcard.htm b/third_party/blink/web_tests/external/wpt/resource-timing/resource_TAO_wildcard.html similarity index 100% rename from third_party/blink/web_tests/external/wpt/resource-timing/resource_TAO_wildcard.htm rename to third_party/blink/web_tests/external/wpt/resource-timing/resource_TAO_wildcard.html
diff --git a/third_party/blink/web_tests/external/wpt/resource-timing/resource_TAO_zero.htm b/third_party/blink/web_tests/external/wpt/resource-timing/resource_TAO_zero.html similarity index 100% rename from third_party/blink/web_tests/external/wpt/resource-timing/resource_TAO_zero.htm rename to third_party/blink/web_tests/external/wpt/resource-timing/resource_TAO_zero.html
diff --git a/third_party/blink/web_tests/external/wpt/resource-timing/resource_cached.htm b/third_party/blink/web_tests/external/wpt/resource-timing/resource_cached.html similarity index 100% rename from third_party/blink/web_tests/external/wpt/resource-timing/resource_cached.htm rename to third_party/blink/web_tests/external/wpt/resource-timing/resource_cached.html
diff --git a/third_party/blink/web_tests/external/wpt/resource-timing/resource_initiator_types.html b/third_party/blink/web_tests/external/wpt/resource-timing/resource_initiator_types.html index 954978c1..2e52f0e4 100644 --- a/third_party/blink/web_tests/external/wpt/resource-timing/resource_initiator_types.html +++ b/third_party/blink/web_tests/external/wpt/resource-timing/resource_initiator_types.html
@@ -158,7 +158,7 @@ <h1>Description</h1> <p>This test validates that all of the initiator types are represented.</p> <div id="log"></div> -<iframe id="frameContext" onload="onload_test();" src="resources/all_resource_types.htm" style="width: 250px; height: 250px;"></iframe> +<iframe id="frameContext" onload="onload_test();" src="resources/all_resource_types.html" style="width: 250px; height: 250px;"></iframe> <iframe id="frameContext2" onload="frameset_onload();" src="resources/green-frame.html" style="width: 250px; height: 250px;"></iframe> </body> </html>
diff --git a/third_party/blink/web_tests/external/wpt/resource-timing/resources/all_resource_types.htm b/third_party/blink/web_tests/external/wpt/resource-timing/resources/all_resource_types.html similarity index 100% rename from third_party/blink/web_tests/external/wpt/resource-timing/resources/all_resource_types.htm rename to third_party/blink/web_tests/external/wpt/resource-timing/resources/all_resource_types.html
diff --git a/third_party/blink/web_tests/flag-specific/composite-after-paint/virtual/layout_ng_block_frag/fast/multicol/composited-opacity-2nd-and-3rd-column-expected.png b/third_party/blink/web_tests/flag-specific/composite-after-paint/virtual/layout_ng_block_frag/fast/multicol/composited-opacity-2nd-and-3rd-column-expected.png deleted file mode 100644 index 02b2f1f..0000000 --- a/third_party/blink/web_tests/flag-specific/composite-after-paint/virtual/layout_ng_block_frag/fast/multicol/composited-opacity-2nd-and-3rd-column-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/flag-specific/composite-after-paint/virtual/layout_ng_svg_text/paint/invalidation/svg/animated-path-inside-transformed-html-expected.txt b/third_party/blink/web_tests/flag-specific/composite-after-paint/virtual/layout_ng_svg_text/paint/invalidation/svg/animated-path-inside-transformed-html-expected.txt index 248439b..d64056a 100644 --- a/third_party/blink/web_tests/flag-specific/composite-after-paint/virtual/layout_ng_svg_text/paint/invalidation/svg/animated-path-inside-transformed-html-expected.txt +++ b/third_party/blink/web_tests/flag-specific/composite-after-paint/virtual/layout_ng_svg_text/paint/invalidation/svg/animated-path-inside-transformed-html-expected.txt
@@ -6,7 +6,7 @@ "contentsOpaque": true, "backgroundColor": "#FFFFFF", "invalidations": [ - [244, 104, 126, 46], + [246, 89, 127, 46], [203, 336, 126, 45], [108, 84, 105, 102], [355, 125, 104, 104],
diff --git a/third_party/blink/web_tests/flag-specific/disable-layout-ng/external/wpt/css/cssom-view/getBoundingClientRect-shy-expected.txt b/third_party/blink/web_tests/flag-specific/disable-layout-ng/external/wpt/css/cssom-view/getBoundingClientRect-shy-expected.txt new file mode 100644 index 0000000..8ead4c03 --- /dev/null +++ b/third_party/blink/web_tests/flag-specific/disable-layout-ng/external/wpt/css/cssom-view/getBoundingClientRect-shy-expected.txt
@@ -0,0 +1,15 @@ +This is a testharness.js-based test. +PASS Range 0-5 should not include the hyphen. +PASS Range 1-5 should not include the hyphen. +PASS Range 0-6 should not include the hyphen. +PASS Range 1-6 should not include the hyphen. +PASS Range 0-7 should include the hyphen. +FAIL Range 1-7 should include the hyphen. assert_equals: expected 60 but got 50 +PASS Range 0-8 should include the hyphen. +PASS Range 0-8 should include only the first hyphen. +PASS Collapsed soft-hyphen should be 0 width. +FAIL Rendered soft-hyphen should have a width. assert_equals: expected 10 but got 0 +PASS Collapsed soft-hyphen in a span should be 0 width. +FAIL Rendered soft-hyphen in a span should have a width. assert_equals: expected 10 but got 0 +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/platform/linux/virtual/layout_ng_block_frag/fast/multicol/composited-opacity-2nd-and-3rd-column-expected.png b/third_party/blink/web_tests/platform/linux/virtual/layout_ng_block_frag/fast/multicol/composited-opacity-2nd-and-3rd-column-expected.png deleted file mode 100644 index e2668b9..0000000 --- a/third_party/blink/web_tests/platform/linux/virtual/layout_ng_block_frag/fast/multicol/composited-opacity-2nd-and-3rd-column-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/layout_ng_svg_text/paint/invalidation/svg/animated-path-inside-transformed-html-expected.txt b/third_party/blink/web_tests/platform/linux/virtual/layout_ng_svg_text/paint/invalidation/svg/animated-path-inside-transformed-html-expected.txt index f219dbe..786e0028 100644 --- a/third_party/blink/web_tests/platform/linux/virtual/layout_ng_svg_text/paint/invalidation/svg/animated-path-inside-transformed-html-expected.txt +++ b/third_party/blink/web_tests/platform/linux/virtual/layout_ng_svg_text/paint/invalidation/svg/animated-path-inside-transformed-html-expected.txt
@@ -6,7 +6,7 @@ "contentsOpaque": true, "backgroundColor": "#FFFFFF", "invalidations": [ - [244, 104, 126, 46], + [246, 89, 127, 46], [203, 336, 126, 45], [108, 84, 105, 102], [355, 125, 104, 104],
diff --git a/third_party/blink/web_tests/platform/linux/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1-SE/filters-image-05-f-expected.png b/third_party/blink/web_tests/platform/linux/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1-SE/filters-image-05-f-expected.png new file mode 100644 index 0000000..4da9bb4a --- /dev/null +++ b/third_party/blink/web_tests/platform/linux/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1-SE/filters-image-05-f-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1-SE/text-tspan-02-b-expected.png b/third_party/blink/web_tests/platform/linux/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1-SE/text-tspan-02-b-expected.png new file mode 100644 index 0000000..3a75210 --- /dev/null +++ b/third_party/blink/web_tests/platform/linux/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1-SE/text-tspan-02-b-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-41-t-expected.png b/third_party/blink/web_tests/platform/linux/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-41-t-expected.png new file mode 100644 index 0000000..c9e12d33 --- /dev/null +++ b/third_party/blink/web_tests/platform/linux/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-41-t-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-61-t-expected.png b/third_party/blink/web_tests/platform/linux/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-61-t-expected.png new file mode 100644 index 0000000..d1c8f9f --- /dev/null +++ b/third_party/blink/web_tests/platform/linux/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-61-t-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-66-t-expected.png b/third_party/blink/web_tests/platform/linux/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-66-t-expected.png new file mode 100644 index 0000000..6b01d048 --- /dev/null +++ b/third_party/blink/web_tests/platform/linux/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-66-t-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-70-t-expected.png b/third_party/blink/web_tests/platform/linux/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-70-t-expected.png new file mode 100644 index 0000000..c686545 --- /dev/null +++ b/third_party/blink/web_tests/platform/linux/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-70-t-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-78-t-expected.png b/third_party/blink/web_tests/platform/linux/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-78-t-expected.png new file mode 100644 index 0000000..07598c5 --- /dev/null +++ b/third_party/blink/web_tests/platform/linux/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-78-t-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-84-t-expected.png b/third_party/blink/web_tests/platform/linux/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-84-t-expected.png new file mode 100644 index 0000000..a07599c --- /dev/null +++ b/third_party/blink/web_tests/platform/linux/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-84-t-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/layout_ng_svg_text/svg/batik/text/textPCDATA-expected.png b/third_party/blink/web_tests/platform/linux/virtual/layout_ng_svg_text/svg/batik/text/textPCDATA-expected.png new file mode 100644 index 0000000..f840eff2 --- /dev/null +++ b/third_party/blink/web_tests/platform/linux/virtual/layout_ng_svg_text/svg/batik/text/textPCDATA-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.13/virtual/layout_ng_block_frag/fast/multicol/composited-opacity-2nd-and-3rd-column-expected.png b/third_party/blink/web_tests/platform/mac-mac10.13/virtual/layout_ng_block_frag/fast/multicol/composited-opacity-2nd-and-3rd-column-expected.png deleted file mode 100644 index 7a25866..0000000 --- a/third_party/blink/web_tests/platform/mac-mac10.13/virtual/layout_ng_block_frag/fast/multicol/composited-opacity-2nd-and-3rd-column-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.14/virtual/layout_ng_block_frag/fast/multicol/composited-opacity-2nd-and-3rd-column-expected.png b/third_party/blink/web_tests/platform/mac-mac10.14/virtual/layout_ng_block_frag/fast/multicol/composited-opacity-2nd-and-3rd-column-expected.png deleted file mode 100644 index 87905c9b..0000000 --- a/third_party/blink/web_tests/platform/mac-mac10.14/virtual/layout_ng_block_frag/fast/multicol/composited-opacity-2nd-and-3rd-column-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_block_frag/fast/multicol/composited-opacity-2nd-and-3rd-column-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_block_frag/fast/multicol/composited-opacity-2nd-and-3rd-column-expected.png deleted file mode 100644 index 7a25866..0000000 --- a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_block_frag/fast/multicol/composited-opacity-2nd-and-3rd-column-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/paint/invalidation/svg/animated-path-inside-transformed-html-expected.txt b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/paint/invalidation/svg/animated-path-inside-transformed-html-expected.txt index 32fe1d4..a17e7c7 100644 --- a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/paint/invalidation/svg/animated-path-inside-transformed-html-expected.txt +++ b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/paint/invalidation/svg/animated-path-inside-transformed-html-expected.txt
@@ -6,7 +6,7 @@ "contentsOpaque": true, "backgroundColor": "#FFFFFF", "invalidations": [ - [244, 102, 121, 44], + [246, 88, 122, 44], [203, 334, 121, 44], [108, 82, 105, 102], [355, 123, 104, 104],
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1-SE/filters-image-05-f-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1-SE/filters-image-05-f-expected.png new file mode 100644 index 0000000..8ca48c8 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1-SE/filters-image-05-f-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1-SE/painting-marker-05-f-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1-SE/painting-marker-05-f-expected.png new file mode 100644 index 0000000..8facc3681 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1-SE/painting-marker-05-f-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1-SE/text-tspan-02-b-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1-SE/text-tspan-02-b-expected.png new file mode 100644 index 0000000..32822cfa --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1-SE/text-tspan-02-b-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-24-t-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-24-t-expected.png new file mode 100644 index 0000000..3f78510 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-24-t-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-41-t-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-41-t-expected.png new file mode 100644 index 0000000..f48e0a49 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-41-t-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-60-t-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-60-t-expected.png new file mode 100644 index 0000000..f293c05 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-60-t-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-61-t-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-61-t-expected.png new file mode 100644 index 0000000..7a74b77 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-61-t-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-62-t-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-62-t-expected.png new file mode 100644 index 0000000..0447c30 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-62-t-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-63-t-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-63-t-expected.png new file mode 100644 index 0000000..fa21dcf --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-63-t-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-64-t-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-64-t-expected.png new file mode 100644 index 0000000..ac1bcbb --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-64-t-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-65-t-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-65-t-expected.png new file mode 100644 index 0000000..a15eab89 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-65-t-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-66-t-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-66-t-expected.png new file mode 100644 index 0000000..fdfeacbc --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-66-t-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-67-t-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-67-t-expected.png new file mode 100644 index 0000000..b4572a0 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-67-t-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-68-t-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-68-t-expected.png new file mode 100644 index 0000000..182d4f6 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-68-t-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-69-t-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-69-t-expected.png new file mode 100644 index 0000000..4bdf1c8 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-69-t-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-70-t-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-70-t-expected.png new file mode 100644 index 0000000..6270cc7 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-70-t-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-78-t-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-78-t-expected.png new file mode 100644 index 0000000..34752f0 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-78-t-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-84-t-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-84-t-expected.png new file mode 100644 index 0000000..0f08030 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-84-t-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-85-t-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-85-t-expected.png new file mode 100644 index 0000000..4dbd8fad --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-85-t-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/fonts-elem-03-b-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/fonts-elem-03-b-expected.png new file mode 100644 index 0000000..a822ef5 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/fonts-elem-03-b-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/fonts-elem-04-b-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/fonts-elem-04-b-expected.png new file mode 100644 index 0000000..8f02879a --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/fonts-elem-04-b-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/interact-zoom-01-t-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/interact-zoom-01-t-expected.png new file mode 100644 index 0000000..b879b0d --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/interact-zoom-01-t-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/struct-group-03-t-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/struct-group-03-t-expected.png new file mode 100644 index 0000000..8d51f06 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/struct-group-03-t-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/struct-use-01-t-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/struct-use-01-t-expected.png new file mode 100644 index 0000000..7437a59 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/struct-use-01-t-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/text-align-01-b-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/text-align-01-b-expected.png new file mode 100644 index 0000000..c850612 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/text-align-01-b-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/text-text-04-t-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/text-text-04-t-expected.png new file mode 100644 index 0000000..a73e6b68 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/text-text-04-t-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/text-text-06-t-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/text-text-06-t-expected.png new file mode 100644 index 0000000..3149ceb1 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/text-text-06-t-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/batik/paints/patternRegions-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/batik/paints/patternRegions-expected.png new file mode 100644 index 0000000..e011375 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/batik/paints/patternRegions-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/batik/paints/patternRegions-positioned-objects-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/batik/paints/patternRegions-positioned-objects-expected.png new file mode 100644 index 0000000..68b77e8 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/batik/paints/patternRegions-positioned-objects-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/batik/text/textPCDATA-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/batik/text/textPCDATA-expected.png new file mode 100644 index 0000000..a1490d6 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/batik/text/textPCDATA-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/text/scaling-font-with-geometric-precision-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/text/scaling-font-with-geometric-precision-expected.png new file mode 100644 index 0000000..13edfc379 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/text/scaling-font-with-geometric-precision-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/text/small-fonts-2-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/text/small-fonts-2-expected.png new file mode 100644 index 0000000..0aecbf5 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/text/small-fonts-2-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/text/small-fonts-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/text/small-fonts-expected.png new file mode 100644 index 0000000..398079a --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/layout_ng_svg_text/svg/text/small-fonts-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/virtual/layout_ng_block_frag/fast/multicol/composited-opacity-2nd-and-3rd-column-expected.png b/third_party/blink/web_tests/platform/win/virtual/layout_ng_block_frag/fast/multicol/composited-opacity-2nd-and-3rd-column-expected.png deleted file mode 100644 index 3141639..0000000 --- a/third_party/blink/web_tests/platform/win/virtual/layout_ng_block_frag/fast/multicol/composited-opacity-2nd-and-3rd-column-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/virtual/layout_ng_svg_text/paint/invalidation/svg/animated-path-inside-transformed-html-expected.txt b/third_party/blink/web_tests/platform/win/virtual/layout_ng_svg_text/paint/invalidation/svg/animated-path-inside-transformed-html-expected.txt index ef1563e1..328d10dc 100644 --- a/third_party/blink/web_tests/platform/win/virtual/layout_ng_svg_text/paint/invalidation/svg/animated-path-inside-transformed-html-expected.txt +++ b/third_party/blink/web_tests/platform/win/virtual/layout_ng_svg_text/paint/invalidation/svg/animated-path-inside-transformed-html-expected.txt
@@ -6,7 +6,7 @@ "contentsOpaque": true, "backgroundColor": "#FFFFFF", "invalidations": [ - [244, 104, 124, 45], + [246, 89, 124, 45], [203, 336, 124, 45], [108, 84, 105, 102], [355, 125, 104, 104],
diff --git a/third_party/blink/web_tests/platform/win/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1-SE/text-tspan-02-b-expected.png b/third_party/blink/web_tests/platform/win/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1-SE/text-tspan-02-b-expected.png new file mode 100644 index 0000000..450f365 --- /dev/null +++ b/third_party/blink/web_tests/platform/win/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1-SE/text-tspan-02-b-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-41-t-expected.png b/third_party/blink/web_tests/platform/win/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-41-t-expected.png new file mode 100644 index 0000000..8523ce9 --- /dev/null +++ b/third_party/blink/web_tests/platform/win/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-41-t-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-61-t-expected.png b/third_party/blink/web_tests/platform/win/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-61-t-expected.png new file mode 100644 index 0000000..c03afe8 --- /dev/null +++ b/third_party/blink/web_tests/platform/win/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-61-t-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-66-t-expected.png b/third_party/blink/web_tests/platform/win/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-66-t-expected.png new file mode 100644 index 0000000..358d372 --- /dev/null +++ b/third_party/blink/web_tests/platform/win/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-66-t-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-70-t-expected.png b/third_party/blink/web_tests/platform/win/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-70-t-expected.png new file mode 100644 index 0000000..f15cf65 --- /dev/null +++ b/third_party/blink/web_tests/platform/win/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-70-t-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-78-t-expected.png b/third_party/blink/web_tests/platform/win/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-78-t-expected.png new file mode 100644 index 0000000..cb65f30 --- /dev/null +++ b/third_party/blink/web_tests/platform/win/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-78-t-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-84-t-expected.png b/third_party/blink/web_tests/platform/win/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-84-t-expected.png new file mode 100644 index 0000000..a6f7faa --- /dev/null +++ b/third_party/blink/web_tests/platform/win/virtual/layout_ng_svg_text/svg/W3C-SVG-1.1/animate-elem-84-t-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/virtual/layout_ng_svg_text/svg/batik/text/textPCDATA-expected.png b/third_party/blink/web_tests/platform/win/virtual/layout_ng_svg_text/svg/batik/text/textPCDATA-expected.png new file mode 100644 index 0000000..2be781d --- /dev/null +++ b/third_party/blink/web_tests/platform/win/virtual/layout_ng_svg_text/svg/batik/text/textPCDATA-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/virtual/plz-dedicated-worker/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/dedicated-worker.tentative.https-expected.txt b/third_party/blink/web_tests/virtual/plz-dedicated-worker/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/dedicated-worker.tentative.https-expected.txt deleted file mode 100644 index 52fc59a2..0000000 --- a/third_party/blink/web_tests/virtual/plz-dedicated-worker/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/dedicated-worker.tentative.https-expected.txt +++ /dev/null
@@ -1,8 +0,0 @@ -This is a testharness.js-based test. -PASS CORS or Credentialless and dedicated worker -PASS fetch same-origin + credentialless worker -PASS fetch same-origin -PASS fetch cross-origin -FAIL fetch cross-origin + credentialless worker assert_equals: coep:none => expected (undefined) undefined but got (string) "cross_origin" -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/shared-worker.tentative.https-expected.txt b/third_party/blink/web_tests/virtual/plz-dedicated-worker/external/wpt/html/cross-origin-embedder-policy/credentialless/dedicated-worker.tentative.https-expected.txt similarity index 86% rename from third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/shared-worker.tentative.https-expected.txt rename to third_party/blink/web_tests/virtual/plz-dedicated-worker/external/wpt/html/cross-origin-embedder-policy/credentialless/dedicated-worker.tentative.https-expected.txt index e51dcf0..7ecbf9ce 100644 --- a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/shared-worker.tentative.https-expected.txt +++ b/third_party/blink/web_tests/virtual/plz-dedicated-worker/external/wpt/html/cross-origin-embedder-policy/credentialless/dedicated-worker.tentative.https-expected.txt
@@ -1,7 +1,7 @@ This is a testharness.js-based test. -PASS CORS or Credentialless and Shared worker -PASS fetch same-origin +PASS dedicated-worker PASS fetch same-origin + credentialless worker +PASS fetch same-origin PASS fetch cross-origin FAIL fetch cross-origin + credentialless worker assert_equals: coep:none => expected (undefined) undefined but got (string) "cross_origin" Harness: the test ran to completion.
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/shared-worker.tentative.https-expected.txt b/third_party/blink/web_tests/virtual/plz-dedicated-worker/external/wpt/html/cross-origin-embedder-policy/credentialless/shared-worker.tentative.https-expected.txt similarity index 86% copy from third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/shared-worker.tentative.https-expected.txt copy to third_party/blink/web_tests/virtual/plz-dedicated-worker/external/wpt/html/cross-origin-embedder-policy/credentialless/shared-worker.tentative.https-expected.txt index e51dcf0..19699d9 100644 --- a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/shared-worker.tentative.https-expected.txt +++ b/third_party/blink/web_tests/virtual/plz-dedicated-worker/external/wpt/html/cross-origin-embedder-policy/credentialless/shared-worker.tentative.https-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -PASS CORS or Credentialless and Shared worker +PASS shared-worker PASS fetch same-origin PASS fetch same-origin + credentialless worker PASS fetch cross-origin
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/dedicated-worker.tentative.https-expected.txt b/third_party/blink/web_tests/virtual/plz-service-worker/external/wpt/html/cross-origin-embedder-policy/credentialless/dedicated-worker.tentative.https-expected.txt similarity index 90% copy from third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/dedicated-worker.tentative.https-expected.txt copy to third_party/blink/web_tests/virtual/plz-service-worker/external/wpt/html/cross-origin-embedder-policy/credentialless/dedicated-worker.tentative.https-expected.txt index 000a3b27..6998fdc 100644 --- a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/dedicated-worker.tentative.https-expected.txt +++ b/third_party/blink/web_tests/virtual/plz-service-worker/external/wpt/html/cross-origin-embedder-policy/credentialless/dedicated-worker.tentative.https-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -PASS CORS or Credentialless and dedicated worker +PASS dedicated-worker PASS fetch same-origin + credentialless worker FAIL fetch same-origin assert_equals: coep:credentialless => expected "Worker blocked" but got "same_origin" FAIL fetch cross-origin assert_equals: coep:credentialless => expected (string) "Worker blocked" but got (undefined) undefined
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/shared-worker.tentative.https-expected.txt b/third_party/blink/web_tests/virtual/plz-service-worker/external/wpt/html/cross-origin-embedder-policy/credentialless/shared-worker.tentative.https-expected.txt similarity index 86% copy from third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/shared-worker.tentative.https-expected.txt copy to third_party/blink/web_tests/virtual/plz-service-worker/external/wpt/html/cross-origin-embedder-policy/credentialless/shared-worker.tentative.https-expected.txt index e51dcf0..19699d9 100644 --- a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/credentialless/cors-or-credentialless/shared-worker.tentative.https-expected.txt +++ b/third_party/blink/web_tests/virtual/plz-service-worker/external/wpt/html/cross-origin-embedder-policy/credentialless/shared-worker.tentative.https-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -PASS CORS or Credentialless and Shared worker +PASS shared-worker PASS fetch same-origin PASS fetch same-origin + credentialless worker PASS fetch cross-origin
diff --git a/third_party/highway/README.chromium b/third_party/highway/README.chromium index 32e69c8..753f481 100644 --- a/third_party/highway/README.chromium +++ b/third_party/highway/README.chromium
@@ -1,9 +1,9 @@ Name: Highway: C++ library for SIMD Short Name: highway URL: https://github.com/google/highway -Version: 0.11.x -Date: 2020-04-08 -Revision: 6cf3e578ee3f3c8f61668e0cb7c0f12f4b8d876e +Version: 0.12.0 +Date: 2020-04-15 +Revision: ca1a57c342cd815053abfcffa29b44eaead4f20b License: Apache 2.0 Security Critical: yes CPEPrefix: unknown
diff --git a/third_party/libjxl/README.chromium b/third_party/libjxl/README.chromium index fb382bd..b068498 100644 --- a/third_party/libjxl/README.chromium +++ b/third_party/libjxl/README.chromium
@@ -2,8 +2,8 @@ Short Name: libjxl URL: https://gitlab.com/wg1/jpeg-xl Version: 0 -Date: 2021-05-04 -Revision: 9a8f5195e4d1c45112fd65f184ebe115f4163ba2 +Date: 2021-05-06 +Revision: 040eae8105b61b312a67791213091103f4c0d034 License: Apache 2.0 Security Critical: yes CPEPrefix: unknown
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 946ecc31..6a2324c 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -32387,7 +32387,7 @@ <int value="3878" label="PrefixedStorageQuotaThirdPartyContext"/> <int value="3879" label="RequestedFileSystemPersistentThirdPartyContext"/> <int value="3880" label="PrefixedStorageInfoThirdPartyContext"/> - <int value="3881" label="CrossOriginEmbedderPolicyCorsOrCredentialless"/> + <int value="3881" label="CrossOriginEmbedderPolicyCredentialless"/> <int value="3882" label="PostMessageFromSecureToSecure"/> <int value="3883" label="PostMessageFromInsecureToInsecure"/> <int value="3884" label="WebAppManifestProtocolHandlers"/>
diff --git a/tools/metrics/histograms/histograms_xml/tab/histograms.xml b/tools/metrics/histograms/histograms_xml/tab/histograms.xml index 17c586a6..c1e8b9d 100644 --- a/tools/metrics/histograms/histograms_xml/tab/histograms.xml +++ b/tools/metrics/histograms/histograms_xml/tab/histograms.xml
@@ -149,6 +149,9 @@ <histogram name="Tab.HorizontalSizeClassUsed" enum="iOSSizeClassForReporting" expires_after="M77"> + <obsolete> + Obsolete in M92. Replaced by IOS.MultiWindow.Configuration. + </obsolete> <owner>pkl@chromium.org</owner> <summary> [iOS] Used on iOS 9+ iPad to report the usage of Compact or Regular @@ -210,6 +213,9 @@ <histogram name="Tab.PageLoadInHorizontalSizeClass" enum="iOSSizeClassForReporting" expires_after="M77"> + <obsolete> + Obsolete in M92. Wasn't being recorded correctly anyway. + </obsolete> <owner>pkl@chromium.org</owner> <summary> [iOS] Used on iOS 9+ iPad to report the usage of Compact or Regular
diff --git a/tools/perf/core/perfetto_binary_roller/binary_deps.json b/tools/perf/core/perfetto_binary_roller/binary_deps.json index 2e0384e..1b3a0b55 100644 --- a/tools/perf/core/perfetto_binary_roller/binary_deps.json +++ b/tools/perf/core/perfetto_binary_roller/binary_deps.json
@@ -9,8 +9,8 @@ "remote_path": "perfetto_binaries/trace_processor_shell/mac/2b0fcfa349ac5ccd7851e459ec683a8e687f7c75/trace_processor_shell" }, "linux": { - "hash": "06b3e695b6dc8db2a271e7bf3605cef7b04d12e5", - "remote_path": "perfetto_binaries/trace_processor_shell/linux/2b0fcfa349ac5ccd7851e459ec683a8e687f7c75/trace_processor_shell" + "hash": "b95b2b75294ef7c5ed96e53582c5d8f0d4e575bd", + "remote_path": "perfetto_binaries/trace_processor_shell/linux/7dc7013d1b97fe8e4a1b653ae7c819e946ab1bc7/trace_processor_shell" } }, "power_profile.sql": {
diff --git a/tools/perf/expectations.config b/tools/perf/expectations.config index c0116170..4a01bdd 100644 --- a/tools/perf/expectations.config +++ b/tools/perf/expectations.config
@@ -114,12 +114,6 @@ crbug.com/879833 loading.desktop/Walgreens_warm [ Skip ] crbug.com/921428 [ chromeos ] loading.desktop/TheVerge_cold [ Skip ] crbug.com/921428 [ chromeos ] loading.desktop/TheVerge_warm [ Skip ] -crbug.com/1205852 [ linux ] loading.desktop/Economist_cold [ Skip ] -crbug.com/1205852 [ linux ] loading.desktop/Economist_warm [ Skip ] -crbug.com/1205852 [ mac ] loading.desktop/Economist_cold [ Skip ] -crbug.com/1205852 [ mac ] loading.desktop/Economist_warm [ Skip ] -crbug.com/1205852 [ win ] loading.desktop/Economist_cold [ Skip ] -crbug.com/1205852 [ win ] loading.desktop/Economist_warm [ Skip ] # Benchmark: loading.mobile crbug.com/656861 loading.mobile/G1 [ Skip ]
diff --git a/ui/accessibility/ax_text_utils_unittest.cc b/ui/accessibility/ax_text_utils_unittest.cc index 8fd1b90..c644941 100644 --- a/ui/accessibility/ax_text_utils_unittest.cc +++ b/ui/accessibility/ax_text_utils_unittest.cc
@@ -290,14 +290,14 @@ } TEST(AXTextUtils, GetSentenceStartOffsetsBasicTest) { - const std::u16string text = - u"This is the first sentence. This is the second sentence"; + const std::u16string text = base::UTF8ToUTF16( + "This is the first sentence. This is the second sentence"); EXPECT_THAT(GetSentenceStartOffsets(text), testing::ElementsAre(0, 28)); } TEST(AXTextUtils, GetSentenceEndOffsetsBasicTest) { - const std::u16string text = - u"This is the first sentence. This is the second sentence"; + const std::u16string text = base::UTF8ToUTF16( + "This is the first sentence. This is the second sentence"); EXPECT_THAT(GetSentenceEndOffsets(text), testing::ElementsAre(28, 55)); }
diff --git a/ui/accessibility/platform/atk_util_auralinux_unittest.cc b/ui/accessibility/platform/atk_util_auralinux_unittest.cc index 11342de..990912b 100644 --- a/ui/accessibility/platform/atk_util_auralinux_unittest.cc +++ b/ui/accessibility/platform/atk_util_auralinux_unittest.cc
@@ -16,8 +16,7 @@ class AtkUtilAuraLinuxTest : public AXPlatformNodeTest { public: - AtkUtilAuraLinuxTest() { - AXPlatformNode::NotifyAddAXModeFlags(kAXModeComplete); + AtkUtilAuraLinuxTest() : ax_mode_setter_(kAXModeComplete) { // We need to create a platform node in order to install it as the root // ATK node. The ATK bridge will complain if we try to use it without a // root node installed. @@ -44,6 +43,9 @@ AtkUtilAuraLinuxTest(const AtkUtilAuraLinuxTest&) = delete; AtkUtilAuraLinuxTest& operator=(const AtkUtilAuraLinuxTest&) = delete; + + private: + ui::testing::ScopedAxModeSetter ax_mode_setter_; }; TEST_F(AtkUtilAuraLinuxTest, KeySnooping) {
diff --git a/ui/accessibility/platform/ax_platform_node.cc b/ui/accessibility/platform/ax_platform_node.cc index 4f8d630..aa8612c 100644 --- a/ui/accessibility/platform/ax_platform_node.cc +++ b/ui/accessibility/platform/ax_platform_node.cc
@@ -94,7 +94,7 @@ // static void AXPlatformNode::NotifyAddAXModeFlags(AXMode mode_flags) { - // Note: this is only called on Windows. + // Note: this is only called on Windows, and in tests. AXMode new_ax_mode(ax_mode_); new_ax_mode |= mode_flags; @@ -107,6 +107,17 @@ } // static +void AXPlatformNode::SetAXMode(AXMode new_mode) { + // Note: this is only called on Windows. + ax_mode_ = new_mode; +} + +// static +void AXPlatformNode::ResetAxModeForTesting() { + ax_mode_ = 0; +} + +// static void AXPlatformNode::SetPopupFocusOverride( gfx::NativeViewAccessible popup_focus_override) { popup_focus_override_ = popup_focus_override;
diff --git a/ui/accessibility/platform/ax_platform_node.h b/ui/accessibility/platform/ax_platform_node.h index 82fe3360..87e5f6c 100644 --- a/ui/accessibility/platform/ax_platform_node.h +++ b/ui/accessibility/platform/ax_platform_node.h
@@ -60,6 +60,15 @@ // the addition of an AXMode flag. static void NotifyAddAXModeFlags(AXMode mode_flags); + // Helper static function to update the AXMode. This is called when flags + // are removed. It doesn't currently notify global observers. + static void SetAXMode(AXMode new_mode); + + // Since |ax_mode_| is a static, calling NotifyAddAXModeFlags in a test can + // cause downstream tests to be flaky. This helper function puts |ax_mode_| + // in the default state. + static void ResetAxModeForTesting(); + // Return the focused object in any UI popup overlaying content, or null. static gfx::NativeViewAccessible GetPopupFocusOverride(); @@ -134,6 +143,16 @@ DISALLOW_COPY_AND_ASSIGN(AXPlatformNode); }; +namespace testing { +class ScopedAxModeSetter { + public: + explicit ScopedAxModeSetter(AXMode new_mode) { + AXPlatformNode::SetAXMode(new_mode); + } + ~ScopedAxModeSetter() { AXPlatformNode::ResetAxModeForTesting(); } +}; +} // namespace testing + } // namespace ui #endif // UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_H_
diff --git a/ui/accessibility/platform/ax_platform_node_auralinux_unittest.cc b/ui/accessibility/platform/ax_platform_node_auralinux_unittest.cc index 405db872..6824207 100644 --- a/ui/accessibility/platform/ax_platform_node_auralinux_unittest.cc +++ b/ui/accessibility/platform/ax_platform_node_auralinux_unittest.cc
@@ -37,16 +37,12 @@ class AXPlatformNodeAuraLinuxTest : public AXPlatformNodeTest { public: - AXPlatformNodeAuraLinuxTest() = default; + AXPlatformNodeAuraLinuxTest() : ax_mode_setter_(kAXModeComplete) {} ~AXPlatformNodeAuraLinuxTest() override = default; AXPlatformNodeAuraLinuxTest(const AXPlatformNodeAuraLinuxTest&) = delete; AXPlatformNodeAuraLinuxTest& operator=(const AXPlatformNodeAuraLinuxTest&) = delete; - void SetUp() override { - AXPlatformNode::NotifyAddAXModeFlags(kAXModeComplete); - } - protected: AXPlatformNodeAuraLinux* GetPlatformNode(AXNode* node) { TestAXNodeWrapper* wrapper = @@ -87,6 +83,9 @@ } return atk_state_type < max_state_type.value(); } + + private: + ui::testing::ScopedAxModeSetter ax_mode_setter_; }; static void EnsureAtkObjectHasAttributeWithValue( @@ -158,14 +157,14 @@ std::make_pair(1000, "1000"), }; - for (unsigned i = 0; i < G_N_ELEMENTS(tests); i++) { + for (const auto& test : tests) { AXNodeData new_data = AXNodeData(); new_data.role = role.value_or(ax::mojom::Role::kApplication); new_data.id = ax_node->data().id; - new_data.AddIntAttribute(mojom_attribute, tests[i].first); + new_data.AddIntAttribute(mojom_attribute, test.first); ax_node->SetData(new_data); EnsureAtkObjectHasAttributeWithValue(atk_object, attribute_name, - tests[i].second); + test.second); } } @@ -186,9 +185,9 @@ "\xE2\x98\xBA", // The smiley emoji. }; - for (unsigned i = 0; i < G_N_ELEMENTS(tests); i++) { - SetStringAttributeOnNode(ax_node, mojom_attribute, tests[i], role); - EnsureAtkObjectHasAttributeWithValue(atk_object, attribute_name, tests[i]); + for (const char* test : tests) { + SetStringAttributeOnNode(ax_node, mojom_attribute, test, role); + EnsureAtkObjectHasAttributeWithValue(atk_object, attribute_name, test); } } @@ -615,9 +614,9 @@ "container-relevant"), }; - for (unsigned i = 0; i < G_N_ELEMENTS(tests); i++) { - TestAtkObjectStringAttribute(root_node, root_atk_object, tests[i].first, - tests[i].second); + for (const auto& test : tests) { + TestAtkObjectStringAttribute(root_node, root_atk_object, test.first, + test.second); } g_object_unref(root_atk_object); @@ -643,9 +642,9 @@ "container-busy"), }; - for (unsigned i = 0; i < G_N_ELEMENTS(tests); i++) { - TestAtkObjectBoolAttribute(root_node, root_atk_object, tests[i].first, - tests[i].second); + for (const auto& test : tests) { + TestAtkObjectBoolAttribute(root_node, root_atk_object, test.first, + test.second); } g_object_unref(root_atk_object); @@ -1215,7 +1214,7 @@ auto verify_text_at_offset = [&](const char* expected_text, int offset, int expected_start, int expected_end) { - testing::Message message; + ::testing::Message message; message << "While checking at offset " << offset; SCOPED_TRACE(message); @@ -1233,7 +1232,7 @@ auto verify_text_after_offset = [&](const char* expected_text, int offset, int expected_start, int expected_end) { - testing::Message message; + ::testing::Message message; message << "While checking after offset " << offset; SCOPED_TRACE(message); @@ -1253,7 +1252,7 @@ auto verify_text_before_offset = [&](const char* expected_text, int offset, int expected_start, int expected_end) { - testing::Message message; + ::testing::Message message; message << "While checking before offset " << offset; SCOPED_TRACE(message); @@ -1299,38 +1298,40 @@ {-1, nullptr, -1, -1}, {1000, nullptr, -1, -1}}; - for (unsigned i = 0; i < G_N_ELEMENTS(tests); i++) { - testing::Message message; - message << "While checking at index " << tests[i].offset << " for \'" - << tests[i].content << "\' at " << tests[i].start_offset << '-' - << tests[i].end_offset << '.'; + for (const auto& test : tests) { + ::testing::Message message; + message << "While checking at index " << test.offset << " for \'" + << test.content << "\' at " << test.start_offset << '-' + << test.end_offset << '.'; SCOPED_TRACE(message); int start_offset = -1, end_offset = -1; - char* content = atk_text_get_text_at_offset(atk_text, tests[i].offset, + char* content = atk_text_get_text_at_offset(atk_text, test.offset, ATK_TEXT_BOUNDARY_WORD_START, &start_offset, &end_offset); - EXPECT_STREQ(content, tests[i].content); - EXPECT_EQ(start_offset, tests[i].start_offset); - EXPECT_EQ(end_offset, tests[i].end_offset); + EXPECT_STREQ(content, test.content); + EXPECT_EQ(start_offset, test.start_offset); + EXPECT_EQ(end_offset, test.end_offset); g_free(content); } #if ATK_CHECK_VERSION(2, 10, 0) - for (unsigned i = 0; i < G_N_ELEMENTS(tests); i++) { - testing::Message message; - message << "While checking at index " << tests[i].offset << " for \'" - << tests[i].content << "\' at " << tests[i].start_offset << '-' - << tests[i].end_offset << '.'; + for (const auto& test : tests) { + ::testing::Message message; + message << "While checking at index " << test.offset << " for \'" + << test.content << "\' at " << test.start_offset << '-' + << test.end_offset << '.'; SCOPED_TRACE(message); int start_offset = -1, end_offset = -1; - char* content = atk_text_get_string_at_offset(atk_text, tests[i].offset, + char* content = atk_text_get_string_at_offset(atk_text, test.offset, ATK_TEXT_GRANULARITY_WORD, &start_offset, &end_offset); - ASSERT_STREQ(content, tests[i].content) << "with test index=" << i; - ASSERT_EQ(start_offset, tests[i].start_offset) << "with test index=" << i; - ASSERT_EQ(end_offset, tests[i].end_offset) << "with test index=" << i; + ASSERT_STREQ(content, test.content) << "with test offset=" << test.offset; + ASSERT_EQ(start_offset, test.start_offset) + << "with test offset=" << test.offset; + ASSERT_EQ(end_offset, test.end_offset) + << "with test offset=" << test.offset; g_free(content); } #endif @@ -1363,38 +1364,38 @@ {1000, nullptr, -1, -1}, }; - for (unsigned i = 0; i < G_N_ELEMENTS(tests); i++) { - testing::Message message; - message << "While checking at index " << tests[i].offset << " for \'" - << tests[i].content << "\' at " << tests[i].start_offset << '-' - << tests[i].end_offset << '.'; + for (const auto& test : tests) { + ::testing::Message message; + message << "While checking at index " << test.offset << " for \'" + << test.content << "\' at " << test.start_offset << '-' + << test.end_offset << '.'; SCOPED_TRACE(message); int start_offset = -1, end_offset = -1; char* content = atk_text_get_text_at_offset( - atk_text, tests[i].offset, ATK_TEXT_BOUNDARY_SENTENCE_START, - &start_offset, &end_offset); - ASSERT_STREQ(content, tests[i].content); - ASSERT_EQ(start_offset, tests[i].start_offset); - ASSERT_EQ(end_offset, tests[i].end_offset); + atk_text, test.offset, ATK_TEXT_BOUNDARY_SENTENCE_START, &start_offset, + &end_offset); + ASSERT_STREQ(content, test.content); + ASSERT_EQ(start_offset, test.start_offset); + ASSERT_EQ(end_offset, test.end_offset); g_free(content); } #if ATK_CHECK_VERSION(2, 10, 0) - for (unsigned i = 0; i < G_N_ELEMENTS(tests); i++) { - testing::Message message; - message << "While checking at index " << tests[i].offset << " for \'" - << tests[i].content << "\' at " << tests[i].start_offset << '-' - << tests[i].end_offset << '.'; + for (const auto& test : tests) { + ::testing::Message message; + message << "While checking at index " << test.offset << " for \'" + << test.content << "\' at " << test.start_offset << '-' + << test.end_offset << '.'; SCOPED_TRACE(message); int start_offset = -1, end_offset = -1; - char* content = atk_text_get_string_at_offset(atk_text, tests[i].offset, + char* content = atk_text_get_string_at_offset(atk_text, test.offset, ATK_TEXT_GRANULARITY_SENTENCE, &start_offset, &end_offset); - ASSERT_STREQ(content, tests[i].content); - ASSERT_EQ(start_offset, tests[i].start_offset); - ASSERT_EQ(end_offset, tests[i].end_offset); + ASSERT_STREQ(content, test.content); + ASSERT_EQ(start_offset, test.start_offset); + ASSERT_EQ(end_offset, test.end_offset); g_free(content); } #endif @@ -1426,14 +1427,16 @@ {12345, nullptr, -1, -1}, }; - for (unsigned i = 0; i < G_N_ELEMENTS(tests); i++) { + for (const auto& test : tests) { int start_offset = -1, end_offset = -1; char* content = atk_text_get_string_at_offset( - atk_text, tests[i].offset, ATK_TEXT_GRANULARITY_PARAGRAPH, - &start_offset, &end_offset); - ASSERT_STREQ(content, tests[i].content) << "with test index=" << i; - ASSERT_EQ(start_offset, tests[i].start_offset) << "with test index=" << i; - ASSERT_EQ(end_offset, tests[i].end_offset) << "with test index=" << i; + atk_text, test.offset, ATK_TEXT_GRANULARITY_PARAGRAPH, &start_offset, + &end_offset); + ASSERT_STREQ(content, test.content) << "with test offset=" << test.offset; + ASSERT_EQ(start_offset, test.start_offset) + << "with test offset=" << test.offset; + ASSERT_EQ(end_offset, test.end_offset) + << "with test offset=" << test.offset; g_free(content); } #endif @@ -1465,7 +1468,7 @@ ASSERT_EQ(atk_text_get_character_count(atk_text), root_text_length); for (int i = 0; i < root_text_length; i++) { - testing::Message message; + ::testing::Message message; message << "Checking character at offset " << i; SCOPED_TRACE(message); @@ -1500,20 +1503,20 @@ static GetTextSegmentTest tests[] = {{0, "\xF0\x9F\x83\x8f ", 0, 2}, {6, "decently ", 4, 13}}; - for (unsigned i = 0; i < G_N_ELEMENTS(tests); i++) { + for (const auto& test : tests) { int start_offset = -1, end_offset = -1; - char* word = atk_text_get_text_at_offset(atk_text, tests[i].offset, + char* word = atk_text_get_text_at_offset(atk_text, test.offset, ATK_TEXT_BOUNDARY_WORD_START, &start_offset, &end_offset); - testing::Message message; - message << "Checking test with index=" << i << " and expected text=\'" - << tests[i].content << "\' at " << tests[1].start_offset << '-' - << tests[1].end_offset << '.'; + ::testing::Message message; + message << "Checking test with index=" << test.offset + << " and expected text=\'" << test.content << "\' at " + << tests[1].start_offset << '-' << tests[1].end_offset << '.'; SCOPED_TRACE(message); - ASSERT_STREQ(word, tests[i].content); - ASSERT_EQ(start_offset, tests[i].start_offset); - ASSERT_EQ(end_offset, tests[i].end_offset); + ASSERT_STREQ(word, test.content); + ASSERT_EQ(start_offset, test.start_offset); + ASSERT_EQ(end_offset, test.end_offset); g_free(word); }
diff --git a/ui/accessibility/platform/ax_platform_node_base_unittest.cc b/ui/accessibility/platform/ax_platform_node_base_unittest.cc index 8dcc9a1f..b348609b 100644 --- a/ui/accessibility/platform/ax_platform_node_base_unittest.cc +++ b/ui/accessibility/platform/ax_platform_node_base_unittest.cc
@@ -66,7 +66,7 @@ // Set an AXMode on the AXPlatformNode as some platforms (auralinux) use it to // determine if it should enable accessibility. - AXPlatformNodeBase::NotifyAddAXModeFlags(kAXModeComplete); + testing::ScopedAxModeSetter ax_mode_setter(kAXModeComplete); AXPlatformNodeBase* root = static_cast<AXPlatformNodeBase*>( TestAXNodeWrapper::GetOrCreate(&tree, tree.root())->ax_platform_node()); @@ -125,7 +125,7 @@ AXTree tree(update); // Set an AXMode on the AXPlatformNode as some platforms (auralinux) use it to // determine if it should enable accessibility. - AXPlatformNodeBase::NotifyAddAXModeFlags(kAXModeComplete); + ui::testing::ScopedAxModeSetter ax_mode_setter(kAXModeComplete); AXPlatformNodeBase* root = static_cast<AXPlatformNodeBase*>( TestAXNodeWrapper::GetOrCreate(&tree, tree.root())->ax_platform_node()); @@ -170,7 +170,7 @@ // Set an AXMode on the AXPlatformNode as some platforms (auralinux) use it to // determine if it should enable accessibility. - AXPlatformNodeBase::NotifyAddAXModeFlags(kAXModeComplete); + ui::testing::ScopedAxModeSetter ax_mode_setter(kAXModeComplete); EXPECT_EQ(root->GetInnerText(), u"abde"); @@ -202,7 +202,7 @@ } TEST(AXPlatformNodeBaseTest, TestMenuSelectedItems) { - AXPlatformNode::NotifyAddAXModeFlags(kAXModeComplete); + ui::testing::ScopedAxModeSetter ax_mode_setter(kAXModeComplete); AXNodeData root_data; root_data.id = 1; @@ -237,7 +237,7 @@ } TEST(AXPlatformNodeBaseTest, TestSelectedChildren) { - AXPlatformNode::NotifyAddAXModeFlags(kAXModeComplete); + ui::testing::ScopedAxModeSetter ax_mode_setter(kAXModeComplete); AXNodeData root_data; root_data.id = 1; @@ -272,7 +272,7 @@ } TEST(AXPlatformNodeBaseTest, TestSelectedChildrenWithGroup) { - AXPlatformNode::NotifyAddAXModeFlags(kAXModeComplete); + ui::testing::ScopedAxModeSetter ax_mode_setter(kAXModeComplete); AXNodeData root_data; root_data.id = 1; @@ -338,7 +338,7 @@ } TEST(AXPlatformNodeBaseTest, TestSelectedChildrenMixed) { - AXPlatformNode::NotifyAddAXModeFlags(kAXModeComplete); + ui::testing::ScopedAxModeSetter ax_mode_setter(kAXModeComplete); // Build the below tree which is mixed with listBoxOption and group. // id=1 listBox FOCUSABLE MULTISELECTABLE (0, 0)-(0, 0) child_ids=2,3,4,9 @@ -446,7 +446,7 @@ // n4 n5 n6 n10 // / // n7 - AXPlatformNode::NotifyAddAXModeFlags(kAXModeComplete); + ui::testing::ScopedAxModeSetter ax_mode_setter(kAXModeComplete); AXNodeData node1; node1.id = 1; node1.role = ax::mojom::Role::kRootWebArea; @@ -548,7 +548,7 @@ else if (lhs->CompareTo(*rhs) > 0) actual_result = 1; - SCOPED_TRACE(testing::Message() + SCOPED_TRACE(::testing::Message() << "lhs.id=" << base::NumberToString(lhs->GetData().id) << ", rhs.id=" << base::NumberToString(rhs->GetData().id) << ", lhs->CompareTo(*rhs)={actual:"
diff --git a/ui/accessibility/platform/ax_platform_node_unittest.h b/ui/accessibility/platform/ax_platform_node_unittest.h index d004a05..b71bc5a 100644 --- a/ui/accessibility/platform/ax_platform_node_unittest.h +++ b/ui/accessibility/platform/ax_platform_node_unittest.h
@@ -15,7 +15,7 @@ namespace ui { -class AXPlatformNodeTest : public testing::Test, public TestAXTreeManager { +class AXPlatformNodeTest : public ::testing::Test, public TestAXTreeManager { public: AXPlatformNodeTest(); ~AXPlatformNodeTest() override;
diff --git a/ui/accessibility/platform/ax_platform_node_win_unittest.cc b/ui/accessibility/platform/ax_platform_node_win_unittest.cc index e28d5c6..19f40b36 100644 --- a/ui/accessibility/platform/ax_platform_node_win_unittest.cc +++ b/ui/accessibility/platform/ax_platform_node_win_unittest.cc
@@ -185,42 +185,42 @@ expected_property_values); \ } -#define EXPECT_UIA_PROPERTY_UNORDERED_ELEMENT_ARRAY_BSTR_EQ( \ - node, array_property_id, element_test_property_id, \ - expected_property_values) \ - { \ - ScopedVariant array; \ - ASSERT_HRESULT_SUCCEEDED( \ - node->GetPropertyValue(array_property_id, array.Receive())); \ - ASSERT_EQ(VT_ARRAY | VT_UNKNOWN, array.type()); \ - ASSERT_EQ(1u, SafeArrayGetDim(array.ptr()->parray)); \ - LONG array_lower_bound; \ - ASSERT_HRESULT_SUCCEEDED( \ - SafeArrayGetLBound(array.ptr()->parray, 1, &array_lower_bound)); \ - LONG array_upper_bound; \ - ASSERT_HRESULT_SUCCEEDED( \ - SafeArrayGetUBound(array.ptr()->parray, 1, &array_upper_bound)); \ - IUnknown** array_data; \ - ASSERT_HRESULT_SUCCEEDED(::SafeArrayAccessData( \ - array.ptr()->parray, reinterpret_cast<void**>(&array_data))); \ - size_t count = array_upper_bound - array_lower_bound + 1; \ - ASSERT_EQ(expected_property_values.size(), count); \ - std::vector<std::wstring> property_values; \ - for (size_t i = 0; i < count; ++i) { \ - ComPtr<IRawElementProviderSimple> element; \ - ASSERT_HRESULT_SUCCEEDED( \ - array_data[i]->QueryInterface(IID_PPV_ARGS(&element))); \ - ScopedVariant actual; \ - ASSERT_HRESULT_SUCCEEDED(element->GetPropertyValue( \ - element_test_property_id, actual.Receive())); \ - ASSERT_EQ(VT_BSTR, actual.type()); \ - ASSERT_NE(nullptr, actual.ptr()->bstrVal); \ - property_values.push_back(std::wstring( \ - V_BSTR(actual.ptr()), SysStringLen(V_BSTR(actual.ptr())))); \ - } \ - ASSERT_HRESULT_SUCCEEDED(::SafeArrayUnaccessData(array.ptr()->parray)); \ - EXPECT_THAT(property_values, \ - testing::UnorderedElementsAreArray(expected_property_values)); \ +#define EXPECT_UIA_PROPERTY_UNORDERED_ELEMENT_ARRAY_BSTR_EQ( \ + node, array_property_id, element_test_property_id, \ + expected_property_values) \ + { \ + ScopedVariant array; \ + ASSERT_HRESULT_SUCCEEDED( \ + node->GetPropertyValue(array_property_id, array.Receive())); \ + ASSERT_EQ(VT_ARRAY | VT_UNKNOWN, array.type()); \ + ASSERT_EQ(1u, SafeArrayGetDim(array.ptr()->parray)); \ + LONG array_lower_bound; \ + ASSERT_HRESULT_SUCCEEDED( \ + SafeArrayGetLBound(array.ptr()->parray, 1, &array_lower_bound)); \ + LONG array_upper_bound; \ + ASSERT_HRESULT_SUCCEEDED( \ + SafeArrayGetUBound(array.ptr()->parray, 1, &array_upper_bound)); \ + IUnknown** array_data; \ + ASSERT_HRESULT_SUCCEEDED(::SafeArrayAccessData( \ + array.ptr()->parray, reinterpret_cast<void**>(&array_data))); \ + size_t count = array_upper_bound - array_lower_bound + 1; \ + ASSERT_EQ(expected_property_values.size(), count); \ + std::vector<std::wstring> property_values; \ + for (size_t i = 0; i < count; ++i) { \ + ComPtr<IRawElementProviderSimple> element; \ + ASSERT_HRESULT_SUCCEEDED( \ + array_data[i]->QueryInterface(IID_PPV_ARGS(&element))); \ + ScopedVariant actual; \ + ASSERT_HRESULT_SUCCEEDED(element->GetPropertyValue( \ + element_test_property_id, actual.Receive())); \ + ASSERT_EQ(VT_BSTR, actual.type()); \ + ASSERT_NE(nullptr, actual.ptr()->bstrVal); \ + property_values.push_back(std::wstring( \ + V_BSTR(actual.ptr()), SysStringLen(V_BSTR(actual.ptr())))); \ + } \ + ASSERT_HRESULT_SUCCEEDED(::SafeArrayUnaccessData(array.ptr()->parray)); \ + EXPECT_THAT(property_values, ::testing::UnorderedElementsAreArray( \ + expected_property_values)); \ } MockIRawElementProviderSimple::MockIRawElementProviderSimple() = default; @@ -6562,10 +6562,10 @@ EXPECT_NE(expandcollapse_provider.Get(), nullptr); EXPECT_HRESULT_SUCCEEDED( expandcollapse_provider->get_ExpandCollapseState(&state)); - SCOPED_TRACE(testing::Message() - << "node index: " << i << ", Actual Expanded/Collapsed State: " - << state << ", Expected Expanded/Collapsed State: " - << node_expected_state[i]); + SCOPED_TRACE( + ::testing::Message() + << "node index: " << i << ", Actual Expanded/Collapsed State: " << state + << ", Expected Expanded/Collapsed State: " << node_expected_state[i]); EXPECT_EQ(node_expected_state[i], state); } }
diff --git a/ui/base/clipboard/clipboard_test_template.h b/ui/base/clipboard/clipboard_test_template.h index e89e626..bf608e2c 100644 --- a/ui/base/clipboard/clipboard_test_template.h +++ b/ui/base/clipboard/clipboard_test_template.h
@@ -63,6 +63,7 @@ using base::ASCIIToUTF16; using base::UTF16ToUTF8; +using base::UTF8ToUTF16; using testing::Contains; @@ -365,7 +366,8 @@ // Some platforms store HTML as UTF-8 internally. Make sure fragment indices are // adjusted appropriately when converting back to UTF-16. TYPED_TEST(ClipboardTest, UnicodeHTMLTest) { - std::u16string markup(u"<div>A ø 水</div>"), markup_result; + std::u16string markup(UTF8ToUTF16("<div>A \xc3\xb8 \xe6\xb0\xb4</div>")), + markup_result; std::string url, url_result; { @@ -441,7 +443,7 @@ this->clipboard().ReadAvailableTypes(ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr, &types); EXPECT_EQ(1u, types.size()); - EXPECT_EQ(u"text/uri-list", types[0]); + EXPECT_EQ("text/uri-list", base::UTF16ToUTF8(types[0])); std::vector<ui::FileInfo> filenames; this->clipboard().ReadFilenames(ClipboardBuffer::kCopyPaste, @@ -706,7 +708,6 @@ TYPED_TEST(ClipboardTest, DataTest) { const std::string kFormatString = "chromium/x-test-format"; - const std::u16string kFormatString16 = u"chromium/x-test-format"; const ClipboardFormatType kFormat = ClipboardFormatType::GetType(kFormatString); const std::string payload = "test string"; @@ -715,7 +716,7 @@ { ScopedClipboardWriter clipboard_writer(ClipboardBuffer::kCopyPaste); - clipboard_writer.WriteData(kFormatString16, + clipboard_writer.WriteData(UTF8ToUTF16(kFormatString), mojo_base::BigBuffer(payload_span)); } @@ -735,7 +736,6 @@ !BUILDFLAG(IS_CHROMEOS_ASH) TYPED_TEST(ClipboardTest, MultipleDataTest) { const std::string kFormatString1 = "chromium/x-test-format1"; - const std::u16string kFormatString116 = u"chromium/x-test-format1"; const ClipboardFormatType kFormat1 = ClipboardFormatType::GetType(kFormatString1); const std::string payload1("test string1"); @@ -743,7 +743,6 @@ reinterpret_cast<const uint8_t*>(payload1.data()), payload1.size()); const std::string kFormatString2 = "chromium/x-test-format2"; - const std::u16string kFormatString216 = u"chromium/x-test-format2"; const ClipboardFormatType kFormat2 = ClipboardFormatType::GetType(kFormatString2); const std::string payload2("test string2"); @@ -753,16 +752,16 @@ { ScopedClipboardWriter clipboard_writer(ClipboardBuffer::kCopyPaste); // Both payloads should write successfully and not overwrite one another. - clipboard_writer.WriteData(kFormatString116, + clipboard_writer.WriteData(UTF8ToUTF16(kFormatString1), mojo_base::BigBuffer(payload_span1)); - clipboard_writer.WriteData(kFormatString216, + clipboard_writer.WriteData(UTF8ToUTF16(kFormatString2), mojo_base::BigBuffer(payload_span2)); } // Check format 1. EXPECT_THAT(this->clipboard().ReadAvailablePlatformSpecificFormatNames( ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr), - Contains(kFormatString116)); + Contains(ASCIIToUTF16(kFormatString1))); EXPECT_TRUE(this->clipboard().IsFormatAvailable( kFormat1, ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr)); std::string output1; @@ -772,7 +771,7 @@ // Check format 2. EXPECT_THAT(this->clipboard().ReadAvailablePlatformSpecificFormatNames( ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr), - Contains(kFormatString216)); + Contains(ASCIIToUTF16(kFormatString2))); EXPECT_TRUE(this->clipboard().IsFormatAvailable( kFormat2, ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr)); std::string output2; @@ -905,9 +904,9 @@ TYPED_TEST(ClipboardTest, HyperlinkTest) { const std::string kTitle("The <Example> Company's \"home page\""); const std::string kUrl("http://www.example.com?x=3<=3#\"'<>"); - const std::u16string kExpectedHtml( - u"<a href=\"http://www.example.com?x=3&lt=3#"'<>\">" - u"The <Example> Company's "home page"</a>"); + const std::u16string kExpectedHtml(UTF8ToUTF16( + "<a href=\"http://www.example.com?x=3&lt=3#"'<>\">" + "The <Example> Company's "home page"</a>")); std::string url_result; std::u16string html_result;
diff --git a/ui/base/cursor/cursor_factory.cc b/ui/base/cursor/cursor_factory.cc index 9eef1fe..1b727571 100644 --- a/ui/base/cursor/cursor_factory.cc +++ b/ui/base/cursor/cursor_factory.cc
@@ -21,6 +21,8 @@ } // namespace +CursorFactoryObserver::~CursorFactoryObserver() = default; + CursorFactory::CursorFactory() { DCHECK(!g_instance) << "There should only be a single CursorFactory."; g_instance = this; @@ -36,6 +38,19 @@ return g_instance; } +void CursorFactory::AddObserver(CursorFactoryObserver* observer) { + observers_.AddObserver(observer); +} + +void CursorFactory::RemoveObserver(CursorFactoryObserver* observer) { + observers_.RemoveObserver(observer); +} + +void CursorFactory::NotifyObserversOnThemeLoaded() { + for (auto& observer : observers_) + observer.OnThemeLoaded(); +} + scoped_refptr<PlatformCursor> CursorFactory::GetDefaultCursor( mojom::CursorType type) { NOTIMPLEMENTED();
diff --git a/ui/base/cursor/cursor_factory.h b/ui/base/cursor/cursor_factory.h index 95991f1..1423293 100644 --- a/ui/base/cursor/cursor_factory.h +++ b/ui/base/cursor/cursor_factory.h
@@ -9,6 +9,7 @@ #include <vector> #include "base/component_export.h" +#include "base/observer_list.h" #include "build/build_config.h" #include "ui/base/cursor/mojom/cursor_type.mojom-forward.h" @@ -28,6 +29,14 @@ namespace ui { class PlatformCursor; +class COMPONENT_EXPORT(UI_BASE_CURSOR_BASE) CursorFactoryObserver { + public: + // Called by the factory after it has loaded the cursor theme. + virtual void OnThemeLoaded() = 0; + + virtual ~CursorFactoryObserver(); +}; + class COMPONENT_EXPORT(UI_BASE_CURSOR_BASE) CursorFactory { public: CursorFactory(); @@ -36,6 +45,10 @@ // Returns the thread-local instance. static CursorFactory* GetInstance(); + void AddObserver(CursorFactoryObserver* observer); + void RemoveObserver(CursorFactoryObserver* observer); + void NotifyObserversOnThemeLoaded(); + // Return the default cursor of the specified type. When a default cursor is // not available, nullptr is returned. virtual scoped_refptr<PlatformCursor> GetDefaultCursor( @@ -63,6 +76,9 @@ // Sets the device scale factor that CursorFactory may use when creating // cursors. virtual void SetDeviceScaleFactor(float scale); + + private: + base::ObserverList<CursorFactoryObserver>::Unchecked observers_; }; #if defined(OS_LINUX) || defined(OS_CHROMEOS)
diff --git a/ui/base/cursor/cursor_loader.cc b/ui/base/cursor/cursor_loader.cc index ab8d4a34..7529e8e 100644 --- a/ui/base/cursor/cursor_loader.cc +++ b/ui/base/cursor/cursor_loader.cc
@@ -33,9 +33,16 @@ CursorLoader::CursorLoader(bool use_platform_cursors) : use_platform_cursors_(use_platform_cursors), - factory_(CursorFactory::GetInstance()) {} + factory_(CursorFactory::GetInstance()) { + factory_->AddObserver(this); +} CursorLoader::~CursorLoader() { + factory_->RemoveObserver(this); + UnloadCursors(); +} + +void CursorLoader::OnThemeLoaded() { UnloadCursors(); }
diff --git a/ui/base/cursor/cursor_loader.h b/ui/base/cursor/cursor_loader.h index c949b6c..39e0320 100644 --- a/ui/base/cursor/cursor_loader.h +++ b/ui/base/cursor/cursor_loader.h
@@ -11,6 +11,7 @@ #include "base/component_export.h" #include "base/memory/scoped_refptr.h" #include "ui/base/cursor/cursor.h" +#include "ui/base/cursor/cursor_factory.h" #include "ui/base/cursor/cursor_size.h" #include "ui/base/cursor/mojom/cursor_type.mojom-forward.h" #include "ui/display/display.h" @@ -20,15 +21,18 @@ } namespace ui { -class CursorFactory; class PlatformCursor; -class COMPONENT_EXPORT(UI_BASE_CURSOR) CursorLoader { +class COMPONENT_EXPORT(UI_BASE_CURSOR) CursorLoader + : public CursorFactoryObserver { public: explicit CursorLoader(bool use_platform_cursors = true); CursorLoader(const CursorLoader&) = delete; CursorLoader& operator=(const CursorLoader&) = delete; - ~CursorLoader(); + ~CursorLoader() override; + + // CursorFactoryObserver: + void OnThemeLoaded() override; // Returns the rotation and scale of the currently loaded cursor. display::Display::Rotation rotation() const { return rotation_; }
diff --git a/ui/gfx/bidi_line_iterator_unittest.cc b/ui/gfx/bidi_line_iterator_unittest.cc index 73032f2..d8dbc51c 100644 --- a/ui/gfx/bidi_line_iterator_unittest.cc +++ b/ui/gfx/bidi_line_iterator_unittest.cc
@@ -121,10 +121,9 @@ TEST_P(BiDiLineIteratorTest, RTLPunctuationNoCustomBehavior) { // This string features Hebrew characters interleaved with ASCII punctuation. - iterator()->Open( - u"א!ב\"ג#ד$ה%ו&ז'ח(ט)י*ך+כ,ל-ם.מ/" - u"ן:נ;ס<ע=ף>פ?ץ@צ[ק\\ר]ש^ת_א`ב{ג|ד}ה~ו", - GetParam()); + iterator()->Open(base::UTF8ToUTF16("א!ב\"ג#ד$ה%ו&ז'ח(ט)י*ך+כ,ל-ם.מ/" + "ן:נ;ס<ע=ף>פ?ץ@צ[ק\\ר]ש^ת_א`ב{ג|ד}ה~ו"), + GetParam()); // Expect a single RTL run. ASSERT_EQ(1, iterator()->CountRuns());
diff --git a/ui/gfx/render_text_unittest.cc b/ui/gfx/render_text_unittest.cc index e0fd5c5..132b257 100644 --- a/ui/gfx/render_text_unittest.cc +++ b/ui/gfx/render_text_unittest.cc
@@ -60,18 +60,22 @@ #include "base/mac/mac_util.h" #endif +using base::ASCIIToUTF16; +using base::UTF8ToUTF16; +using base::WideToUTF16; + namespace gfx { namespace { // Various weak, LTR, RTL, and Bidi string cases with three characters each. -const char16_t kWeak[] = u" . "; -const char16_t kLtr[] = u"abc"; -const char16_t kRtl[] = u"אבג"; -const char16_t kLtrRtl[] = u"aאב"; -const char16_t kLtrRtlLtr[] = u"aבb"; -const char16_t kRtlLtr[] = u"אבa"; -const char16_t kRtlLtrRtl[] = u"אaב"; +const char kWeak[] = " . "; +const char kLtr[] = "abc"; +const char kRtl[] = "\u05d0\u05d1\u05d2"; +const char kLtrRtl[] = "a\u05d0\u05d1"; +const char kLtrRtlLtr[] = "a\u05d1b"; +const char kRtlLtr[] = "\u05d0\u05d1a"; +const char kRtlLtrRtl[] = "\u05d0a\u05d1"; constexpr bool kUseWordWrap = true; constexpr bool kUseObscuredText = true; @@ -253,6 +257,15 @@ return std::u16string(length, RenderText::kPasswordReplacementChar); } +// Converts a vector of UTF8 literals into a vector of (UTF16) string16. +std::vector<std::u16string> ToString16Vec( + const std::vector<const char*>& utf8_literals) { + std::vector<std::u16string> vec; + for (auto* const literal : utf8_literals) + vec.push_back(UTF8ToUTF16(literal)); + return vec; +} + // Returns the combined character range from all text runs on |line|. Range LineCharRange(const internal::Line& line) { if (line.segments.empty()) @@ -663,14 +676,14 @@ // Check the default styles applied to new instances and adjusted text. RenderText* render_text = GetRenderText(); EXPECT_TRUE(render_text->text().empty()); - const char16_t* const cases[] = {kWeak, kLtr, u"Hello", kRtl, u"", u""}; + const char* const cases[] = {kWeak, kLtr, "Hello", kRtl, "", ""}; for (size_t i = 0; i < base::size(cases); ++i) { EXPECT_TRUE(test_api()->colors().EqualsValueForTesting(kPlaceholderColor)); EXPECT_TRUE(test_api()->baselines().EqualsValueForTesting(NORMAL_BASELINE)); EXPECT_TRUE(test_api()->font_size_overrides().EqualsValueForTesting(0)); for (size_t style = 0; style < static_cast<int>(TEXT_STYLE_COUNT); ++style) EXPECT_TRUE(test_api()->styles()[style].EqualsValueForTesting(false)); - render_text->SetText(cases[i]); + render_text->SetText(UTF8ToUTF16(cases[i])); } } @@ -682,7 +695,7 @@ render_text->SetBaselineStyle(SUPERSCRIPT); render_text->SetWeight(Font::Weight::BOLD); render_text->SetStyle(TEXT_STYLE_UNDERLINE, false); - const char16_t* const cases[] = {kWeak, kLtr, u"Hello", kRtl, u"", u""}; + const char* const cases[] = {kWeak, kLtr, "Hello", kRtl, "", ""}; for (size_t i = 0; i < base::size(cases); ++i) { EXPECT_TRUE(test_api()->colors().EqualsValueForTesting(color)); EXPECT_TRUE(test_api()->baselines().EqualsValueForTesting(SUPERSCRIPT)); @@ -691,7 +704,7 @@ EXPECT_TRUE( test_api()->styles()[TEXT_STYLE_UNDERLINE].EqualsValueForTesting( false)); - render_text->SetText(cases[i]); + render_text->SetText(UTF8ToUTF16(cases[i])); // Ensure custom default styles can be applied after text has been set. if (i == 1) @@ -808,7 +821,7 @@ TEST_F(RenderTextTest, ApplyStyleGrapheme) { RenderText* render_text = GetRenderText(); - render_text->SetText(u"e\u0301"); + render_text->SetText(u"\u0065\u0301"); render_text->ApplyStyle(TEXT_STYLE_ITALIC, true, gfx::Range(1, 2)); render_text->ApplyStyle(TEXT_STYLE_UNDERLINE, true, gfx::Range(0, 1)); Draw(); @@ -819,7 +832,7 @@ TEST_F(RenderTextTest, ApplyStyleMultipleGraphemes) { RenderText* render_text = GetRenderText(); - render_text->SetText(u"xxe\u0301x"); + render_text->SetText(u"xx\u0065\u0301x"); // Apply the style in the middle of a grapheme. gfx::Range range(1, 3); render_text->ApplyStyle(TEXT_STYLE_ITALIC, true, range); @@ -930,14 +943,14 @@ // Render the isolated form of the first glyph. RenderText* render_text = GetRenderText(); - render_text->SetText(u"ب"); + render_text->SetText(u"\u0628"); Draw(); ASSERT_EQ(1u, text_log().size()); ASSERT_EQ(1u, text_log()[0].glyphs().size()); uint16_t isolated_first_glyph = text_log()[0].glyphs()[0]; // Render a pair of glyphs (initial form and final form). - render_text->SetText(u"بم"); + render_text->SetText(u"\u0628\u0645"); Draw(); ASSERT_EQ(1u, text_log().size()); ASSERT_LE(2u, text_log()[0].glyphs().size()); @@ -1055,8 +1068,7 @@ constexpr float kGlyphWidth = 5.5f; constexpr Size kCanvasSize(300, 50); constexpr SkColor kTranslucentBlue = SkColorSetARGB(0x7F, 0x00, 0x00, 0xFF); - const char* const kTestString{"A B C D"}; - const char16_t* const kTestString16{u"A B C D"}; + const char* kTestString{"A B C D"}; SkBitmap bitmap; bitmap.allocPixels( @@ -1070,7 +1082,7 @@ render_text->set_selection_background_focused_color(kTranslucentBlue); render_text->set_focused(true); - render_text->SetText(kTestString16); + render_text->SetText(UTF8ToUTF16(kTestString)); render_text->SelectRange(Range(0, 7)); const Rect text_rect = Rect(render_text->GetStringSize()); render_text->SetDisplayRect(text_rect); @@ -1086,7 +1098,7 @@ TEST_F(RenderTextTest, SelectRangeColoredGrapheme) { RenderText* render_text = GetRenderText(); - render_text->SetText(u"xe\u0301y"); + render_text->SetText(u"x\u0065\u0301y"); render_text->SetColor(SK_ColorBLACK); render_text->set_selection_color(SK_ColorGREEN); render_text->set_focused(true); @@ -1149,7 +1161,7 @@ TEST_F(RenderTextTest, SetCompositionRangeColoredGrapheme) { RenderText* render_text = GetRenderText(); - render_text->SetText(u"xe\u0301y"); + render_text->SetText(u"x\u0065\u0301y"); render_text->SetCompositionRange(Range(0, 1)); Draw(); @@ -1251,16 +1263,15 @@ std::ceil(render_text->GetCursorSpan({0, 2}).length())); // Cursoring is independent of underlying characters when text is obscured. - const char16_t* const texts[] = { - kWeak, kLtr, kLtrRtl, kLtrRtlLtr, kRtl, kRtlLtr, kRtlLtrRtl, - u"hop on pop", // Check LTR word boundaries. - u"אב אג בג", // Check RTL word boundaries. + const char* const texts[] = { + kWeak, kLtr, kLtrRtl, kLtrRtlLtr, kRtl, kRtlLtr, kRtlLtrRtl, + "hop on pop", // Check LTR word boundaries. + "\u05d0\u05d1 \u05d0\u05d2 \u05d1\u05d2", // Check RTL word boundaries. }; for (size_t i = 0; i < base::size(texts); ++i) { - TestVisualCursorMotionInObscuredField(render_text, texts[i], - SELECTION_NONE); - TestVisualCursorMotionInObscuredField(render_text, texts[i], - SELECTION_RETAIN); + std::u16string text = UTF8ToUTF16(texts[i]); + TestVisualCursorMotionInObscuredField(render_text, text, SELECTION_NONE); + TestVisualCursorMotionInObscuredField(render_text, text, SELECTION_RETAIN); } } @@ -1337,7 +1348,8 @@ // Text with invalid surrogates (surrogates low 0xDC00 and high 0xD800). // Invalid surrogates are replaced by replacement character (e.g. 0xFFFD). - render_text->SetText(u"\xDC00\xD800hop"); + const char16_t invalid_surrogates[] = {0xDC00, 0xD800, 'h', 'o', 'p', 0}; + render_text->SetText(invalid_surrogates); EXPECT_EQ(GetObscuredString(5), render_text->GetDisplayText()); render_text->RenderText::SetObscuredRevealIndex(0); EXPECT_EQ(GetObscuredString(5, 0, 0xFFFD), render_text->GetDisplayText()); @@ -1347,7 +1359,9 @@ EXPECT_EQ(GetObscuredString(5, 2, 'h'), render_text->GetDisplayText()); // Text with valid surrogates before and after the reveal index. - render_text->SetText(u"\xD800\xDC00hop\xD800\xDC00"); + const char16_t valid_surrogates[] = {0xD800, 0xDC00, 'h', 'o', + 'p', 0xD800, 0xDC00, 0}; + render_text->SetText(valid_surrogates); EXPECT_EQ(GetObscuredString(5), render_text->GetDisplayText()); render_text->RenderText::SetObscuredRevealIndex(0); const char16_t valid_expect_0_and_1[] = {0xD800, @@ -1380,11 +1394,12 @@ RenderText* render_text = GetRenderText(); render_text->SetObscured(true); // Test U+1F601 😁 "Grinning face with smiling eyes", followed by 'y'. - render_text->SetText(u"😁y"); + // Windows requires wide strings for \Unnnnnnnn universal character names. + render_text->SetText(u"\U0001F601y"); render_text->Draw(canvas()); - // Emoji codepoints are replaced by bullets. - EXPECT_EQ(u"••", render_text->GetDisplayText()); + // Emoji codepoints are replaced by bullets (e.g. "\u2022\u2022"). + EXPECT_EQ(u"\u2022\u2022", render_text->GetDisplayText()); EXPECT_EQ(0U, test_api()->TextIndexToDisplayIndex(0U)); EXPECT_EQ(0U, test_api()->TextIndexToDisplayIndex(1U)); EXPECT_EQ(1U, test_api()->TextIndexToDisplayIndex(2U)); @@ -1397,11 +1412,12 @@ EXPECT_EQ(3U, test_api()->DisplayIndexToTextIndex(2U)); // Test two U+1F4F7 📷 "Camera" characters in a row. - render_text->SetText(u"📷📷"); + // Windows requires wide strings for \Unnnnnnnn universal character names. + render_text->SetText(u"\U0001F4F7\U0001F4F7"); render_text->Draw(canvas()); - // Emoji codepoints are replaced by bullets. - EXPECT_EQ(u"••", render_text->GetDisplayText()); + // Emoji codepoints are replaced by bullets (e.g. "\u2022\u2022"). + EXPECT_EQ(u"\u2022\u2022", render_text->GetDisplayText()); EXPECT_EQ(0U, test_api()->TextIndexToDisplayIndex(0U)); EXPECT_EQ(0U, test_api()->TextIndexToDisplayIndex(1U)); EXPECT_EQ(1U, test_api()->TextIndexToDisplayIndex(2U)); @@ -1414,7 +1430,7 @@ render_text->SetObscuredRevealIndex(0); render_text->Draw(canvas()); - EXPECT_EQ(u"📷•", render_text->GetDisplayText()); + EXPECT_EQ(u"\U0001F4F7\u2022", render_text->GetDisplayText()); EXPECT_EQ(0U, test_api()->TextIndexToDisplayIndex(0U)); EXPECT_EQ(0U, test_api()->TextIndexToDisplayIndex(1U)); EXPECT_EQ(2U, test_api()->TextIndexToDisplayIndex(2U)); @@ -1428,7 +1444,7 @@ TEST_F(RenderTextTest, ObscuredEmojiRevealed) { RenderText* render_text = GetRenderText(); - std::u16string text = u"123📷📷x😁-"; + std::u16string text = u"123\U0001F4F7\U0001F4F7x\U0001F601-"; for (size_t i = 0; i < text.length(); ++i) { render_text->SetText(text); render_text->SetObscured(true); @@ -1439,7 +1455,7 @@ struct TextIndexConversionCase { const char* test_name; - const char16_t* text; + const wchar_t* text; }; using TextIndexConversionParam = @@ -1465,7 +1481,7 @@ size_t reveal_index = std::get<2>(GetParam()); RenderText* render_text = GetRenderText(); - render_text->SetText(param.text); + render_text->SetText(WideToUTF16(param.text)); render_text->SetObscured(obscured); render_text->SetObscuredRevealIndex(reveal_index); render_text->Draw(canvas()); @@ -1493,15 +1509,15 @@ } const TextIndexConversionCase kTextIndexConversionCases[] = { - {"simple", u"abc"}, - {"simple_obscured1", u"abc"}, - {"simple_obscured2", u"abc"}, - {"emoji_asc", u"😨1234"}, - {"emoji_asc_obscured0", u"😨1234"}, - {"emoji_asc_obscured2", u"😨1234"}, - {"picto_title", u"x☛"}, - {"simple_mixed", u"aaڭڭcc"}, - {"simple_rtl", u"أسكي"}, + {"simple", L"abc"}, + {"simple_obscured1", L"abc"}, + {"simple_obscured2", L"abc"}, + {"emoji_asc", L"\U0001F6281234"}, + {"emoji_asc_obscured0", L"\U0001F6281234"}, + {"emoji_asc_obscured2", L"\U0001F6281234"}, + {"picto_title", L"x☛"}, + {"simple_mixed", L"aaڭڭcc"}, + {"simple_rtl", L"أسكي"}, }; // Validate that conversion text and between display text indexes are consistent @@ -1516,7 +1532,7 @@ struct RunListCase { const char* test_name; - const char16_t* text; + const wchar_t* text; const char* expected; const bool multiline = false; }; @@ -1535,39 +1551,40 @@ RunListCase param = GetParam(); RenderTextHarfBuzz* render_text = GetRenderText(); render_text->SetMultiline(param.multiline); - render_text->SetText(param.text); + render_text->SetText(WideToUTF16(param.text)); EXPECT_EQ(param.expected, GetRunListStructureString()); } const RunListCase kBasicsRunListCases[] = { - {"simpleLTR", u"abc", "[0->2]"}, - {"simpleRTL", u"ښڛڜ", "[2<-0]"}, - {"asc_arb", u"abcښڛڜdef", "[0->2][5<-3][6->8]"}, - {"asc_dev_asc", u"abcऔकखdefڜ", "[0->2][3->5][6->8][9]"}, - {"phone", u"1-(800)-xxx-xxxx", "[0][1][2][3->5][6][7][8->10][11][12->15]"}, - {"dev_ZWS", u"क\u200Bख", "[0][1][2]"}, - {"numeric", u"1 2 3 4", "[0][1][2][3][4][5][6]"}, - {"joiners1", u"1\u200C2\u200C3\u200C4", "[0->6]"}, - {"joiners2", u"؏\u200C؏", "[0->2]"}, - {"combining_accents1", u"àé", "[0->3]"}, - {"combining_accents2", u"ëё", "[0->1][2->3]"}, - {"picto_title", u"☞☛test☚☜", "[0->1][2->5][6->7]"}, - {"picto_LTR", u"☺☺☺!", "[0->2][3]"}, - {"picto_RTL", u"☺☺☺ښ", "[3][2<-0]"}, - {"paren_picto", u"(☾☹☽)", "[0][1][2][3][4]"}, - {"emoji_asc", u"😨1234", "[0->1][2->5]"}, // http://crbug.com/530021 - {"emoji_title", u"▶Feel goods", + {"simpleLTR", L"abc", "[0->2]"}, + {"simpleRTL", L"ښڛڜ", "[2<-0]"}, + {"asc_arb", L"abcښڛڜdef", "[0->2][5<-3][6->8]"}, + {"asc_dev_asc", L"abcऔकखdefڜ", "[0->2][3->5][6->8][9]"}, + {"phone", L"1-(800)-xxx-xxxx", "[0][1][2][3->5][6][7][8->10][11][12->15]"}, + {"dev_ZWS", L"क\u200Bख", "[0][1][2]"}, + {"numeric", L"1 2 3 4", "[0][1][2][3][4][5][6]"}, + {"joiners1", L"1\u200C2\u200C3\u200C4", "[0->6]"}, + {"joiners2", L"\u060F\u200C\u060F", "[0->2]"}, + {"combining_accents1", L"a\u0300e\u0301", "[0->3]"}, + {"combining_accents2", L"\u0065\u0308\u0435\u0308", "[0->1][2->3]"}, + {"picto_title", L"☞☛test☚☜", "[0->1][2->5][6->7]"}, + {"picto_LTR", L"☺☺☺!", "[0->2][3]"}, + {"picto_RTL", L"☺☺☺ښ", "[3][2<-0]"}, + {"paren_picto", L"(☾☹☽)", "[0][1][2][3][4]"}, + {"emoji_asc", L"\U0001F6281234", + "[0->1][2->5]"}, // http://crbug.com/530021 + {"emoji_title", L"▶Feel goods", "[0][1->4][5][6->10]"}, // http://crbug.com/278913 - {"jap_paren1", u"ぬ「シ」ほ", + {"jap_paren1", L"ぬ「シ」ほ", "[0][1][2][3][4]"}, // http://crbug.com/396776 - {"jap_paren2", u"國哲(c)1", + {"jap_paren2", L"國哲(c)1", "[0->1][2][3][4][5]"}, // http://crbug.com/125792 - {"newline1", u"\n\n", "[0->1]"}, - {"newline2", u"\r\n\r\n", "[0->3]"}, - {"newline3", u"\r\r\n", "[0->2]"}, - {"multiline_newline1", u"\n\n", "[0][1]", true}, - {"multiline_newline2", u"\r\n\r\n", "[0->1][2->3]", true}, - {"multiline_newline3", u"\r\r\n", "[0][1->2]", true}, + {"newline1", L"\n\n", "[0->1]"}, + {"newline2", L"\r\n\r\n", "[0->3]"}, + {"newline3", L"\r\r\n", "[0->2]"}, + {"multiline_newline1", L"\n\n", "[0][1]", true}, + {"multiline_newline2", L"\r\n\r\n", "[0->1][2->3]", true}, + {"multiline_newline3", L"\r\r\n", "[0][1->2]", true}, }; INSTANTIATE_TEST_SUITE_P(ItemizeTextToRunsBasics, @@ -1577,38 +1594,38 @@ // see 'Unicode Bidirectional Algorithm': http://unicode.org/reports/tr9/ const RunListCase kBidiRunListCases[] = { - {"simple_ltr", u"ascii", "[0->4]"}, - {"simple_rtl", u"أسكي", "[3<-0]"}, - {"simple_mixed", u"aaڭڭcc", "[0->1][3<-2][4->5]"}, - {"simple_mixed_LRE", u"\u202Aaaڭڭcc\u202C", "[0][1->2][4<-3][5->6][7]"}, - {"simple_mixed_RLE", u"\u202Baaڭڭcc\u202C", "[7][5->6][4<-3][0][1->2]"}, - {"sequence_RLE", u"\u202Baa\u202C\u202Bbb\u202C", + {"simple_ltr", L"ascii", "[0->4]"}, + {"simple_rtl", L"أسكي", "[3<-0]"}, + {"simple_mixed", L"aaڭڭcc", "[0->1][3<-2][4->5]"}, + {"simple_mixed_LRE", L"\u202Aaaڭڭcc\u202C", "[0][1->2][4<-3][5->6][7]"}, + {"simple_mixed_RLE", L"\u202Baaڭڭcc\u202C", "[7][5->6][4<-3][0][1->2]"}, + {"sequence_RLE", L"\u202Baa\u202C\u202Bbb\u202C", "[7][0][1->2][3->4][5->6]"}, - {"simple_mixed_LRI", u"\u2066aaڭڭcc\u2069", "[0][1->2][4<-3][5->6][7]"}, - {"simple_mixed_RLI", u"\u2067aaڭڭcc\u2069", "[0][5->6][4<-3][1->2][7]"}, - {"sequence_RLI", u"\u2067aa\u2069\u2067bb\u2069", + {"simple_mixed_LRI", L"\u2066aaڭڭcc\u2069", "[0][1->2][4<-3][5->6][7]"}, + {"simple_mixed_RLI", L"\u2067aaڭڭcc\u2069", "[0][5->6][4<-3][1->2][7]"}, + {"sequence_RLI", L"\u2067aa\u2069\u2067bb\u2069", "[0][1->2][3->4][5->6][7]"}, - {"override_ltr_RLO", u"\u202Eaaa\u202C", "[4][3<-1][0]"}, - {"override_rtl_LRO", u"\u202Dڭڭڭ\u202C", "[0][1->3][4]"}, - {"neutral_strong_ltr", u"a!!a", "[0][1->2][3]"}, - {"neutral_strong_rtl", u"ڭ!!ڭ", "[3][2<-1][0]"}, - {"neutral_strong_both", u"a a ڭ ڭ", "[0][1][2][3][6][5][4]"}, - {"neutral_strong_both_RLE", u"\u202Ba a ڭ ڭ\u202C", + {"override_ltr_RLO", L"\u202Eaaa\u202C", "[4][3<-1][0]"}, + {"override_rtl_LRO", L"\u202Dڭڭڭ\u202C", "[0][1->3][4]"}, + {"neutral_strong_ltr", L"a!!a", "[0][1->2][3]"}, + {"neutral_strong_rtl", L"ڭ!!ڭ", "[3][2<-1][0]"}, + {"neutral_strong_both", L"a a ڭ ڭ", "[0][1][2][3][6][5][4]"}, + {"neutral_strong_both_RLE", L"\u202Ba a ڭ ڭ\u202C", "[8][7][6][5][4][0][1][2][3]"}, - {"weak_numbers", u"one ڭ222ڭ", "[0->2][3][8][5->7][4]"}, - {"not_weak_letters", u"one ڭabcڭ", "[0->2][3][4][5->7][8]"}, - {"weak_arabic_numbers", u"one ڭ١٢٣ڭ", "[0->2][3][8][5->7][4]"}, - {"neutral_LRM_pre", u"\u200E……", "[0->2]"}, - {"neutral_LRM_post", u"……\u200E", "[0->2]"}, - {"neutral_RLM_pre", u"\u200F……", "[2<-0]"}, - {"neutral_RLM_post", u"……\u200F", "[2<-0]"}, - {"brackets_ltr", u"aa(ڭڭ)……", "[0->1][2][4<-3][5][6->7]"}, - {"brackets_rtl", u"ڭڭ(aa)……", "[7<-6][5][3->4][2][1<-0]"}, - {"mixed_with_punct", u"aa \"ڭڭ!\", aa", + {"weak_numbers", L"one ڭ222ڭ", "[0->2][3][8][5->7][4]"}, + {"not_weak_letters", L"one ڭabcڭ", "[0->2][3][4][5->7][8]"}, + {"weak_arabic_numbers", L"one ڭ١٢٣ڭ", "[0->2][3][8][5->7][4]"}, + {"neutral_LRM_pre", L"\u200E\u2026\u2026", "[0->2]"}, + {"neutral_LRM_post", L"\u2026\u2026\u200E", "[0->2]"}, + {"neutral_RLM_pre", L"\u200F\u2026\u2026", "[2<-0]"}, + {"neutral_RLM_post", L"\u2026\u2026\u200F", "[2<-0]"}, + {"brackets_ltr", L"aa(ڭڭ)\u2026\u2026", "[0->1][2][4<-3][5][6->7]"}, + {"brackets_rtl", L"ڭڭ(aa)\u2026\u2026", "[7<-6][5][3->4][2][1<-0]"}, + {"mixed_with_punct", L"aa \"ڭڭ!\", aa", "[0->1][2][3][5<-4][6->8][9][10->11]"}, - {"mixed_with_punct_RLI", u"aa \"\u2067ڭڭ!\u2069\", aa", + {"mixed_with_punct_RLI", L"aa \"\u2067ڭڭ!\u2069\", aa", "[0->1][2][3][4][7][6<-5][8][9->10][11][12->13]"}, - {"mixed_with_punct_RLM", u"aa \"ڭڭ!\u200F\", aa", + {"mixed_with_punct_RLM", L"aa \"ڭڭ!\u200F\", aa", "[0->1][2][3][7][6][5<-4][8->9][10][11->12]"}, }; @@ -1618,17 +1635,18 @@ RenderTextTestWithRunListCase::ParamInfoToString); const RunListCase kBracketsRunListCases[] = { - {"matched_parens", u"(a)", "[0][1][2]"}, - {"double_matched_parens", u"((a))", "[0->1][2][3->4]"}, - {"double_matched_parens2", u"((aaa))", "[0->1][2->4][5->6]"}, - {"square_brackets", u"[...]x", "[0][1->3][4][5]"}, - {"curly_brackets", u"{}x{}", "[0->1][2][3->4]"}, - {"style_brackets", u"「...」x", "[0][1->3][4][5]"}, - {"tibetan_brackets", u"༺༻༠༠༼༽", "[0->1][2->3][4->5]"}, - {"angle_brackets", u"〈〇〇〉", "[0][1->2][3]"}, - {"double_angle_brackets", u"《〇〇》", "[0][1->2][3]"}, - {"corner_angle_brackets", u"「〇〇」", "[0][1->2][3]"}, - {"fullwidth_parens", u"(!)", "[0][1][2]"}, + {"matched_parens", L"(a)", "[0][1][2]"}, + {"double_matched_parens", L"((a))", "[0->1][2][3->4]"}, + {"double_matched_parens2", L"((aaa))", "[0->1][2->4][5->6]"}, + {"square_brackets", L"[...]x", "[0][1->3][4][5]"}, + {"curly_brackets", L"{}x{}", "[0->1][2][3->4]"}, + {"style_brackets", L"\u300c...\u300dx", "[0][1->3][4][5]"}, + {"tibetan_brackets", L"\u0f3a\u0f3b\u0f20\u0f20\u0f3c\u0f3d", + "[0->1][2->3][4->5]"}, + {"angle_brackets", L"\u3008\u3007\u3007\u3009", "[0][1->2][3]"}, + {"double_angle_brackets", L"\u300A\u3007\u3007\u300B", "[0][1->2][3]"}, + {"corner_angle_brackets", L"\u300C\u3007\u3007\u300D", "[0][1->2][3]"}, + {"fullwidth_parens", L"\uff08\uff01\uff09", "[0][1][2]"}, }; INSTANTIATE_TEST_SUITE_P(ItemizeTextToRunsBrackets, @@ -1640,15 +1658,15 @@ // account while performing the text itemization. // See table 7 from http://www.unicode.org/reports/tr24/tr24-29.html const RunListCase kScriptExtensionRunListCases[] = { - {"implicit_com_inherited", u"a\u0301", "[0->1]"}, - {"explicit_lat", u"\u0061d", "[0->1]"}, - {"explicit_inherited_lat", u"x\u0363d", "[0->2]"}, - {"explicit_inherited_dev", u"क\u1CD1क", "[0->2]"}, - {"multi_explicit_hira", u"は\u30FCz", "[0->1][2]"}, - {"multi_explicit_kana", u"ハ\u30FCz", "[0->1][2]"}, - {"multi_explicit_lat", u"a\u30FCz", "[0][1][2]"}, - {"multi_explicit_impl_dev", u"क\u1CD0z", "[0->1][2]"}, - {"multi_explicit_expl_dev", u"क\u096Fz", "[0->1][2]"}, + {"implicit_com_inherited", L"a\u0301", "[0->1]"}, + {"explicit_lat", L"\u0061d", "[0->1]"}, + {"explicit_inherited_lat", L"x\u0363d", "[0->2]"}, + {"explicit_inherited_dev", L"क\u1CD1क", "[0->2]"}, + {"multi_explicit_hira", L"は\u30FCz", "[0->1][2]"}, + {"multi_explicit_kana", L"ハ\u30FCz", "[0->1][2]"}, + {"multi_explicit_lat", L"a\u30FCz", "[0][1][2]"}, + {"multi_explicit_impl_dev", L"क\u1CD0z", "[0->1][2]"}, + {"multi_explicit_expl_dev", L"क\u096Fz", "[0->1][2]"}, }; INSTANTIATE_TEST_SUITE_P(ItemizeTextToRunsScriptExtension, @@ -1661,111 +1679,111 @@ // See ScriptExtensions.txt and Scripts.txt from // http://www.unicode.org/reports/tr24/tr24-29.html const RunListCase kScriptsRunListCases[] = { - {"lat", u"abc", "[0->2]"}, - {"lat_diac", u"e\u0308f", "[0->2]"}, + {"lat", L"abc", "[0->2]"}, + {"lat_diac", L"e\u0308f", "[0->2]"}, // Indic Fraction codepoints have large set of script extensions. - {"indic_fraction", u"\uA830\uA832\uA834\uA835", "[0->3]"}, + {"indic_fraction", L"\uA830\uA832\uA834\uA835", "[0->3]"}, // Devanagari Danda codepoints have large set of script extensions. - {"dev_danda", u"\u0964\u0965", "[0->1]"}, + {"dev_danda", L"\u0964\u0965", "[0->1]"}, // Combining Diacritical Marks (inherited) should only merge with preceding. - {"diac_lat", u"\u0308fg", "[0][1->2]"}, - {"diac_dev", u"क\u0308f", "[0->1][2]"}, + {"diac_lat", L"\u0308fg", "[0][1->2]"}, + {"diac_dev", L"क\u0308f", "[0->1][2]"}, // ZWJW has the inherited script. - {"lat_ZWNJ", u"ab\u200Ccd", "[0->4]"}, - {"dev_ZWNJ", u"क\u200Cक", "[0->2]"}, - {"lat_dev_ZWNJ", u"a\u200Cक", "[0->1][2]"}, + {"lat_ZWNJ", L"ab\u200Ccd", "[0->4]"}, + {"dev_ZWNJ", L"क\u200Cक", "[0->2]"}, + {"lat_dev_ZWNJ", L"a\u200Cक", "[0->1][2]"}, // Invalid codepoints. - {"invalid_cp", u"\uFFFE", "[0]"}, - {"invalid_cps", u"\uFFFE\uFFFF", "[0->1]"}, - {"unknown", u"a\u243Fb", "[0][1][2]"}, + {"invalid_cp", L"\uFFFE", "[0]"}, + {"invalid_cps", L"\uFFFE\uFFFF", "[0->1]"}, + {"unknown", L"a\u243Fb", "[0][1][2]"}, // Codepoints from different code block should be in same run when part of // the same script. - {"blocks_lat", u"aɒɠƉĚÑ", "[0->5]"}, - {"blocks_lat_paren", u"([_!_])", "[0->1][2->4][5->6]"}, - {"blocks_lat_sub", u"ₐₑaeꬱ", "[0->4]"}, - {"blocks_lat_smallcap", u"ꟺM", "[0->1]"}, - {"blocks_lat_small_letter", u"ᶓᶍᶓᴔᴟ", "[0->4]"}, - {"blocks_lat_acc", u"eéěĕȩɇḕẻếⱻꞫ", "[0->10]"}, - {"blocks_com", u"⟦ℳ¥¾⟾⁸⟧Ⓔ", "[0][1][2->3][4][5][6][7]"}, + {"blocks_lat", L"aɒɠƉĚÑ", "[0->5]"}, + {"blocks_lat_paren", L"([_!_])", "[0->1][2->4][5->6]"}, + {"blocks_lat_sub", L"ₐₑaeꬱ", "[0->4]"}, + {"blocks_lat_smallcap", L"ꟺM", "[0->1]"}, + {"blocks_lat_small_letter", L"ᶓᶍᶓᴔᴟ", "[0->4]"}, + {"blocks_lat_acc", L"eéěĕȩɇḕẻếⱻꞫ", "[0->10]"}, + {"blocks_com", L"⟦ℳ¥¾⟾⁸⟧Ⓔ", "[0][1][2->3][4][5][6][7]"}, // Latin script. - {"latin_numbers", u"a1b2c3", "[0][1][2][3][4][5]"}, - {"latin_puncts1", u"a,b,c.", "[0][1][2][3][4][5]"}, - {"latin_puncts2", u"aa,bb,cc!!", "[0->1][2][3->4][5][6->7][8->9]"}, - {"latin_diac_multi", u"a\u0300e\u0352i", "[0->4]"}, + {"latin_numbers", L"a1b2c3", "[0][1][2][3][4][5]"}, + {"latin_puncts1", L"a,b,c.", "[0][1][2][3][4][5]"}, + {"latin_puncts2", L"aa,bb,cc!!", "[0->1][2][3->4][5][6->7][8->9]"}, + {"latin_diac_multi", L"a\u0300e\u0352i", "[0->4]"}, // Common script. - {"common_tm", u"•bug™", "[0][1->3][4]"}, - {"common_copyright", u"chromium©", "[0->7][8]"}, - {"common_math1", u"ℳ: ¬ƒ(x)=½×¾", "[0][1][2][3][4][5][6][7][8][9->11]"}, - {"common_math2", u"𝟏×𝟑", "[0->1][2][3->4]"}, - {"common_numbers", u"🄀𝟭𝟐⒓¹²", "[0->1][2->5][6][7->8]"}, - {"common_puncts", u",.\u0083!", "[0->1][2][3]"}, + {"common_tm", L"•bug™", "[0][1->3][4]"}, + {"common_copyright", L"chromium©", "[0->7][8]"}, + {"common_math1", L"ℳ: ¬ƒ(x)=½×¾", "[0][1][2][3][4][5][6][7][8][9->11]"}, + {"common_math2", L"𝟏×𝟑", "[0->1][2][3->4]"}, + {"common_numbers", L"🄀𝟭𝟐⒓¹²", "[0->1][2->5][6][7->8]"}, + {"common_puncts", L",.\u0083!", "[0->1][2][3]"}, // Arabic script. - {"arabic", u"\u0633\u069b\u0763\u077f\u08A2\uFB53", "[5<-0]"}, - {"arabic_lat", u"\u0633\u069b\u0763\u077f\u08A2\uFB53abc", "[6->8][5<-0]"}, - {"arabic_word_ligatures", u"\uFDFD\uFDF3", "[1<-0]"}, - {"arabic_diac", u"\u069D\u0300", "[1<-0]"}, - {"arabic_diac_lat", u"\u069D\u0300abc", "[2->4][1<-0]"}, - {"arabic_diac_lat2", u"abc\u069D\u0300abc", "[0->2][4<-3][5->7]"}, - {"arabic_lyd", u"\U00010935\U00010930\u06B0\u06B1", "[5<-4][3<-0]"}, - {"arabic_numbers", u"12\u06D034", "[3->4][2][0->1]"}, - {"arabic_letters", u"ab\u06D0cd", "[0->1][2][3->4]"}, - {"arabic_mixed", u"a1\u06D02d", "[0][1][3][2][4]"}, - {"arabic_coptic1", u"\u06D0\U000102E2\u2CB2", "[1->3][0]"}, - {"arabic_coptic2", u"\u2CB2\U000102E2\u06D0", "[0->2][3]"}, + {"arabic", L"\u0633\u069b\u0763\u077f\u08A2\uFB53", "[5<-0]"}, + {"arabic_lat", L"\u0633\u069b\u0763\u077f\u08A2\uFB53abc", "[6->8][5<-0]"}, + {"arabic_word_ligatures", L"\uFDFD\uFDF3", "[1<-0]"}, + {"arabic_diac", L"\u069D\u0300", "[1<-0]"}, + {"arabic_diac_lat", L"\u069D\u0300abc", "[2->4][1<-0]"}, + {"arabic_diac_lat2", L"abc\u069D\u0300abc", "[0->2][4<-3][5->7]"}, + {"arabic_lyd", L"\U00010935\U00010930\u06B0\u06B1", "[5<-4][3<-0]"}, + {"arabic_numbers", L"12\u06D034", "[3->4][2][0->1]"}, + {"arabic_letters", L"ab\u06D0cd", "[0->1][2][3->4]"}, + {"arabic_mixed", L"a1\u06D02d", "[0][1][3][2][4]"}, + {"arabic_coptic1", L"\u06D0\U000102E2\u2CB2", "[1->3][0]"}, + {"arabic_coptic2", L"\u2CB2\U000102E2\u06D0", "[0->2][3]"}, // Devanagari script. - {"devanagari1", u"ञटठडढणतथ", "[0->7]"}, - {"devanagari2", u"ढ꣸ꣴ", "[0->2]"}, - {"devanagari_vowels", u"\u0915\u093F\u0915\u094C", "[0->3]"}, - {"devanagari_consonants", u"\u0915\u094D\u0937", "[0->2]"}, + {"devanagari1", L"ञटठडढणतथ", "[0->7]"}, + {"devanagari2", L"ढ꣸ꣴ", "[0->2]"}, + {"devanagari_vowels", L"\u0915\u093F\u0915\u094C", "[0->3]"}, + {"devanagari_consonants", L"\u0915\u094D\u0937", "[0->2]"}, // Ethiopic script. - {"ethiopic", u"መጩጪᎅⶹⶼꬣꬦ", "[0->7]"}, - {"ethiopic_numbers", u"1ቨቤ2", "[0][1->2][3]"}, - {"ethiopic_mixed1", u"abቨቤ12", "[0->1][2->3][4->5]"}, - {"ethiopic_mixed2", u"a1ቨቤb2", "[0][1][2->3][4][5]"}, + {"ethiopic", L"መጩጪᎅⶹⶼꬣꬦ", "[0->7]"}, + {"ethiopic_numbers", L"1ቨቤ2", "[0][1->2][3]"}, + {"ethiopic_mixed1", L"abቨቤ12", "[0->1][2->3][4->5]"}, + {"ethiopic_mixed2", L"a1ቨቤb2", "[0][1][2->3][4][5]"}, // Georgian script. - {"georgian1", u"ႼႽႾႿჀჁჂჳჴჵ", "[0->9]"}, - {"georgian2", u"ლⴊⴅ", "[0->2]"}, - {"georgian_numbers", u"1ლⴊⴅ2", "[0][1->3][4]"}, - {"georgian_mixed", u"a1ლⴊⴅb2", "[0][1][2->4][5][6]"}, + {"georgian1", L"ႼႽႾႿჀჁჂჳჴჵ", "[0->9]"}, + {"georgian2", L"ლⴊⴅ", "[0->2]"}, + {"georgian_numbers", L"1ლⴊⴅ2", "[0][1->3][4]"}, + {"georgian_mixed", L"a1ლⴊⴅb2", "[0][1][2->4][5][6]"}, // Telugu script. - {"telugu_lat", u"aaఉయ!", "[0->1][2->3][4]"}, - {"telugu_numbers", u"123౦౧౨456౩౪౫", "[0->2][3->5][6->8][9->11]"}, - {"telugu_puncts", u"కురుచ, చిఱుత, చేరువ, చెఱువు!", + {"telugu_lat", L"aaఉయ!", "[0->1][2->3][4]"}, + {"telugu_numbers", L"123౦౧౨456౩౪౫", "[0->2][3->5][6->8][9->11]"}, + {"telugu_puncts", L"కురుచ, చిఱుత, చేరువ, చెఱువు!", "[0->4][5][6][7->11][12][13][14->18][19][20][21->26][27]"}, // Control Pictures. - {"control_pictures", u"␑␒␓␔␕␖␗␘␙␚␛", "[0->10]"}, - {"control_pictures_rewrite", u"␑\t␛", "[0->2]"}, + {"control_pictures", L"␑␒␓␔␕␖␗␘␙␚␛", "[0->10]"}, + {"control_pictures_rewrite", L"␑\t␛", "[0->2]"}, // Unicode art. - {"unicode_emoticon1", u"(▀̿ĺ̯▀̿ ̿)", "[0][1->2][3->4][5->6][7->8][9]"}, - {"unicode_emoticon2", u"▀̿̿Ĺ̯̿▀̿ ", "[0->2][3->5][6->7][8]"}, - {"unicode_emoticon3", u"( ͡° ͜ʖ ͡°)", "[0][1->2][3][4->5][6][7->8][9][10]"}, - {"unicode_emoticon4", u"✩·͙*̩̩͙˚̩̥̩̥( ͡ᵔ ͜ʖ ͡ᵔ )*̩̩͙✩·͙˚̩̥̩̥.", + {"unicode_emoticon1", L"(▀̿ĺ̯▀̿ ̿)", "[0][1->2][3->4][5->6][7->8][9]"}, + {"unicode_emoticon2", L"▀̿̿Ĺ̯̿▀̿ ", "[0->2][3->5][6->7][8]"}, + {"unicode_emoticon3", L"( ͡° ͜ʖ ͡°)", "[0][1->2][3][4->5][6][7->8][9][10]"}, + {"unicode_emoticon4", L"✩·͙*̩̩͙˚̩̥̩̥( ͡ᵔ ͜ʖ ͡ᵔ )*̩̩͙✩·͙˚̩̥̩̥.", "[0][1->2][3->6][7->11][12][13->14][15][16->17][18][19->20][21][22][23][" "24->27][28][29->30][31->35][36]"}, - {"unicode_emoticon5", u"ヽ(͡◕ ͜ʖ ͡◕)ノ", + {"unicode_emoticon5", L"ヽ(͡◕ ͜ʖ ͡◕)ノ", "[0][1->2][3][4->5][6][7->8][9][10][11]"}, - {"unicode_art1", u"꧁༒✧ Great ✧༒꧂", "[0][1][2][3][4->8][9][10][11][12]"}, - {"unicode_art2", u"t͎e͎s͎t͎", "[0->7]"}, + {"unicode_art1", L"꧁༒✧ Great ✧༒꧂", "[0][1][2][3][4->8][9][10][11][12]"}, + {"unicode_art2", L"t͎e͎s͎t͎", "[0->7]"}, // Combining diacritical sequences. - {"unicode_diac1", u"\u2123\u0336", "[0->1]"}, - {"unicode_diac2", u"\u273c\u0325", "[0->1]"}, - {"unicode_diac3", u"\u2580\u033f", "[0->1]"}, - {"unicode_diac4", u"\u2022\u0325\u0329", "[0->2]"}, - {"unicode_diac5", u"\u2022\u0325", "[0->1]"}, - {"unicode_diac6", u"\u00b7\u0359\u0325", "[0->2]"}, - {"unicode_diac7", u"\u2027\u0329\u0325", "[0->2]"}, - {"unicode_diac8", u"\u0332\u0305\u03c1", "[0->1][2]"}, + {"unicode_diac1", L"\u2123\u0336", "[0->1]"}, + {"unicode_diac2", L"\u273c\u0325", "[0->1]"}, + {"unicode_diac3", L"\u2580\u033f", "[0->1]"}, + {"unicode_diac4", L"\u2022\u0325\u0329", "[0->2]"}, + {"unicode_diac5", L"\u2022\u0325", "[0->1]"}, + {"unicode_diac6", L"\u00b7\u0359\u0325", "[0->2]"}, + {"unicode_diac7", L"\u2027\u0329\u0325", "[0->2]"}, + {"unicode_diac8", L"\u0332\u0305\u03c1", "[0->1][2]"}, }; INSTANTIATE_TEST_SUITE_P(ItemizeTextToRunsScripts, @@ -1779,96 +1797,96 @@ const RunListCase kEmojiRunListCases[] = { // Samples from // https://www.unicode.org/Public/emoji/12.0/emoji-data.txt - {"number_sign", u"\u0023", "[0]"}, - {"keyboard", u"\u2328", "[0]"}, - {"aries", u"\u2648", "[0]"}, - {"candle", u"\U0001F56F", "[0->1]"}, - {"anchor", u"\u2693", "[0]"}, - {"grinning_face", u"\U0001F600", "[0->1]"}, - {"face_with_monocle", u"\U0001F9D0", "[0->1]"}, - {"light_skin_tone", u"\U0001F3FB", "[0->1]"}, - {"index_pointing_up", u"\u261D", "[0]"}, - {"horse_racing", u"\U0001F3C7", "[0->1]"}, - {"kiss", u"\U0001F48F", "[0->1]"}, - {"couple_with_heart", u"\U0001F491", "[0->1]"}, - {"people_wrestling", u"\U0001F93C", "[0->1]"}, - {"eject_button", u"\u23CF", "[0]"}, + {"number_sign", L"\u0023", "[0]"}, + {"keyboard", L"\u2328", "[0]"}, + {"aries", L"\u2648", "[0]"}, + {"candle", L"\U0001F56F", "[0->1]"}, + {"anchor", L"\u2693", "[0]"}, + {"grinning_face", L"\U0001F600", "[0->1]"}, + {"face_with_monocle", L"\U0001F9D0", "[0->1]"}, + {"light_skin_tone", L"\U0001F3FB", "[0->1]"}, + {"index_pointing_up", L"\u261D", "[0]"}, + {"horse_racing", L"\U0001F3C7", "[0->1]"}, + {"kiss", L"\U0001F48F", "[0->1]"}, + {"couple_with_heart", L"\U0001F491", "[0->1]"}, + {"people_wrestling", L"\U0001F93C", "[0->1]"}, + {"eject_button", L"\u23CF", "[0]"}, // Samples from // https://unicode.org/Public/emoji/12.0/emoji-sequences.txt - {"watch", u"\u231A", "[0]"}, - {"cross_mark", u"\u274C", "[0]"}, - {"copyright", u"\u00A9\uFE0F", "[0->1]"}, - {"stop_button", u"\u23F9\uFE0F", "[0->1]"}, - {"passenger_ship", u"\U0001F6F3\uFE0F", "[0->2]"}, - {"keycap_star", u"\u002A\uFE0F\u20E3", "[0->2]"}, - {"keycap_6", u"\u0036\uFE0F\u20E3", "[0->2]"}, - {"flag_andorra", u"\U0001F1E6\U0001F1E9", "[0->3]"}, - {"flag_egypt", u"\U0001F1EA\U0001F1EC", "[0->3]"}, + {"watch", L"\u231A", "[0]"}, + {"cross_mark", L"\u274C", "[0]"}, + {"copyright", L"\u00A9\uFE0F", "[0->1]"}, + {"stop_button", L"\u23F9\uFE0F", "[0->1]"}, + {"passenger_ship", L"\U0001F6F3\uFE0F", "[0->2]"}, + {"keycap_star", L"\u002A\uFE0F\u20E3", "[0->2]"}, + {"keycap_6", L"\u0036\uFE0F\u20E3", "[0->2]"}, + {"flag_andorra", L"\U0001F1E6\U0001F1E9", "[0->3]"}, + {"flag_egypt", L"\U0001F1EA\U0001F1EC", "[0->3]"}, {"flag_england", - u"\U0001F3F4\U000E0067\U000E0062\U000E0065\U000E006E\U000E0067\U000E007F", + L"\U0001F3F4\U000E0067\U000E0062\U000E0065\U000E006E\U000E0067\U000E007F", "[0->13]"}, - {"index_up_light", u"\u261D\U0001F3FB", "[0->2]"}, - {"person_bouncing_ball_light", u"\u26F9\U0001F3FC", "[0->2]"}, - {"victory_hand_med_light", u"\u270C\U0001F3FC", "[0->2]"}, - {"horse_racing_med_dark", u"\U0001F3C7\U0001F3FE", "[0->3]"}, - {"woman_man_hands_light", u"\U0001F46B\U0001F3FB", "[0->3]"}, - {"person_haircut_med_light", u"\U0001F487\U0001F3FC", "[0->3]"}, - {"pinching_hand_light", u"\U0001F90F\U0001F3FB", "[0->3]"}, - {"love_you_light", u"\U0001F91F\U0001F3FB", "[0->3]"}, - {"leg_dark", u"\U0001F9B5\U0001F3FF", "[0->3]"}, + {"index_up_light", L"\u261D\U0001F3FB", "[0->2]"}, + {"person_bouncing_ball_light", L"\u26F9\U0001F3FC", "[0->2]"}, + {"victory_hand_med_light", L"\u270C\U0001F3FC", "[0->2]"}, + {"horse_racing_med_dark", L"\U0001F3C7\U0001F3FE", "[0->3]"}, + {"woman_man_hands_light", L"\U0001F46B\U0001F3FB", "[0->3]"}, + {"person_haircut_med_light", L"\U0001F487\U0001F3FC", "[0->3]"}, + {"pinching_hand_light", L"\U0001F90F\U0001F3FB", "[0->3]"}, + {"love_you_light", L"\U0001F91F\U0001F3FB", "[0->3]"}, + {"leg_dark", L"\U0001F9B5\U0001F3FF", "[0->3]"}, // Samples from // https://unicode.org/Public/emoji/12.0/emoji-variation-sequences.txt - {"number_sign_text", u"\u0023\uFE0E", "[0->1]"}, - {"number_sign_emoji", u"\u0023\uFE0F", "[0->1]"}, - {"digit_eight_text", u"\u0038\uFE0E", "[0->1]"}, - {"digit_eight_emoji", u"\u0038\uFE0F", "[0->1]"}, - {"up_down_arrow_text", u"\u2195\uFE0E", "[0->1]"}, - {"up_down_arrow_emoji", u"\u2195\uFE0F", "[0->1]"}, - {"stopwatch_text", u"\u23F1\uFE0E", "[0->1]"}, - {"stopwatch_emoji", u"\u23F1\uFE0F", "[0->1]"}, - {"thermometer_text", u"\U0001F321\uFE0E", "[0->2]"}, - {"thermometer_emoji", u"\U0001F321\uFE0F", "[0->2]"}, - {"thumbs_up_text", u"\U0001F44D\uFE0E", "[0->2]"}, - {"thumbs_up_emoji", u"\U0001F44D\uFE0F", "[0->2]"}, - {"hole_text", u"\U0001F573\uFE0E", "[0->2]"}, - {"hole_emoji", u"\U0001F573\uFE0F", "[0->2]"}, + {"number_sign_text", L"\u0023\uFE0E", "[0->1]"}, + {"number_sign_emoji", L"\u0023\uFE0F", "[0->1]"}, + {"digit_eight_text", L"\u0038\uFE0E", "[0->1]"}, + {"digit_eight_emoji", L"\u0038\uFE0F", "[0->1]"}, + {"up_down_arrow_text", L"\u2195\uFE0E", "[0->1]"}, + {"up_down_arrow_emoji", L"\u2195\uFE0F", "[0->1]"}, + {"stopwatch_text", L"\u23F1\uFE0E", "[0->1]"}, + {"stopwatch_emoji", L"\u23F1\uFE0F", "[0->1]"}, + {"thermometer_text", L"\U0001F321\uFE0E", "[0->2]"}, + {"thermometer_emoji", L"\U0001F321\uFE0F", "[0->2]"}, + {"thumbs_up_text", L"\U0001F44D\uFE0E", "[0->2]"}, + {"thumbs_up_emoji", L"\U0001F44D\uFE0F", "[0->2]"}, + {"hole_text", L"\U0001F573\uFE0E", "[0->2]"}, + {"hole_emoji", L"\U0001F573\uFE0F", "[0->2]"}, // Samples from // https://unicode.org/Public/emoji/12.0/emoji-zwj-sequences.txt - {"couple_man_man", u"\U0001F468\u200D\u2764\uFE0F\u200D\U0001F468", + {"couple_man_man", L"\U0001F468\u200D\u2764\uFE0F\u200D\U0001F468", "[0->7]"}, {"kiss_man_man", - u"\U0001F468\u200D\u2764\uFE0F\u200D\U0001F48B\u200D\U0001F468", + L"\U0001F468\u200D\u2764\uFE0F\u200D\U0001F48B\u200D\U0001F468", "[0->10]"}, {"family_man_woman_girl_boy", - u"\U0001F468\u200D\U0001F469\u200D\U0001F467\u200D\U0001F466", "[0->10]"}, + L"\U0001F468\u200D\U0001F469\u200D\U0001F467\u200D\U0001F466", "[0->10]"}, {"men_hands_dark_medium", - u"\U0001F468\U0001F3FF\u200D\U0001F91D\u200D\U0001F468\U0001F3FD", + L"\U0001F468\U0001F3FF\u200D\U0001F91D\u200D\U0001F468\U0001F3FD", "[0->11]"}, {"people_hands_dark", - u"\U0001F9D1\U0001F3FF\u200D\U0001F91D\u200D\U0001F9D1\U0001F3FF", + L"\U0001F9D1\U0001F3FF\u200D\U0001F91D\u200D\U0001F9D1\U0001F3FF", "[0->11]"}, - {"man_pilot", u"\U0001F468\u200D\u2708\uFE0F", "[0->4]"}, - {"man_scientist", u"\U0001F468\u200D\U0001F52C", "[0->4]"}, - {"man_mechanic_light", u"\U0001F468\U0001F3FB\u200D\U0001F527", "[0->6]"}, - {"man_judge_medium", u"\U0001F468\U0001F3FD\u200D\u2696\uFE0F", "[0->6]"}, - {"woman_cane_dark", u"\U0001F469\U0001F3FF\u200D\U0001F9AF", "[0->6]"}, - {"woman_ball_light", u"\u26F9\U0001F3FB\u200D\u2640\uFE0F", "[0->5]"}, - {"woman_running", u"\U0001F3C3\u200D\u2640\uFE0F", "[0->4]"}, - {"woman_running_dark", u"\U0001F3C3\U0001F3FF\u200D\u2640\uFE0F", "[0->6]"}, - {"woman_turban", u"\U0001F473\u200D\u2640\uFE0F", "[0->4]"}, - {"woman_detective", u"\U0001F575\uFE0F\u200D\u2640\uFE0F", "[0->5]"}, - {"man_facepalming", u"\U0001F926\u200D\u2642\uFE0F", "[0->4]"}, - {"man_red_hair", u"\U0001F468\u200D\U0001F9B0", "[0->4]"}, - {"man_medium_curly", u"\U0001F468\U0001F3FD\u200D\U0001F9B1", "[0->6]"}, - {"woman_dark_white_hair", u"\U0001F469\U0001F3FF\u200D\U0001F9B3", + {"man_pilot", L"\U0001F468\u200D\u2708\uFE0F", "[0->4]"}, + {"man_scientist", L"\U0001F468\u200D\U0001F52C", "[0->4]"}, + {"man_mechanic_light", L"\U0001F468\U0001F3FB\u200D\U0001F527", "[0->6]"}, + {"man_judge_medium", L"\U0001F468\U0001F3FD\u200D\u2696\uFE0F", "[0->6]"}, + {"woman_cane_dark", L"\U0001F469\U0001F3FF\u200D\U0001F9AF", "[0->6]"}, + {"woman_ball_light", L"\u26F9\U0001F3FB\u200D\u2640\uFE0F", "[0->5]"}, + {"woman_running", L"\U0001F3C3\u200D\u2640\uFE0F", "[0->4]"}, + {"woman_running_dark", L"\U0001F3C3\U0001F3FF\u200D\u2640\uFE0F", "[0->6]"}, + {"woman_turban", L"\U0001F473\u200D\u2640\uFE0F", "[0->4]"}, + {"woman_detective", L"\U0001F575\uFE0F\u200D\u2640\uFE0F", "[0->5]"}, + {"man_facepalming", L"\U0001F926\u200D\u2642\uFE0F", "[0->4]"}, + {"man_red_hair", L"\U0001F468\u200D\U0001F9B0", "[0->4]"}, + {"man_medium_curly", L"\U0001F468\U0001F3FD\u200D\U0001F9B1", "[0->6]"}, + {"woman_dark_white_hair", L"\U0001F469\U0001F3FF\u200D\U0001F9B3", "[0->6]"}, - {"rainbow_flag", u"\U0001F3F3\uFE0F\u200D\U0001F308", "[0->5]"}, - {"pirate_flag", u"\U0001F3F4\u200D\u2620\uFE0F", "[0->4]"}, - {"service_dog", u"\U0001F415\u200D\U0001F9BA", "[0->4]"}, - {"eye_bubble", u"\U0001F441\uFE0F\u200D\U0001F5E8\uFE0F", "[0->6]"}, + {"rainbow_flag", L"\U0001F3F3\uFE0F\u200D\U0001F308", "[0->5]"}, + {"pirate_flag", L"\U0001F3F4\u200D\u2620\uFE0F", "[0->4]"}, + {"service_dog", L"\U0001F415\u200D\U0001F9BA", "[0->4]"}, + {"eye_bubble", L"\U0001F441\uFE0F\u200D\U0001F5E8\uFE0F", "[0->6]"}, }; INSTANTIATE_TEST_SUITE_P(ItemizeTextToRunsEmoji, @@ -1885,12 +1903,12 @@ struct ElideTextCase { const char* test_name; - const char16_t* text; - const char16_t* display_text; + const wchar_t* text; + const wchar_t* display_text; // The available width, specified as a number of fixed-width glyphs. If no // value is specified, the width of the resulting |display_text| is used. This // helps test available widths larger than the resulting test; e.g. "a b" - // should yield "a…" even if 3 glyph widths are available, when + // should yield "a\u2026" even if 3 glyph widths are available, when // whitespace elision is enabled. const base::Optional<size_t> available_width_as_glyph_count = base::nullopt; const base::Optional<bool> whitespace_elision = base::nullopt; @@ -1915,8 +1933,8 @@ const ElideTextTestOptions options = std::get<0>(GetParam()); const ElideTextCase param = std::get<1>(GetParam()); - const std::u16string text = param.text; - const std::u16string display_text = param.display_text; + const std::u16string text = WideToUTF16(param.text); + const std::u16string display_text = WideToUTF16(param.display_text); // Retrieve the display_text width without eliding. RenderTextHarfBuzz* render_text = GetRenderText(); @@ -1952,64 +1970,68 @@ } const ElideTextCase kElideHeadTextCases[] = { - {"empty", u"", u""}, - {"letter_m_tail0", u"M", u""}, - {"letter_m_tail1", u"M", u"M"}, - {"no_eliding", u"012ab", u"012ab"}, - {"ltr_3", u"abc", u"abc"}, - {"ltr_2", u"abc", u"…c"}, - {"ltr_1", u"abc", u"…"}, - {"ltr_0", u"abc", u""}, - {"rtl_3", u"אבג", u"אבג"}, - {"rtl_2", u"אבג", u"…ג"}, - {"rtl_1", u"אבג", u"…"}, - {"rtl_0", u"אבג", u""}, - {"ltr_rtl_5", u"abcאבג", u"…cאבג"}, - {"ltr_rtl_4", u"abcאבג", u"…אבג"}, - {"ltr_rtl_3", u"abcאבג", u"…בג"}, - {"rtl_ltr_5", u"אבגabc", u"…גabc"}, - {"rtl_ltr_4", u"אבגabc", u"…abc"}, - {"rtl_ltr_3", u"אבגabc", u"…bc"}, - {"bidi_1", u"aבbבc012", u"…bבc012"}, - {"bidi_2", u"aבbבc012", u"…בc012"}, - {"bidi_3", u"aבbבc012", u"…c012"}, + {"empty", L"", L""}, + {"letter_m_tail0", L"M", L""}, + {"letter_m_tail1", L"M", L"M"}, + {"no_eliding", L"012ab", L"012ab"}, + {"ltr_3", L"abc", L"abc"}, + {"ltr_2", L"abc", L"\u2026c"}, + {"ltr_1", L"abc", L"\u2026"}, + {"ltr_0", L"abc", L""}, + {"rtl_3", L"\u05d0\u05d1\u05d2", L"\u05d0\u05d1\u05d2"}, + {"rtl_2", L"\u05d0\u05d1\u05d2", L"\u2026\u05d2"}, + {"rtl_1", L"\u05d0\u05d1\u05d2", L"\u2026"}, + {"rtl_0", L"\u05d0\u05d1\u05d2", L""}, + {"ltr_rtl_5", L"abc\u05d0\u05d1\u05d2", L"\u2026c\u05d0\u05d1\u05d2"}, + {"ltr_rtl_4", L"abc\u05d0\u05d1\u05d2", L"\u2026\u05d0\u05d1\u05d2"}, + {"ltr_rtl_3", L"abc\u05d0\u05d1\u05d2", L"\u2026\u05d1\u05d2"}, + {"rtl_ltr_5", L"\u05d0\u05d1\u05d2abc", L"\u2026\u05d2abc"}, + {"rtl_ltr_4", L"\u05d0\u05d1\u05d2abc", L"\u2026abc"}, + {"rtl_ltr_3", L"\u05d0\u05d1\u05d2abc", L"\u2026bc"}, + {"bidi_1", L"a\u05d1b\u05d1c012", L"\u2026b\u05d1c012"}, + {"bidi_2", L"a\u05d1b\u05d1c012", L"\u2026\u05d1c012"}, + {"bidi_3", L"a\u05d1b\u05d1c012", L"\u2026c012"}, // Test surrogate pairs. No surrogate pair should be partially elided. - {"surrogate1", u"abc\U0001D11E\U0001D122x", u"…\U0001D11E\U0001D122x"}, - {"surrogate2", u"abc\U0001D11E\U0001D122x", u"…\U0001D122x"}, - {"surrogate3", u"abc\U0001D11E\U0001D122x", u"…x"}, + {"surrogate1", L"abc\U0001D11E\U0001D122x", L"\u2026\U0001D11E\U0001D122x"}, + {"surrogate2", L"abc\U0001D11E\U0001D122x", L"\u2026\U0001D122x"}, + {"surrogate3", L"abc\U0001D11E\U0001D122x", L"\u2026x"}, // Test combining character sequences. U+0915 U+093F forms a compound // glyph, as does U+0915 U+0942. No combining sequence should be partially // elided. - {"combining1", u"0123\u0915\u093f\u0915\u0942456", u"…\u0915\u0942456"}, - {"combining2", u"0123\u0915\u093f\u0915\u0942456", u"…456"}, + {"combining1", L"0123\u0915\u093f\u0915\u0942456", + L"\u2026\u0915\u0942456"}, + {"combining2", L"0123\u0915\u093f\u0915\u0942456", L"\u2026456"}, // 𝄞 (U+1D11E, MUSICAL SYMBOL G CLEF) should be fully elided. - {"emoji1", u"012\U0001D11Ex", u"…\U0001D11Ex"}, - {"emoji2", u"012\U0001D11Ex", u"…x"}, + {"emoji1", L"012\U0001D11Ex", L"\u2026\U0001D11Ex"}, + {"emoji2", L"012\U0001D11Ex", L"\u2026x"}, // Whitespace elision tests. - {"empty_no_elision", u"", u"", 0, kForceNoWhitespaceElision}, - {"empty_elision", u"", u"", 0, kForceWhitespaceElision}, - {"xyz_no_elision", u" x xyz", u"… xyz", 5, kForceNoWhitespaceElision}, - {"xyz_elision", u" x xyz", u"…xyz", 5, kForceWhitespaceElision}, - {"ltr_rtl_elision3", u"x ב y ג", u"…ג", 3, kForceWhitespaceElision}, - {"ltr_rtl_elision6", u"x ב y ג", u"…ג", 6, kForceWhitespaceElision}, - {"ltr_rtl_elision7", u"x ב y ג", u"…y ג", 7, + {"empty_no_elision", L"", L"", 0, kForceNoWhitespaceElision}, + {"empty_elision", L"", L"", 0, kForceWhitespaceElision}, + {"xyz_no_elision", L" x xyz", L"\u2026 xyz", 5, + kForceNoWhitespaceElision}, + {"xyz_elision", L" x xyz", L"\u2026xyz", 5, kForceWhitespaceElision}, + {"ltr_rtl_elision3", L"x \u05d1 y \u05d2", L"\u2026\u05d2", 3, kForceWhitespaceElision}, - {"ltr_rtl_elision10", u"x ב y ג", u"…ב y ג", 10, + {"ltr_rtl_elision6", L"x \u05d1 y \u05d2", L"\u2026\u05d2", 6, kForceWhitespaceElision}, - {"ltr_rtl_elision11", u"x ב y ג", u"…ב y ג", 11, + {"ltr_rtl_elision7", L"x \u05d1 y \u05d2", L"\u2026y \u05d2", 7, kForceWhitespaceElision}, + {"ltr_rtl_elision10", L"x \u05d1 y \u05d2", + L"\u2026\u05d1 y \u05d2", 10, kForceWhitespaceElision}, + {"ltr_rtl_elision11", L"x \u05d1 y \u05d2", + L"\u2026\u05d1 y \u05d2", 11, kForceWhitespaceElision}, // Emoji U+1F601 and emoji U+1F321 U+FE0E are graphemes that result in // one glyph each. Eliding a glyph must remove the whole grapheme. It is // invalid to break a grapheme in pieces. - {"graphemes_elision3", u" \U0001F601 \U0001F321\uFE0E ", u"…", 3, + {"graphemes_elision3", L" \U0001F601 \U0001F321\uFE0E ", L"\u2026", 3, kForceWhitespaceElision}, - {"graphemes_elision4", u" \U0001F601 \U0001F321\uFE0E ", - u"…\U0001F321\uFE0E ", 4, kForceWhitespaceElision}, - {"graphemes_elision6", u" \U0001F601 \U0001F321\uFE0E ", - u"…\U0001F321\uFE0E ", 6, kForceWhitespaceElision}, - {"graphemes_elision7", u" \U0001F601 \U0001F321\uFE0E ", - u"…\U0001F601 \U0001F321\uFE0E ", 7, kForceWhitespaceElision}, + {"graphemes_elision4", L" \U0001F601 \U0001F321\uFE0E ", + L"\u2026\U0001F321\uFE0E ", 4, kForceWhitespaceElision}, + {"graphemes_elision6", L" \U0001F601 \U0001F321\uFE0E ", + L"\u2026\U0001F321\uFE0E ", 6, kForceWhitespaceElision}, + {"graphemes_elision7", L" \U0001F601 \U0001F321\uFE0E ", + L"\u2026\U0001F601 \U0001F321\uFE0E ", 7, kForceWhitespaceElision}, }; INSTANTIATE_TEST_SUITE_P( @@ -2020,71 +2042,75 @@ RenderTextTestWithElideTextCase::ParamInfoToString); const ElideTextCase kElideTailTextCases[] = { - {"empty", u"", u""}, - {"letter_m_tail0", u"M", u""}, - {"letter_m_tail1", u"M", u"M"}, - {"letter_weak_3", u" . ", u" . "}, - {"letter_weak_2", u" . ", u"…"}, - {"no_eliding", u"012ab", u"012ab"}, - {"ltr_3", u"abc", u"abc"}, - {"ltr_2", u"abc", u"a…"}, - {"ltr_1", u"abc", u"…"}, - {"ltr_0", u"abc", u""}, - {"rtl_3", u"אבג", u"אבג"}, - {"rtl_2", u"אבג", u"א…"}, - {"rtl_1", u"אבג", u"…"}, - {"rtl_0", u"אבג", u""}, - {"ltr_rtl_5", u"abcאבג", u"abcא…\u200F"}, - {"ltr_rtl_4", u"abcאבג", u"abc…"}, - {"ltr_rtl_3", u"abcאבג", u"ab…"}, - {"rtl_ltr_5", u"אבגabc", u"אבגa…\u200E"}, - {"rtl_ltr_4", u"אבגabc", u"אבג…"}, - {"rtl_ltr_3", u"אבגabc", u"אב…"}, - {"bidi_1", u"012aבbבc", u"012a…"}, - {"bidi_2", u"012aבbבc", u"012aב…\u200F"}, - {"bidi_3", u"012aבbבc", u"012aבb…"}, + {"empty", L"", L""}, + {"letter_m_tail0", L"M", L""}, + {"letter_m_tail1", L"M", L"M"}, + {"letter_weak_3", L" . ", L" . "}, + {"letter_weak_2", L" . ", L"\u2026"}, + {"no_eliding", L"012ab", L"012ab"}, + {"ltr_3", L"abc", L"abc"}, + {"ltr_2", L"abc", L"a\u2026"}, + {"ltr_1", L"abc", L"\u2026"}, + {"ltr_0", L"abc", L""}, + {"rtl_3", L"\u05d0\u05d1\u05d2", L"\u05d0\u05d1\u05d2"}, + {"rtl_2", L"\u05d0\u05d1\u05d2", L"\u05d0\u2026"}, + {"rtl_1", L"\u05d0\u05d1\u05d2", L"\u2026"}, + {"rtl_0", L"\u05d0\u05d1\u05d2", L""}, + {"ltr_rtl_5", L"abc\u05d0\u05d1\u05d2", L"abc\u05d0\u2026\u200F"}, + {"ltr_rtl_4", L"abc\u05d0\u05d1\u05d2", L"abc\u2026"}, + {"ltr_rtl_3", L"abc\u05d0\u05d1\u05d2", L"ab\u2026"}, + {"rtl_ltr_5", L"\u05d0\u05d1\u05d2abc", L"\u05d0\u05d1\u05d2a\u2026\u200E"}, + {"rtl_ltr_4", L"\u05d0\u05d1\u05d2abc", L"\u05d0\u05d1\u05d2\u2026"}, + {"rtl_ltr_3", L"\u05d0\u05d1\u05d2abc", L"\u05d0\u05d1\u2026"}, + {"bidi_1", L"012a\u05d1b\u05d1c", L"012a\u2026"}, + {"bidi_2", L"012a\u05d1b\u05d1c", L"012a\u05d1\u2026\u200F"}, + {"bidi_3", L"012a\u05d1b\u05d1c", L"012a\u05d1b\u2026"}, // No RLM marker added as digits (012) have weak directionality. - {"no_rlm", u"01אבג", u"01א…"}, + {"no_rlm", L"01\u05d0\u05d1\u05d2", L"01\u05d0\u2026"}, // RLM marker added as "ab" have strong LTR directionality. - {"with_rlm", u"abאבגcd", u"abאב…\u200f"}, + {"with_rlm", L"ab\u05d0\u05d1\u05d2cd", L"ab\u05d0\u05d1\u2026\u200f"}, // Test surrogate pairs. The first pair 𝄞 'MUSICAL SYMBOL G CLEF' U+1D11E // should be kept, and the second pair 𝄢 'MUSICAL SYMBOL F CLEF' U+1D122 // should be removed. No surrogate pair should be partially elided. - {"surrogate", u"0123\U0001D11E\U0001D122x", u"0123\U0001D11E…"}, + {"surrogate", L"0123\U0001D11E\U0001D122x", L"0123\U0001D11E\u2026"}, // Test combining character sequences. U+0915 U+093F forms a compound // glyph, as does U+0915 U+0942. The first should be kept; the second // removed. No combining sequence should be partially elided. - {"combining", u"0123\u0915\u093f\u0915\u0942456", u"0123\u0915\u093f…"}, + {"combining", L"0123\u0915\u093f\u0915\u0942456", + L"0123\u0915\u093f\u2026"}, // U+05E9 U+05BC U+05C1 U+05B8 forms a four-character compound glyph. // It should be either fully elided, or not elided at all. If completely // elided, an LTR Mark (U+200E) should be added. - {"grapheme1", u"0\u05e9\u05bc\u05c1\u05b8", u"0\u05e9\u05bc\u05c1\u05b8"}, - {"grapheme2", u"0\u05e9\u05bc\u05c1\u05b8abc", u"0…\u200E"}, - {"grapheme3", u"01\u05e9\u05bc\u05c1\u05b8abc", u"01…\u200E"}, - {"grapheme4", u"012\u05e9\u05bc\u05c1\u05b8abc", u"012…\u200E"}, + {"grapheme1", L"0\u05e9\u05bc\u05c1\u05b8", L"0\u05e9\u05bc\u05c1\u05b8"}, + {"grapheme2", L"0\u05e9\u05bc\u05c1\u05b8abc", L"0\u2026\u200E"}, + {"grapheme3", L"01\u05e9\u05bc\u05c1\u05b8abc", L"01\u2026\u200E"}, + {"grapheme4", L"012\u05e9\u05bc\u05c1\u05b8abc", L"012\u2026\u200E"}, // 𝄞 (U+1D11E, MUSICAL SYMBOL G CLEF) should be fully elided. - {"emoji", u"012\U0001D11Ex", u"012…"}, + {"emoji", L"012\U0001D11Ex", L"012\u2026"}, // Whitespace elision tests. - {"empty_no_elision", u"", u"", 0, kForceNoWhitespaceElision}, - {"empty_elision", u"", u"", 0, kForceWhitespaceElision}, - {"letter_weak_2_no_elision", u" . ", u" …", 2, kForceNoWhitespaceElision}, - {"xyz_no_elision", u" x xyz", u" x …", 5, kForceNoWhitespaceElision}, - {"xyz_elision", u" x xyz", u" x…", 5, kForceWhitespaceElision}, - {"ltr_rtl_elision4", u"x ב y ג", u"x…", 4, kForceWhitespaceElision}, - {"ltr_rtl_elision5", u"x ב y ג", u"x ב…\u200F", 5, + {"empty_no_elision", L"", L"", 0, kForceNoWhitespaceElision}, + {"empty_elision", L"", L"", 0, kForceWhitespaceElision}, + {"letter_weak_2_no_elision", L" . ", L" \u2026", 2, + kForceNoWhitespaceElision}, + {"xyz_no_elision", L" x xyz", L" x \u2026", 5, + kForceNoWhitespaceElision}, + {"xyz_elision", L" x xyz", L" x\u2026", 5, kForceWhitespaceElision}, + {"ltr_rtl_elision4", L"x \u05d1 y \u05d2", L"x\u2026", 4, kForceWhitespaceElision}, - {"ltr_rtl_elision9", u"x ב y ג", u"x ב y…", 9, + {"ltr_rtl_elision5", L"x \u05d1 y \u05d2", L"x \u05d1\u2026\u200F", 5, + kForceWhitespaceElision}, + {"ltr_rtl_elision9", L"x \u05d1 y \u05d2", L"x \u05d1 y\u2026", 9, kForceWhitespaceElision}, // Emoji U+1F601 and emoji U+1F321 U+FE0E are graphemes that result in // one glyph each. Eliding a glyph must remove the whole grapheme. It is // invalid to break a grapheme in pieces. - {"graphemes_elision3", u" \U0001F601 \U0001F321\uFE0E ", u"…", 3, + {"graphemes_elision3", L" \U0001F601 \U0001F321\uFE0E ", L"\u2026", 3, kForceWhitespaceElision}, - {"graphemes_elision6", u" \U0001F601 \U0001F321\uFE0E ", - u" \U0001F601…", 6, kForceWhitespaceElision}, - {"graphemes_elision7", u" \U0001F601 \U0001F321\uFE0E ", - u" \U0001F601 \U0001F321\uFE0E…", 7, kForceWhitespaceElision}, + {"graphemes_elision6", L" \U0001F601 \U0001F321\uFE0E ", + L" \U0001F601\u2026", 6, kForceWhitespaceElision}, + {"graphemes_elision7", L" \U0001F601 \U0001F321\uFE0E ", + L" \U0001F601 \U0001F321\uFE0E\u2026", 7, kForceWhitespaceElision}, }; INSTANTIATE_TEST_SUITE_P( @@ -2095,67 +2121,70 @@ RenderTextTestWithElideTextCase::ParamInfoToString); const ElideTextCase kElideTruncateTextCases[] = { - {"empty", u"", u""}, - {"letter_m_tail0", u"M", u""}, - {"letter_m_tail1", u"M", u"M"}, - {"no_eliding", u"012ab", u"012ab"}, - {"ltr_3", u"abc", u"abc"}, - {"ltr_2", u"abc", u"ab"}, - {"ltr_1", u"abc", u"a"}, - {"ltr_0", u"abc", u""}, - {"rtl_3", u"אבג", u"אבג"}, - {"rtl_2", u"אבג", u"אב"}, - {"rtl_1", u"אבג", u"א"}, - {"rtl_0", u"אבג", u""}, - {"ltr_rtl_5", u"abcאבג", u"abcאב"}, - {"ltr_rtl_4", u"abcאבג", u"abcא"}, - {"ltr_rtl_3", u"abcאבג", u"abc"}, - {"ltr_rtl_2", u"abcאבג", u"ab"}, - {"rtl_ltr_5", u"אבגabc", u"אבגab"}, - {"rtl_ltr_4", u"אבגabc", u"אבגa"}, - {"rtl_ltr_3", u"אבגabc", u"אבג"}, - {"rtl_ltr_2", u"אבגabc", u"אב"}, - {"bidi_1", u"012aבbבc", u"012aבbב"}, - {"bidi_2", u"012aבbבc", u"012aבb"}, - {"bidi_3", u"012aבbבc", u"012aב"}, - {"bidi_4", u"012aבbבc", u"012aב"}, + {"empty", L"", L""}, + {"letter_m_tail0", L"M", L""}, + {"letter_m_tail1", L"M", L"M"}, + {"no_eliding", L"012ab", L"012ab"}, + {"ltr_3", L"abc", L"abc"}, + {"ltr_2", L"abc", L"ab"}, + {"ltr_1", L"abc", L"a"}, + {"ltr_0", L"abc", L""}, + {"rtl_3", L"\u05d0\u05d1\u05d2", L"\u05d0\u05d1\u05d2"}, + {"rtl_2", L"\u05d0\u05d1\u05d2", L"\u05d0\u05d1"}, + {"rtl_1", L"\u05d0\u05d1\u05d2", L"\u05d0"}, + {"rtl_0", L"\u05d0\u05d1\u05d2", L""}, + {"ltr_rtl_5", L"abc\u05d0\u05d1\u05d2", L"abc\u05d0\u05d1"}, + {"ltr_rtl_4", L"abc\u05d0\u05d1\u05d2", L"abc\u05d0"}, + {"ltr_rtl_3", L"abc\u05d0\u05d1\u05d2", L"abc"}, + {"ltr_rtl_2", L"abc\u05d0\u05d1\u05d2", L"ab"}, + {"rtl_ltr_5", L"\u05d0\u05d1\u05d2abc", L"\u05d0\u05d1\u05d2ab"}, + {"rtl_ltr_4", L"\u05d0\u05d1\u05d2abc", L"\u05d0\u05d1\u05d2a"}, + {"rtl_ltr_3", L"\u05d0\u05d1\u05d2abc", L"\u05d0\u05d1\u05d2"}, + {"rtl_ltr_2", L"\u05d0\u05d1\u05d2abc", L"\u05d0\u05d1"}, + {"bidi_1", L"012a\u05d1b\u05d1c", L"012a\u05d1b\u05d1"}, + {"bidi_2", L"012a\u05d1b\u05d1c", L"012a\u05d1b"}, + {"bidi_3", L"012a\u05d1b\u05d1c", L"012a\u05d1"}, + {"bidi_4", L"012a\u05d1b\u05d1c", L"012a\u05d1"}, // Test surrogate pairs. The first pair 𝄞 'MUSICAL SYMBOL G CLEF' U+1D11E // should be kept, and the second pair 𝄢 'MUSICAL SYMBOL F CLEF' U+1D122 // should be removed. No surrogate pair should be partially elided. - {"surrogate1", u"0123\U0001D11E\U0001D122x", u"0123\U0001D11E\U0001D122"}, - {"surrogate2", u"0123\U0001D11E\U0001D122x", u"0123\U0001D11E"}, - {"surrogate3", u"0123\U0001D11E\U0001D122x", u"0123"}, + {"surrogate1", L"0123\U0001D11E\U0001D122x", L"0123\U0001D11E\U0001D122"}, + {"surrogate2", L"0123\U0001D11E\U0001D122x", L"0123\U0001D11E"}, + {"surrogate3", L"0123\U0001D11E\U0001D122x", L"0123"}, // Test combining character sequences. U+0915 U+093F forms a compound // glyph, as does U+0915 U+0942. The first should be kept; the second // removed. No combining sequence should be partially elided. - {"combining", u"0123\u0915\u093f\u0915\u0942456", u"0123\u0915\u093f"}, + {"combining", L"0123\u0915\u093f\u0915\u0942456", L"0123\u0915\u093f"}, // 𝄞 (U+1D11E, MUSICAL SYMBOL G CLEF) should be fully elided. - {"emoji1", u"012\U0001D11Ex", u"012\U0001D11E"}, - {"emoji2", u"012\U0001D11Ex", u"012"}, + {"emoji1", L"012\U0001D11Ex", L"012\U0001D11E"}, + {"emoji2", L"012\U0001D11Ex", L"012"}, // Whitespace elision tests. - {"empty_no_elision", u"", u"", 0, kForceNoWhitespaceElision}, - {"empty_elision", u"", u"", 0, kForceWhitespaceElision}, - {"xyz_no_elision", u" x xyz", u" x ", 5, kForceNoWhitespaceElision}, - {"xyz_elision", u" x xyz", u" x", 5, kForceWhitespaceElision}, - {"ltr_rtl_elision3", u"x ב y ג", u"x", 3, kForceWhitespaceElision}, - {"ltr_rtl_elision4", u"x ב y ג", u"x ב", 4, kForceWhitespaceElision}, - {"ltr_rtl_elision5", u"x ב y ג", u"x ב", 5, kForceWhitespaceElision}, - {"ltr_rtl_elision9", u"x ב y ג", u"x ב y", 9, + {"empty_no_elision", L"", L"", 0, kForceNoWhitespaceElision}, + {"empty_elision", L"", L"", 0, kForceWhitespaceElision}, + {"xyz_no_elision", L" x xyz", L" x ", 5, kForceNoWhitespaceElision}, + {"xyz_elision", L" x xyz", L" x", 5, kForceWhitespaceElision}, + {"ltr_rtl_elision3", L"x \u05d1 y \u05d2", L"x", 3, + kForceWhitespaceElision}, + {"ltr_rtl_elision4", L"x \u05d1 y \u05d2", L"x \u05d1", 4, + kForceWhitespaceElision}, + {"ltr_rtl_elision5", L"x \u05d1 y \u05d2", L"x \u05d1", 5, + kForceWhitespaceElision}, + {"ltr_rtl_elision9", L"x \u05d1 y \u05d2", L"x \u05d1 y", 9, kForceWhitespaceElision}, // Emoji U+1F601 and emoji U+1F321 U+FE0E are graphemes that result in // one glyph each. Eliding a glyph must remove the whole grapheme. It is // invalid to break a grapheme in pieces. - {"graphemes_elision2", u" \U0001F601 \U0001F321\uFE0E ", u"", 2, + {"graphemes_elision2", L" \U0001F601 \U0001F321\uFE0E ", L"", 2, kForceWhitespaceElision}, - {"graphemes_elision3", u" \U0001F601 \U0001F321\uFE0E ", u" \U0001F601", + {"graphemes_elision3", L" \U0001F601 \U0001F321\uFE0E ", L" \U0001F601", 3, kForceWhitespaceElision}, - {"graphemes_elision5", u" \U0001F601 \U0001F321\uFE0E ", u" \U0001F601", + {"graphemes_elision5", L" \U0001F601 \U0001F321\uFE0E ", L" \U0001F601", 5, kForceWhitespaceElision}, - {"graphemes_elision6", u" \U0001F601 \U0001F321\uFE0E ", - u" \U0001F601 \U0001F321\uFE0E", 6, kForceWhitespaceElision}, - {"graphemes_elision7", u" \U0001F601 \U0001F321\uFE0E ", - u" \U0001F601 \U0001F321\uFE0E", 7, kForceWhitespaceElision}, + {"graphemes_elision6", L" \U0001F601 \U0001F321\uFE0E ", + L" \U0001F601 \U0001F321\uFE0E", 6, kForceWhitespaceElision}, + {"graphemes_elision7", L" \U0001F601 \U0001F321\uFE0E ", + L" \U0001F601 \U0001F321\uFE0E", 7, kForceWhitespaceElision}, }; INSTANTIATE_TEST_SUITE_P( @@ -2167,44 +2196,44 @@ const ElideTextCase kElideEmailTextCases[] = { // Invalid email text. - {"empty", u"", u""}, - {"invalid_char1", u"x", u""}, - {"invalid_char3", u"xyz", u"x…"}, - {"invalid_amp", u"@", u""}, - {"invalid_no_prefix0", u"@y", u""}, - {"invalid_no_prefix1", u"@y", u"…"}, - {"invalid_no_prefix2", u"@xyz", u"@x…"}, - {"invalid_no_suffix0", u"x@", u""}, - {"invalid_no_suffix1", u"x@", u"…"}, - {"invalid_no_suffix2", u"xyz@", u"x…@"}, + {"empty", L"", L""}, + {"invalid_char1", L"x", L""}, + {"invalid_char3", L"xyz", L"x\u2026"}, + {"invalid_amp", L"@", L""}, + {"invalid_no_prefix0", L"@y", L""}, + {"invalid_no_prefix1", L"@y", L"\u2026"}, + {"invalid_no_prefix2", L"@xyz", L"@x\u2026"}, + {"invalid_no_suffix0", L"x@", L""}, + {"invalid_no_suffix1", L"x@", L"\u2026"}, + {"invalid_no_suffix2", L"xyz@", L"x\u2026@"}, - {"at1", u"@", u"@"}, - {"at2", u"@@", u"…", 1}, - {"at3", u"@@@", u"…", 2}, - {"at4", u"@@@@", u"@…@", 3}, + {"at1", L"@", L"@"}, + {"at2", L"@@", L"\u2026", 1}, + {"at3", L"@@@", L"\u2026", 2}, + {"at4", L"@@@@", L"@\u2026@", 3}, - {"small1", u"a@b", u"…", 1}, - {"small2", u"a@b", u"…", 2}, - {"small3", u"a@b", u"a@b", 3}, - {"small_username3", u"xyz@b", u"…", 3}, - {"small_username4", u"xyz@b", u"x…@b", 4}, - {"small_username5", u"xyz@b", u"xyz@b", 5}, - {"small_domain3", u"a@xyz", u"…", 3}, - {"small_domain4", u"a@xyz", u"a@x…", 4}, - {"small_domain5", u"a@xyz", u"a@xyz", 5}, + {"small1", L"a@b", L"\u2026", 1}, + {"small2", L"a@b", L"\u2026", 2}, + {"small3", L"a@b", L"a@b", 3}, + {"small_username3", L"xyz@b", L"\u2026", 3}, + {"small_username4", L"xyz@b", L"x\u2026@b", 4}, + {"small_username5", L"xyz@b", L"xyz@b", 5}, + {"small_domain3", L"a@xyz", L"\u2026", 3}, + {"small_domain4", L"a@xyz", L"a@x\u2026", 4}, + {"small_domain5", L"a@xyz", L"a@xyz", 5}, // Valid email. - {"email_small", u"a@b.com", u"…"}, - {"email_nobody3", u"nobody@gmail.com", u"…", 3}, - {"email_nobody4", u"nobody@gmail.com", u"…", 4}, - {"email_nobody5", u"nobody@gmail.com", u"n…@g…", 5}, - {"email_nobody6", u"nobody@gmail.com", u"no…@g…", 6}, - {"email_nobody7", u"nobody@gmail.com", u"no…@g…m", 7}, - {"email_nobody8", u"nobody@gmail.com", u"nob…@g…m", 8}, - {"email_nobody9", u"nobody@gmail.com", u"nob…@gm…m", 9}, - {"email_nobody10", u"nobody@gmail.com", u"nobo…@gm…m", 10}, - {"email_root", u"root@localhost", u"r…@l…", 5}, - {"email_myself", u"myself@127.0.0.1", u"my…@1…", 6}, + {"email_small", L"a@b.com", L"\u2026"}, + {"email_nobody3", L"nobody@gmail.com", L"\u2026", 3}, + {"email_nobody4", L"nobody@gmail.com", L"\u2026", 4}, + {"email_nobody5", L"nobody@gmail.com", L"n\u2026@g\u2026", 5}, + {"email_nobody6", L"nobody@gmail.com", L"no\u2026@g\u2026", 6}, + {"email_nobody7", L"nobody@gmail.com", L"no\u2026@g\u2026m", 7}, + {"email_nobody8", L"nobody@gmail.com", L"nob\u2026@g\u2026m", 8}, + {"email_nobody9", L"nobody@gmail.com", L"nob\u2026@gm\u2026m", 9}, + {"email_nobody10", L"nobody@gmail.com", L"nobo\u2026@gm\u2026m", 10}, + {"email_root", L"root@localhost", L"r\u2026@l\u2026", 5}, + {"email_myself", L"myself@127.0.0.1", L"my\u2026@1\u2026", 6}, }; INSTANTIATE_TEST_SUITE_P( @@ -2259,11 +2288,11 @@ render_text->SetCursorEnabled(false); render_text->SetDisplayRect(Rect(0, 0, 3 * kGlyphWidth, 100)); render_text->SetElideBehavior(ELIDE_TAIL); - EXPECT_EQ(u"ab…", render_text->GetDisplayText()); + EXPECT_EQ(u"ab\u2026", render_text->GetDisplayText()); // Setting a different eliding behavior must trigger a relayout. render_text->SetElideBehavior(ELIDE_HEAD); - EXPECT_EQ(u"…ef", render_text->GetDisplayText()); + EXPECT_EQ(u"\u2026ef", render_text->GetDisplayText()); } TEST_F(RenderTextTest, SetWhitespaceElision) { @@ -2277,11 +2306,11 @@ render_text->SetDisplayRect(Rect(0, 0, 3 * kGlyphWidth, 100)); render_text->SetElideBehavior(ELIDE_TAIL); render_text->SetWhitespaceElision(false); - EXPECT_EQ(u"a …", render_text->GetDisplayText()); + EXPECT_EQ(u"a \u2026", render_text->GetDisplayText()); // Setting a different whitespace elision must trigger a relayout. render_text->SetWhitespaceElision(true); - EXPECT_EQ(u"a…", render_text->GetDisplayText()); + EXPECT_EQ(u"a\u2026", render_text->GetDisplayText()); } TEST_F(RenderTextTest, ElidedObscuredText) { @@ -2531,22 +2560,23 @@ } TEST_F(RenderTextTest, ElidedStyledTextRtl) { - static const char16_t* kInputTexts[] = { - u"http://ar.wikipedia.com/فحص", - u"testحص,", - u"حص,test", - u"…", - u"…test", - u"test…", - u"حص,test…", - u"ٱ", - u"\uFEFF", // BOM: Byte Order Marker - u"…\u200F", // Right to left marker. + static const char* kInputTexts[] = { + "http://ar.wikipedia.com/فحص", + "testحص,", + "حص,test", + "…", + "…test", + "test…", + "حص,test…", + "ٱ", + "\uFEFF", // BOM: Byte Order Marker + "…\u200F", // Right to left marker. }; for (const auto* raw_text : kInputTexts) { - std::u16string input_text(raw_text); - SCOPED_TRACE(u"ElidedStyledTextRtl text = " + input_text); + SCOPED_TRACE( + base::StringPrintf("ElidedStyledTextRtl text = %s", raw_text)); + std::u16string input_text(UTF8ToUTF16(raw_text)); RenderText* render_text = GetRenderText(); render_text->SetText(input_text); @@ -2584,61 +2614,61 @@ TEST_F(RenderTextTest, TruncatedText) { struct { - const char16_t* text; - const char16_t* display_text; + const wchar_t* text; + const wchar_t* display_text; } cases[] = { // Strings shorter than the truncation length should be laid out in full. - {u"", u""}, - {u" . ", u" . "}, // a wide kWeak - {u"abc", u"abc"}, // a wide kLtr - {u"אבג", u"אבג"}, // a wide kRtl - {u"aאב", u"aאב"}, // a wide kLtrRtl - {u"aבb", u"aבb"}, // a wide kLtrRtlLtr - {u"אבa", u"אבa"}, // a wide kRtlLtr - {u"אaב", u"אaב"}, // a wide kRtlLtrRtl - {u"01234", u"01234"}, + {L"", L""}, + {L" . ", L" . "}, // a wide kWeak + {L"abc", L"abc"}, // a wide kLtr + {L"\u05d0\u05d1\u05d2", L"\u05d0\u05d1\u05d2"}, // a wide kRtl + {L"a\u05d0\u05d1", L"a\u05d0\u05d1"}, // a wide kLtrRtl + {L"a\u05d1b", L"a\u05d1b"}, // a wide kLtrRtlLtr + {L"\u05d0\u05d1a", L"\u05d0\u05d1a"}, // a wide kRtlLtr + {L"\u05d0a\u05d1", L"\u05d0a\u05d1"}, // a wide kRtlLtrRtl + {L"01234", L"01234"}, // Long strings should be truncated with an ellipsis appended at the end. - {u"012345", u"0123…"}, - {u"012 . ", u"012 …"}, - {u"012abc", u"012a…"}, - {u"012aאב", u"012a…"}, - {u"012aבb", u"012a…"}, - {u"012אבג", u"012א…"}, - {u"012אבa", u"012א…"}, - {u"012אaב", u"012א…"}, + {L"012345", L"0123\u2026"}, + {L"012 . ", L"012 \u2026"}, + {L"012abc", L"012a\u2026"}, + {L"012a\u05d0\u05d1", L"012a\u2026"}, + {L"012a\u05d1b", L"012a\u2026"}, + {L"012\u05d0\u05d1\u05d2", L"012\u05d0\u2026"}, + {L"012\u05d0\u05d1a", L"012\u05d0\u2026"}, + {L"012\u05d0a\u05d1", L"012\u05d0\u2026"}, // Surrogate pairs should be truncated reasonably enough. - {u"0123\u0915\u093f", u"0123…"}, - {u"\u05e9\u05bc\u05c1\u05b8", u"\u05e9\u05bc\u05c1\u05b8"}, - {u"0\u05e9\u05bc\u05c1\u05b8", u"0\u05e9\u05bc\u05c1\u05b8"}, - {u"01\u05e9\u05bc\u05c1\u05b8", u"01…"}, - {u"012\u05e9\u05bc\u05c1\u05b8", u"012…"}, + {L"0123\u0915\u093f", L"0123\u2026"}, + {L"\u05e9\u05bc\u05c1\u05b8", L"\u05e9\u05bc\u05c1\u05b8"}, + {L"0\u05e9\u05bc\u05c1\u05b8", L"0\u05e9\u05bc\u05c1\u05b8"}, + {L"01\u05e9\u05bc\u05c1\u05b8", L"01\u2026"}, + {L"012\u05e9\u05bc\u05c1\u05b8", L"012\u2026"}, // Codepoint U+0001D11E is using 2x 16-bit characters. - {u"0\U0001D11Eaaa", u"0\U0001D11Ea…"}, - {u"01\U0001D11Eaaa", u"01\U0001D11E…"}, - {u"012\U0001D11Eaaa", u"012…"}, - {u"0123\U0001D11Eaaa", u"0123…"}, - {u"01234\U0001D11Eaaa", u"0123…"}, + {L"0\U0001D11Eaaa", L"0\U0001D11Ea\u2026"}, + {L"01\U0001D11Eaaa", L"01\U0001D11E\u2026"}, + {L"012\U0001D11Eaaa", L"012\u2026"}, + {L"0123\U0001D11Eaaa", L"0123\u2026"}, + {L"01234\U0001D11Eaaa", L"0123\u2026"}, // Combining codepoint should stay together. // (Letter 'e' U+0065 and acute accent U+0301). - {u"0e\u0301aaa", u"0e\u0301a…"}, - {u"01e\u0301aaa", u"01e\u0301…"}, - {u"012e\u0301aaa", u"012…"}, + {L"0e\u0301aaa", L"0e\u0301a\u2026"}, + {L"01e\u0301aaa", L"01e\u0301\u2026"}, + {L"012e\u0301aaa", L"012\u2026"}, // Emoji 'keycap letter 6'. - {u"\u0036\uFE0F\u20E3aaa", u"\u0036\uFE0F\u20E3a…"}, - {u"0\u0036\uFE0F\u20E3aaa", u"0\u0036\uFE0F\u20E3…"}, - {u"01\u0036\uFE0F\u20E3aaa", u"01…"}, + {L"\u0036\uFE0F\u20E3aaa", L"\u0036\uFE0F\u20E3a\u2026"}, + {L"0\u0036\uFE0F\u20E3aaa", L"0\u0036\uFE0F\u20E3\u2026"}, + {L"01\u0036\uFE0F\u20E3aaa", L"01\u2026"}, // Emoji 'pilot'. - {u"\U0001F468\u200D\u2708\uFE0F", u"\U0001F468\u200D\u2708\uFE0F"}, - {u"\U0001F468\u200D\u2708\uFE0F0", u"…"}, - {u"0\U0001F468\u200D\u2708\uFE0F", u"0…"}, + {L"\U0001F468\u200D\u2708\uFE0F", L"\U0001F468\u200D\u2708\uFE0F"}, + {L"\U0001F468\u200D\u2708\uFE0F0", L"\u2026"}, + {L"0\U0001F468\u200D\u2708\uFE0F", L"0\u2026"}, }; RenderText* render_text = GetRenderText(); render_text->set_truncate_length(5); for (size_t i = 0; i < base::size(cases); i++) { - render_text->SetText(cases[i].text); - EXPECT_EQ(cases[i].text, render_text->text()); - EXPECT_EQ(cases[i].display_text, render_text->GetDisplayText()) + render_text->SetText(WideToUTF16(cases[i].text)); + EXPECT_EQ(WideToUTF16(cases[i].text), render_text->text()); + EXPECT_EQ(WideToUTF16(cases[i].display_text), render_text->GetDisplayText()) << "For case " << i << ": " << cases[i].text; } } @@ -2661,13 +2691,13 @@ EXPECT_EQ(GetObscuredString(3), render_text->GetDisplayText()); render_text->SetObscuredRevealIndex(0); - EXPECT_EQ(u"e\u0301…", render_text->GetDisplayText()); + EXPECT_EQ(u"e\u0301\u2026", render_text->GetDisplayText()); render_text->SetObscuredRevealIndex(2); - EXPECT_EQ(u"\u2022…", render_text->GetDisplayText()); + EXPECT_EQ(u"\u2022\u2026", render_text->GetDisplayText()); render_text->SetObscuredRevealIndex(7); - EXPECT_EQ(u"\u2022\u2022…", render_text->GetDisplayText()); + EXPECT_EQ(u"\u2022\u2022\u2026", render_text->GetDisplayText()); } TEST_F(RenderTextTest, TruncatedCursorMovementLTR) { @@ -2701,7 +2731,7 @@ TEST_F(RenderTextTest, TruncatedCursorMovementRTL) { RenderText* render_text = GetRenderText(); render_text->set_truncate_length(2); - render_text->SetText(u"אבגד"); + render_text->SetText(u"\u05d0\u05d1\u05d2\u05d3"); EXPECT_EQ(SelectionModel(0, CURSOR_BACKWARD), render_text->selection_model()); render_text->MoveCursor(LINE_BREAK, CURSOR_LEFT, SELECTION_NONE); @@ -3223,18 +3253,18 @@ render_text->SetText(u"a"); EXPECT_EQ(base::i18n::LEFT_TO_RIGHT, render_text->GetTextDirection()); - render_text->SetText(u"א"); + render_text->SetText(u"\u05d0"); EXPECT_EQ(base::i18n::RIGHT_TO_LEFT, render_text->GetTextDirection()); // The codepoints u+2026 (ellipsis) has no strong direction. - render_text->SetText(u"…"); + render_text->SetText(u"\u2026"); EXPECT_EQ(original_text_direction, render_text->GetTextDirection()); render_text->AppendText(u"a"); EXPECT_EQ(base::i18n::LEFT_TO_RIGHT, render_text->GetTextDirection()); - render_text->SetText(u"…"); + render_text->SetText(u"\u2026"); EXPECT_EQ(original_text_direction, render_text->GetTextDirection()); - render_text->AppendText(u"א"); + render_text->AppendText(u"\u05d0"); EXPECT_EQ(base::i18n::RIGHT_TO_LEFT, render_text->GetTextDirection()); } @@ -3248,18 +3278,18 @@ render_text->SetText(u"a"); EXPECT_EQ(base::i18n::LEFT_TO_RIGHT, render_text->GetDisplayTextDirection()); - render_text->SetText(u"א"); + render_text->SetText(u"\u05d0"); EXPECT_EQ(base::i18n::RIGHT_TO_LEFT, render_text->GetDisplayTextDirection()); // The codepoints u+2026 (ellipsis) has no strong direction. - render_text->SetText(u"…"); + render_text->SetText(u"\u2026"); EXPECT_EQ(original_text_direction, render_text->GetDisplayTextDirection()); render_text->AppendText(u"a"); EXPECT_EQ(base::i18n::LEFT_TO_RIGHT, render_text->GetDisplayTextDirection()); - render_text->SetText(u"…"); + render_text->SetText(u"\u2026"); EXPECT_EQ(original_text_direction, render_text->GetDisplayTextDirection()); - render_text->AppendText(u"א"); + render_text->AppendText(u"\u05d0"); EXPECT_EQ(base::i18n::RIGHT_TO_LEFT, render_text->GetDisplayTextDirection()); } @@ -3274,7 +3304,7 @@ // The elided text is an ellipsis with neutral directionality, and a 'z' with // a strong LTR directionality. - EXPECT_EQ(u"…z", render_text->GetDisplayText()); + EXPECT_EQ(u"\u2026z", render_text->GetDisplayText()); EXPECT_EQ(base::i18n::RIGHT_TO_LEFT, render_text->GetTextDirection()); EXPECT_EQ(base::i18n::LEFT_TO_RIGHT, render_text->GetDisplayTextDirection()); } @@ -3284,7 +3314,7 @@ ASSERT_EQ(render_text->directionality_mode(), DIRECTIONALITY_FROM_TEXT); // The codepoints u+2026 (ellipsis) has weak directionality. - render_text->SetText(u"…"); + render_text->SetText(u"\u2026"); const base::i18n::TextDirection original_text_direction = render_text->GetTextDirection(); @@ -3308,11 +3338,11 @@ render_text->SetVerticalAlignment(ALIGN_TOP); const size_t kLineSize = 50; - std::u16string text; + std::string text; for (size_t i = 0; i < kLineSize - 1; ++i) - text += u"a\n"; + text += "a\n"; - render_text->SetText(text); + render_text->SetText(ASCIIToUTF16(text)); EXPECT_EQ(kLineSize, render_text->GetNumLines()); // Move cursor down with scroll. @@ -3353,11 +3383,11 @@ TEST_F(RenderTextTest, GetDisplayTextDirection) { struct { - const char16_t* text; + const char* text; const base::i18n::TextDirection text_direction; } cases[] = { // Blank strings and those with no/weak directionality default to LTR. - {u"", base::i18n::LEFT_TO_RIGHT}, + {"", base::i18n::LEFT_TO_RIGHT}, {kWeak, base::i18n::LEFT_TO_RIGHT}, // Strings that begin with strong LTR characters. {kLtr, base::i18n::LEFT_TO_RIGHT}, @@ -3380,7 +3410,7 @@ // Ensure that directionality modes yield the correct text directions. for (size_t j = 0; j < base::size(cases); j++) { - render_text->SetText(cases[j].text); + render_text->SetText(UTF8ToUTF16(cases[j].text)); render_text->SetDirectionalityMode(DIRECTIONALITY_FROM_TEXT); EXPECT_EQ(render_text->GetDisplayTextDirection(),cases[j].text_direction); render_text->SetDirectionalityMode(DIRECTIONALITY_FROM_UI); @@ -3401,15 +3431,15 @@ // Ensure that text changes update the direction for DIRECTIONALITY_FROM_TEXT. render_text->SetDirectionalityMode(DIRECTIONALITY_FROM_TEXT); - render_text->SetText(kLtr); + render_text->SetText(UTF8ToUTF16(kLtr)); EXPECT_EQ(render_text->GetDisplayTextDirection(), base::i18n::LEFT_TO_RIGHT); - render_text->SetText(kRtl); + render_text->SetText(UTF8ToUTF16(kRtl)); EXPECT_EQ(render_text->GetDisplayTextDirection(), base::i18n::RIGHT_TO_LEFT); } struct GetTextIndexOfLineCase { const char* test_name; - const char16_t* const text; + const wchar_t* const text; const std::vector<size_t> line_breaks; const bool set_word_wrap = false; const bool set_obscured = false; @@ -3435,60 +3465,60 @@ render_text->SetWordWrapBehavior(WRAP_LONG_WORDS); } render_text->SetObscured(param.set_obscured); - render_text->SetText(param.text); + render_text->SetText(base::WideToUTF16(param.text)); for (size_t i = 0; i < param.line_breaks.size(); ++i) { EXPECT_EQ(param.line_breaks[i], render_text->GetTextIndexOfLine(i)); } } const GetTextIndexOfLineCase kGetTextIndexOfLineCases[] = { - {"emptyString", u"", {0}}, + {"emptyString", L"", {0}}, // The following test strings are three character strings. // The word wrap makes each character fall on a new line. - {"kWeak_minWidth", u" . ", {0, 1, 2}, kUseWordWrap}, - {"kLtr_minWidth", u"abc", {0, 1, 2}, kUseWordWrap}, - {"kLtrRtl_minWidth", u"aאב", {0, 1, 2}, kUseWordWrap}, - {"kLtrRtlLtr_minWidth", u"aבb", {0, 1, 2}, kUseWordWrap}, - {"kRtl_minWidth", u"אבג", {0, 1, 2}, kUseWordWrap}, - {"kRtlLtr_minWidth", u"אבa", {0, 1, 2}, kUseWordWrap}, - {"kRtlLtrRtl_minWidth", u"אaב", {0, 1, 2}, kUseWordWrap}, + {"kWeak_minWidth", L" . ", {0, 1, 2}, kUseWordWrap}, + {"kLtr_minWidth", L"abc", {0, 1, 2}, kUseWordWrap}, + {"kLtrRtl_minWidth", L"a\u05d0\u05d1", {0, 1, 2}, kUseWordWrap}, + {"kLtrRtlLtr_minWidth", L"a\u05d1b", {0, 1, 2}, kUseWordWrap}, + {"kRtl_minWidth", L"\u05d0\u05d1\u05d2", {0, 1, 2}, kUseWordWrap}, + {"kRtlLtr_minWidth", L"\u05d0\u05d1a", {0, 1, 2}, kUseWordWrap}, + {"kRtlLtrRtl_minWidth", L"\u05d0a\u05d1", {0, 1, 2}, kUseWordWrap}, // The following test strings have 2 graphemes separated by a newline. // The obscured text replace each grapheme by a single codepoint. {"grapheme_unobscured", - u"\U0001F601\n\U0001F468\u200D\u2708\uFE0F\nx", + L"\U0001F601\n\U0001F468\u200D\u2708\uFE0F\nx", {0, 3, 9}}, {"grapheme_obscured", - u"\U0001F601\n\U0001F468\u200D\u2708\uFE0F\nx", + L"\U0001F601\n\U0001F468\u200D\u2708\uFE0F\nx", {0, 3, 9}, !kUseWordWrap, kUseObscuredText}, // The following test strings have a new line character. - {"basic_newLine", u"abc\ndef", {0, 4}}, - {"basic_newLineWindows", u"abc\r\ndef", {0, 5}}, - {"spaces_newLine", u"a \n b ", {0, 3}}, - {"spaces_newLineWindows", u"a \r\n b ", {0, 4}}, - {"double_newLine", u"a\n\nb", {0, 2, 3}}, - {"double_newLineWindows", u"a\r\n\r\nb", {0, 3, 5}}, - {"start_newLine", u"\nab", {0, 1}}, - {"start_newLineWindows", u"\r\nab", {0, 2}}, - {"end_newLine", u"ab\n", {0}}, - {"end_newLineWindows", u"ab\r\n", {0}}, - {"isolated_newLine", u"\n", {0}}, - {"isolated_newLineWindows", u"\r\n", {0}}, - {"isolatedDouble_newLine", u"\n\n", {0, 1}}, - {"isolatedDouble_newLineWindows", u"\r\n\r\n", {0, 2}}, + {"basic_newLine", L"abc\ndef", {0, 4}}, + {"basic_newLineWindows", L"abc\r\ndef", {0, 5}}, + {"spaces_newLine", L"a \n b ", {0, 3}}, + {"spaces_newLineWindows", L"a \r\n b ", {0, 4}}, + {"double_newLine", L"a\n\nb", {0, 2, 3}}, + {"double_newLineWindows", L"a\r\n\r\nb", {0, 3, 5}}, + {"start_newLine", L"\nab", {0, 1}}, + {"start_newLineWindows", L"\r\nab", {0, 2}}, + {"end_newLine", L"ab\n", {0}}, + {"end_newLineWindows", L"ab\r\n", {0}}, + {"isolated_newLine", L"\n", {0}}, + {"isolated_newLineWindows", L"\r\n", {0}}, + {"isolatedDouble_newLine", L"\n\n", {0, 1}}, + {"isolatedDouble_newLineWindows", L"\r\n\r\n", {0, 2}}, // The following test strings have unicode characters. - {"playSymbol_unicode", u"x\n\u25B6\ny", {0, 2, 4}}, - {"emoji_unicode", u"x\n\U0001F601\ny\n\u2728\nz", {0, 2, 5, 7, 9}}, - {"flag_unicode", u"🇬🇧\n🇯🇵", {0, 5}, false, false}, + {"playSymbol_unicode", L"x\n\u25B6\ny", {0, 2, 4}}, + {"emoji_unicode", L"x\n\U0001F601\ny\n\u2728\nz", {0, 2, 5, 7, 9}}, + {"flag_unicode", L"🇬🇧\n🇯🇵", {0, 5}, false, false}, // The following cases test that GetTextIndexOfLine returns the length of // the text when passed a line index larger than the number of lines. - {"basic_outsideRange", u"abc", {0, 1, 2, 3, 3}, kUseWordWrap}, - {"emptyString_outsideRange", u"", {0, 0, 0}}, - {"newLine_outsideRange", u"\n", {0, 1, 1}}, - {"newLineWindows_outsideRange", u"\r\n", {0, 2, 2, 2}}, - {"doubleNewLine_outsideRange", u"\n\n", {0, 1, 2, 2}}, - {"doubleNewLineWindows_outsideRange", u"\r\n\r\n", {0, 2, 4, 4}}, + {"basic_outsideRange", L"abc", {0, 1, 2, 3, 3}, kUseWordWrap}, + {"emptyString_outsideRange", L"", {0, 0, 0}}, + {"newLine_outsideRange", L"\n", {0, 1, 1}}, + {"newLineWindows_outsideRange", L"\r\n", {0, 2, 2, 2}}, + {"doubleNewLine_outsideRange", L"\n\n", {0, 1, 2, 2}}, + {"doubleNewLineWindows_outsideRange", L"\r\n\r\n", {0, 2, 4, 4}}, }; INSTANTIATE_TEST_SUITE_P( @@ -3523,7 +3553,7 @@ TEST_F(RenderTextTest, MoveCursorLeftRightInLtrRtl) { RenderText* render_text = GetRenderText(); // LTR-RTL - render_text->SetText(u"abcאבג"); + render_text->SetText(u"abc\u05d0\u05d1\u05d2"); // The last one is the expected END position. std::vector<SelectionModel> expected; expected.push_back(SelectionModel(0, CURSOR_BACKWARD)); @@ -3551,7 +3581,7 @@ TEST_F(RenderTextTest, MoveCursorLeftRightInLtrRtlLtr) { RenderText* render_text = GetRenderText(); // LTR-RTL-LTR. - render_text->SetText(u"aבb"); + render_text->SetText(u"a\u05d1b"); std::vector<SelectionModel> expected; expected.push_back(SelectionModel(0, CURSOR_BACKWARD)); expected.push_back(SelectionModel(1, CURSOR_BACKWARD)); @@ -3572,7 +3602,7 @@ TEST_F(RenderTextTest, MoveCursorLeftRightInRtl) { RenderText* render_text = GetRenderText(); // Pure RTL. - render_text->SetText(u"אבג"); + render_text->SetText(u"\u05d0\u05d1\u05d2"); render_text->MoveCursor(LINE_BREAK, CURSOR_RIGHT, SELECTION_NONE); std::vector<SelectionModel> expected; @@ -3596,7 +3626,7 @@ TEST_F(RenderTextTest, MoveCursorLeftRightInRtlLtr) { RenderText* render_text = GetRenderText(); // RTL-LTR - render_text->SetText(u"אבגabc"); + render_text->SetText(u"\u05d0\u05d1\u05d2abc"); render_text->MoveCursor(LINE_BREAK, CURSOR_RIGHT, SELECTION_NONE); std::vector<SelectionModel> expected; expected.push_back(SelectionModel(0, CURSOR_BACKWARD)); @@ -3624,7 +3654,7 @@ TEST_F(RenderTextTest, MoveCursorLeftRightInRtlLtrRtl) { RenderText* render_text = GetRenderText(); // RTL-LTR-RTL. - render_text->SetText(u"אaב"); + render_text->SetText(u"\u05d0a\u05d1"); render_text->MoveCursor(LINE_BREAK, CURSOR_RIGHT, SELECTION_NONE); std::vector<SelectionModel> expected; expected.push_back(SelectionModel(0, CURSOR_BACKWARD)); @@ -3926,12 +3956,12 @@ } TEST_F(RenderTextTest, FindCursorPosition) { - const char16_t* kTestStrings[] = {kLtrRtl, kLtrRtlLtr, kRtlLtr, kRtlLtrRtl}; + const char* kTestStrings[] = {kLtrRtl, kLtrRtlLtr, kRtlLtr, kRtlLtrRtl}; RenderText* render_text = GetRenderText(); render_text->SetDisplayRect(Rect(0, 0, 100, 20)); for (size_t i = 0; i < base::size(kTestStrings); ++i) { SCOPED_TRACE(base::StringPrintf("Testing case[%" PRIuS "]", i)); - render_text->SetText(kTestStrings[i]); + render_text->SetText(UTF8ToUTF16(kTestStrings[i])); for (size_t j = 0; j < render_text->text().length(); ++j) { gfx::RangeF cursor_span = render_text->GetCursorSpan(Range(j, j + 1)); // Test a point just inside the leading edge of the glyph bounds. @@ -3944,7 +3974,8 @@ // Tests that FindCursorPosition behaves correctly for multi-line text. TEST_F(RenderTextTest, FindCursorPositionMultiline) { - const char16_t* kTestStrings[] = {u"abc def", u"אבג דהו"}; + const char* kTestStrings[] = {"abc def", + "\u05d0\u05d1\u05d2 \u05d3\u05d4\u05d5"}; SetGlyphWidth(5); RenderText* render_text = GetRenderText(); @@ -3952,7 +3983,7 @@ render_text->SetMultiline(true); for (size_t i = 0; i < base::size(kTestStrings); i++) { - render_text->SetText(kTestStrings[i]); + render_text->SetText(UTF8ToUTF16(kTestStrings[i])); EXPECT_EQ(2u, render_text->GetNumLines()); const bool is_ltr = @@ -4044,8 +4075,8 @@ } TEST_F(RenderTextTest, SelectAll) { - const char16_t* const cases[] = {kWeak, kLtr, kLtrRtl, kLtrRtlLtr, - kRtl, kRtlLtr, kRtlLtrRtl}; + const char* const cases[] = {kWeak, kLtr, kLtrRtl, kLtrRtlLtr, + kRtl, kRtlLtr, kRtlLtrRtl}; // Ensure that SelectAll respects the |reversed| argument regardless of // application locale and text content directionality. @@ -4062,7 +4093,7 @@ // Test the weak, LTR, RTL, and Bidi string cases. for (size_t j = 0; j < base::size(cases); j++) { - render_text->SetText(cases[j]); + render_text->SetText(UTF8ToUTF16(cases[j])); render_text->SelectAll(false); EXPECT_EQ(render_text->selection_model(), expected_forwards); render_text->SelectAll(true); @@ -4075,7 +4106,7 @@ TEST_F(RenderTextTest, MoveCursorLeftRightWithSelection) { RenderText* render_text = GetRenderText(); - render_text->SetText(u"abcאבג"); + render_text->SetText(u"abc\u05d0\u05d1\u05d2"); // Left arrow on select ranging (6, 4). render_text->MoveCursor(LINE_BREAK, CURSOR_RIGHT, SELECTION_NONE); EXPECT_EQ(Range(6), render_text->selection()); @@ -4239,9 +4270,9 @@ render_text->GetUpdatedCursorBounds().right()); } -void MoveLeftRightByWordVerifier(RenderText* render_text, const char16_t* str) { +void MoveLeftRightByWordVerifier(RenderText* render_text, const char* str) { SCOPED_TRACE(str); - const std::u16string str16(str); + const std::u16string str16(UTF8ToUTF16(str)); render_text->SetText(str16); // Test moving by word from left to right. @@ -4313,37 +4344,37 @@ TEST_F(RenderTextTest, MAYBE_MoveLeftRightByWordInBidiText) { RenderText* render_text = GetRenderText(); // For testing simplicity, each word is a 3-character word. - std::vector<const char16_t*> test; - test.push_back(u"abc"); - test.push_back(u"abc def"); - test.push_back(u"\u05E1\u05E2\u05E3"); - test.push_back(u"\u05E1\u05E2\u05E3 \u05E4\u05E5\u05E6"); - test.push_back(u"abc \u05E1\u05E2\u05E3"); - test.push_back(u"abc def \u05E1\u05E2\u05E3 \u05E4\u05E5\u05E6"); + std::vector<const char*> test; + test.push_back("abc"); + test.push_back("abc def"); + test.push_back("\u05E1\u05E2\u05E3"); + test.push_back("\u05E1\u05E2\u05E3 \u05E4\u05E5\u05E6"); + test.push_back("abc \u05E1\u05E2\u05E3"); + test.push_back("abc def \u05E1\u05E2\u05E3 \u05E4\u05E5\u05E6"); test.push_back( - u"abc def hij \u05E1\u05E2\u05E3 \u05E4\u05E5\u05E6" - u" \u05E7\u05E8\u05E9"); + "abc def hij \u05E1\u05E2\u05E3 \u05E4\u05E5\u05E6" + " \u05E7\u05E8\u05E9"); - test.push_back(u"abc \u05E1\u05E2\u05E3 hij"); - test.push_back(u"abc def \u05E1\u05E2\u05E3 \u05E4\u05E5\u05E6 hij opq"); + test.push_back("abc \u05E1\u05E2\u05E3 hij"); + test.push_back("abc def \u05E1\u05E2\u05E3 \u05E4\u05E5\u05E6 hij opq"); test.push_back( - u"abc def hij \u05E1\u05E2\u05E3 \u05E4\u05E5\u05E6" - u" \u05E7\u05E8\u05E9 opq rst uvw"); + "abc def hij \u05E1\u05E2\u05E3 \u05E4\u05E5\u05E6" + " \u05E7\u05E8\u05E9 opq rst uvw"); - test.push_back(u"\u05E1\u05E2\u05E3 abc"); - test.push_back(u"\u05E1\u05E2\u05E3 \u05E4\u05E5\u05E6 abc def"); + test.push_back("\u05E1\u05E2\u05E3 abc"); + test.push_back("\u05E1\u05E2\u05E3 \u05E4\u05E5\u05E6 abc def"); test.push_back( - u"\u05E1\u05E2\u05E3 \u05E4\u05E5\u05E6 \u05E7\u05E8\u05E9" - u" abc def hij"); + "\u05E1\u05E2\u05E3 \u05E4\u05E5\u05E6 \u05E7\u05E8\u05E9" + " abc def hij"); - test.push_back(u"בגד abc \u05E1\u05E2\u05E3"); + test.push_back("\u05D1\u05D2\u05D3 abc \u05E1\u05E2\u05E3"); test.push_back( - u"בגד הוז abc def" - u" \u05E1\u05E2\u05E3 \u05E4\u05E5\u05E6"); + "\u05D1\u05D2\u05D3 \u05D4\u05D5\u05D6 abc def" + " \u05E1\u05E2\u05E3 \u05E4\u05E5\u05E6"); test.push_back( - u"בגד הוז חטי" - u" abc def hij \u05E1\u05E2\u05E3 \u05E4\u05E5\u05E6" - u" \u05E7\u05E8\u05E9"); + "\u05D1\u05D2\u05D3 \u05D4\u05D5\u05D6 \u05D7\u05D8\u05D9" + " abc def hij \u05E1\u05E2\u05E3 \u05E4\u05E5\u05E6" + " \u05E7\u05E8\u05E9"); for (size_t i = 0; i < test.size(); ++i) MoveLeftRightByWordVerifier(render_text, test[i]); @@ -4680,13 +4711,15 @@ Font cjk_font(kCJKFontName, 16); ASSERT_EQ(base::ToLowerASCII(kCJKFontName), base::ToLowerASCII(cjk_font.GetActualFontName())); - Font smaller_font = test_font; - Font larger_font = cjk_font; // "a" should be rendered with the test font, not with the CJK font. - const char16_t* smaller_font_text = u"a"; + const char* test_font_text = "a"; // "円" (U+5168 Han character YEN) should render with the CJK font, not // the test font. - const char16_t* larger_font_text = u"\u5168"; + const char* cjk_font_text = "\u5168"; + Font smaller_font = test_font; + Font larger_font = cjk_font; + const char* smaller_font_text = test_font_text; + const char* larger_font_text = cjk_font_text; if (cjk_font.GetHeight() < test_font.GetHeight() && cjk_font.GetBaseline() < test_font.GetBaseline()) { std::swap(smaller_font, larger_font); @@ -4697,7 +4730,7 @@ // Check |smaller_font_text| is rendered with the smaller font. RenderText* render_text = GetRenderText(); - render_text->SetText(smaller_font_text); + render_text->SetText(UTF8ToUTF16(smaller_font_text)); render_text->SetFontList(FontList(smaller_font)); render_text->SetDisplayRect(Rect(0, 0, 0, render_text->font_list().GetHeight())); @@ -4807,7 +4840,7 @@ RenderText* render_text = GetRenderText(); for (size_t text_length = 0; text_length < 10; ++text_length) { - render_text->SetText(std::u16string(text_length, u'x')); + render_text->SetText(ASCIIToUTF16(std::string(text_length, 'x'))); // Ensures that conversion from float to integer ceils the values. const float expected_width = text_length * kGlyphWidth; @@ -4848,7 +4881,7 @@ if (line != 0) render_text->AppendText(u"\n"); const int text_length = line; - render_text->AppendText(std::u16string(text_length, u'x')); + render_text->AppendText(ASCIIToUTF16(std::string(text_length, 'x'))); // Ensures that conversion from float to integer ceils the values. const float expected_width = text_length * kGlyphWidth; @@ -4912,7 +4945,7 @@ const int kGlyphCount = 3; RenderText* render_text = GetRenderText(); - render_text->SetText(std::u16string(kGlyphCount, u'x')); + render_text->SetText(ASCIIToUTF16(std::string(kGlyphCount, 'x'))); render_text->SetDisplayRect(Rect(1, 1, 25, 12)); render_text->SetCursorEnabled(false); render_text->SetVerticalAlignment(ALIGN_TOP); @@ -5411,18 +5444,18 @@ // Make sure the last word is selected when the cursor is at text.length(). TEST_F(RenderTextTest, LastWordSelected) { - const std::u16string kTestURL1 = u"http://www.google.com"; - const std::u16string kTestURL2 = u"http://www.google.com/something/"; + const std::string kTestURL1 = "http://www.google.com"; + const std::string kTestURL2 = "http://www.google.com/something/"; RenderText* render_text = GetRenderText(); - render_text->SetText(kTestURL1); + render_text->SetText(ASCIIToUTF16(kTestURL1)); render_text->SetCursorPosition(kTestURL1.length()); render_text->SelectWord(); EXPECT_EQ(u"com", GetSelectedText(render_text)); EXPECT_FALSE(render_text->selection().is_reversed()); - render_text->SetText(kTestURL2); + render_text->SetText(ASCIIToUTF16(kTestURL2)); render_text->SetCursorPosition(kTestURL2.length()); render_text->SelectWord(); EXPECT_EQ(u"/", GetSelectedText(render_text)); @@ -5432,11 +5465,11 @@ // When given a non-empty selection, SelectWord should expand the selection to // nearest word boundaries. TEST_F(RenderTextTest, SelectMultipleWords) { - const std::u16string kTestURL = u"http://www.google.com"; + const std::string kTestURL = "http://www.google.com"; RenderText* render_text = GetRenderText(); - render_text->SetText(kTestURL); + render_text->SetText(ASCIIToUTF16(kTestURL)); render_text->SelectRange(Range(16, 20)); render_text->SelectWord(); EXPECT_EQ(u"google.com", GetSelectedText(render_text)); @@ -5478,7 +5511,9 @@ EXPECT_EQ(width, render_text->GetUpdatedCursorBounds().x()); // Repeat the test with RTL text. - render_text->SetText(u"אבגדהוזחטיךכלםמן"); + render_text->SetText( + UTF8ToUTF16("\u05d0\u05d1\u05d2\u05d3\u05d4\u05d5\u05d6\u05d7" + "\u05d8\u05d9\u05da\u05db\u05dc\u05dd\u05de\u05df")); render_text->SetCursorPosition(0); width = render_text->GetStringSize().width(); ASSERT_GT(width, 10); @@ -5534,7 +5569,9 @@ render_text->GetUpdatedCursorBounds().x()); // Repeat the test with RTL text. - render_text->SetText(u"אבגדהוזחטיךכלםמן"); + render_text->SetText( + UTF8ToUTF16("\u05d0\u05d1\u05d2\u05d3\u05d4\u05d5\u05d6\u05d7" + "\u05d8\u05d9\u05da\u05db\u05dc\u05dd\u05de\u05df")); render_text->SetCursorPosition(render_text->text().length()); width = render_text->GetStringSize().width(); ASSERT_GT(width, 10); @@ -5564,12 +5601,12 @@ // Changing colors between or inside ligated glyphs should not break shaping. TEST_F(RenderTextTest, SelectionKeepsLigatures) { - const char16_t* const kTestStrings[] = {u"\u0644\u0623", u"\u0633\u0627"}; + const char* kTestStrings[] = {"\u0644\u0623", "\u0633\u0627"}; RenderText* render_text = GetRenderText(); render_text->set_selection_color(SK_ColorGREEN); for (size_t i = 0; i < base::size(kTestStrings); ++i) { - render_text->SetText(kTestStrings[i]); + render_text->SetText(UTF8ToUTF16(kTestStrings[i])); const int expected_width = render_text->GetStringSize().width(); render_text->SelectRange({0, 1}); EXPECT_EQ(expected_width, render_text->GetStringSize().width()); @@ -5596,8 +5633,7 @@ EXPECT_EQ(std::vector<std::u16string>({ramen_katakana}), RunsFor(ramen_katakana)); - EXPECT_EQ(std::vector<std::u16string>({u"らあ", u"メン"}), - RunsFor(ramen_mixed)); + EXPECT_EQ(ToString16Vec({"らあ", "メン"}), RunsFor(ramen_mixed)); } // Test that whitespace breaks runs of text. E.g. this can permit better fonts @@ -5613,20 +5649,18 @@ // This says "thank you very much" with a full-width non-ascii space (U+3000). const std::u16string full_width_space = u"ども ありがと"; - EXPECT_EQ( - std::vector<std::u16string>({u"סיבית", u" ", u"–", u" ", u"ויקיפדיה"}), - RunsFor(ascii_space_he)); - EXPECT_EQ( - std::vector<std::u16string>({u"Bit", u" ", u"-", u" ", u"Wikipedia"}), - RunsFor(ascii_space_en)); - EXPECT_EQ(std::vector<std::u16string>({u"ども", u" ", u"ありがと"}), + EXPECT_EQ(ToString16Vec({"סיבית", " ", "–", " ", "ויקיפדיה"}), + RunsFor(ascii_space_he)); + EXPECT_EQ(ToString16Vec({"Bit", " ", "-", " ", "Wikipedia"}), + RunsFor(ascii_space_en)); + EXPECT_EQ(ToString16Vec({"ども", " ", "ありがと"}), RunsFor(full_width_space)); } // Ensure strings wrap onto multiple lines for a small available width. TEST_F(RenderTextTest, Multiline_MinWidth) { - const char16_t* kTestStrings[] = {kWeak, kLtr, kLtrRtl, kLtrRtlLtr, - kRtl, kRtlLtr, kRtlLtrRtl}; + const char* kTestStrings[] = {kWeak, kLtr, kLtrRtl, kLtrRtlLtr, + kRtl, kRtlLtr, kRtlLtrRtl}; RenderText* render_text = GetRenderText(); render_text->SetDisplayRect(Rect(1, 1000)); @@ -5635,7 +5669,7 @@ for (size_t i = 0; i < base::size(kTestStrings); ++i) { SCOPED_TRACE(base::StringPrintf("kTestStrings[%" PRIuS "]", i)); - render_text->SetText(kTestStrings[i]); + render_text->SetText(UTF8ToUTF16(kTestStrings[i])); render_text->Draw(canvas()); EXPECT_GT(test_api()->lines().size(), 1U); } @@ -5646,7 +5680,7 @@ // Should RenderText suppress drawing whitespace at the end of a line? // Currently it does not. const struct { - const char16_t* const text; + const char* const text; const Range first_line_char_range; const Range second_line_char_range; @@ -5658,20 +5692,22 @@ bool is_ltr; } kTestStrings[] = { - {u"abc defg hijkl", Range(0, 9), Range(9, 14), {3, 1, 4, 1, 5}, 4, true}, - {u"qwertyzxcvbn", Range(0, 10), Range(10, 12), {10, 2}, 1, true}, + {"abc defg hijkl", Range(0, 9), Range(9, 14), {3, 1, 4, 1, 5}, 4, true}, + {"qwertyzxcvbn", Range(0, 10), Range(10, 12), {10, 2}, 1, true}, // RTL: should render left-to-right as "<space>43210 \n cba9876". // Note this used to say "Arabic language", in Arabic, but the last // character in the string (\u0629) got fancy in an updated Mac font, so // now the penultimate character repeats. (See "NOTE" below). - {u"اللغة العربيي", + {"\u0627\u0644\u0644\u063A\u0629 " + "\u0627\u0644\u0639\u0631\u0628\u064A\u064A", Range(0, 6), Range(6, 13), {1 /* space first */, 5, 7}, 2, false}, // RTL: should render left-to-right as "<space>3210 \n cba98765". - {u"تفاح תפוזיךכם", + {"\u062A\u0641\u0627\u062D \u05EA\u05E4\u05D5\u05D6\u05D9" + "\u05DA\u05DB\u05DD", Range(0, 5), Range(5, 13), {1 /* space first */, 5, 8}, @@ -5690,7 +5726,7 @@ for (size_t i = 0; i < base::size(kTestStrings); ++i) { SCOPED_TRACE(base::StringPrintf("kTestStrings[%" PRIuS "]", i)); - render_text->SetText(kTestStrings[i].text); + render_text->SetText(UTF8ToUTF16(kTestStrings[i].text)); DrawVisualText(); ASSERT_EQ(2U, test_api()->lines().size()); @@ -5724,14 +5760,8 @@ // Ensure strings don't wrap onto multiple lines for a sufficient available // width. TEST_F(RenderTextTest, Multiline_SufficientWidth) { - const char16_t* kTestStrings[] = {u"", - u" ", - u".", - u" . ", - u"abc", - u"a b c", - u"\u062E\u0628\u0632", - u"\u062E \u0628 \u0632"}; + const char* kTestStrings[] = {"", " ", ".", " . ", "abc", "a b c", + "\u062E\u0628\u0632", "\u062E \u0628 \u0632"}; RenderText* render_text = GetRenderText(); render_text->SetDisplayRect(Rect(1000, 1000)); @@ -5739,7 +5769,7 @@ for (size_t i = 0; i < base::size(kTestStrings); ++i) { SCOPED_TRACE(base::StringPrintf("kTestStrings[%" PRIuS "]", i)); - render_text->SetText(kTestStrings[i]); + render_text->SetText(UTF8ToUTF16(kTestStrings[i])); render_text->Draw(canvas()); EXPECT_EQ(1U, test_api()->lines().size()); } @@ -5747,17 +5777,17 @@ TEST_F(RenderTextTest, Multiline_Newline) { const struct { - const char16_t* const text; + const char* const text; const size_t lines_count; // Ranges of the characters on each line. const Range line_char_ranges[3]; } kTestStrings[] = { - {u"abc\ndef", 2ul, {Range(0, 4), Range(4, 7), Range::InvalidRange()}}, - {u"a \n b ", 2ul, {Range(0, 3), Range(3, 6), Range::InvalidRange()}}, - {u"ab\n", 2ul, {Range(0, 3), Range(), Range::InvalidRange()}}, - {u"a\n\nb", 3ul, {Range(0, 2), Range(2, 3), Range(3, 4)}}, - {u"\nab", 2ul, {Range(0, 1), Range(1, 3), Range::InvalidRange()}}, - {u"\n", 2ul, {Range(0, 1), Range(), Range::InvalidRange()}}, + {"abc\ndef", 2ul, {Range(0, 4), Range(4, 7), Range::InvalidRange()}}, + {"a \n b ", 2ul, {Range(0, 3), Range(3, 6), Range::InvalidRange()}}, + {"ab\n", 2ul, {Range(0, 3), Range(), Range::InvalidRange()}}, + {"a\n\nb", 3ul, {Range(0, 2), Range(2, 3), Range(3, 4)}}, + {"\nab", 2ul, {Range(0, 1), Range(1, 3), Range::InvalidRange()}}, + {"\n", 2ul, {Range(0, 1), Range(), Range::InvalidRange()}}, }; RenderText* render_text = GetRenderText(); @@ -5766,7 +5796,7 @@ for (size_t i = 0; i < base::size(kTestStrings); ++i) { SCOPED_TRACE(base::StringPrintf("kTestStrings[%" PRIuS "]", i)); - render_text->SetText(kTestStrings[i].text); + render_text->SetText(UTF8ToUTF16(kTestStrings[i].text)); render_text->Draw(canvas()); EXPECT_EQ(kTestStrings[i].lines_count, test_api()->lines().size()); if (kTestStrings[i].lines_count != test_api()->lines().size()) @@ -5791,20 +5821,23 @@ TEST_F(RenderTextTest, Multiline_IgnoreElide) { const char16_t kTestString[] = u"very very very long string xxxxxxxxxxxxxxxxxxxxxxxxxx"; + const char kEllipsis[] = "\u2026"; RenderText* render_text = GetRenderText(); render_text->SetElideBehavior(ELIDE_TAIL); render_text->SetDisplayRect(Rect(20, 1000)); render_text->SetText(kTestString); - EXPECT_NE(std::u16string::npos, render_text->GetDisplayText().find(u"…")); + EXPECT_NE(std::u16string::npos, + render_text->GetDisplayText().find(base::UTF8ToUTF16(kEllipsis))); render_text->SetMultiline(true); - EXPECT_EQ(std::u16string::npos, render_text->GetDisplayText().find(u"…")); + EXPECT_EQ(std::u16string::npos, + render_text->GetDisplayText().find(base::UTF8ToUTF16(kEllipsis))); } TEST_F(RenderTextTest, Multiline_NewlineCharacterReplacement) { - const char16_t* kTestStrings[] = { - u"abc\ndef", u"a \n b ", u"ab\n", u"a\n\nb", u"\nab", u"\n", + const char* kTestStrings[] = { + "abc\ndef", "a \n b ", "ab\n", "a\n\nb", "\nab", "\n", }; for (size_t i = 0; i < base::size(kTestStrings); ++i) { @@ -5812,45 +5845,49 @@ ResetRenderTextInstance(); RenderText* render_text = GetRenderText(); render_text->SetDisplayRect(Rect(200, 1000)); - render_text->SetText(kTestStrings[i]); + render_text->SetText(ASCIIToUTF16(kTestStrings[i])); std::u16string display_text = render_text->GetDisplayText(); // If RenderText is not multiline, the newline characters are replaced // by symbols, therefore the character should be changed. - EXPECT_NE(kTestStrings[i], render_text->GetDisplayText()); + EXPECT_NE(ASCIIToUTF16(kTestStrings[i]), render_text->GetDisplayText()); // Setting multiline will fix this, the newline characters will be back // to the original text. render_text->SetMultiline(true); - EXPECT_EQ(kTestStrings[i], render_text->GetDisplayText()); + EXPECT_EQ(ASCIIToUTF16(kTestStrings[i]), render_text->GetDisplayText()); } } // Ensure horizontal alignment works in multiline mode. TEST_F(RenderTextTest, Multiline_HorizontalAlignment) { constexpr struct { - const char16_t* const text; + const char* const text; const HorizontalAlignment alignment; const base::i18n::TextDirection display_text_direction; } kTestStrings[] = { - {u"abcdefghi\nhijk", ALIGN_LEFT, base::i18n::LEFT_TO_RIGHT}, - {u"nhij\nabcdefghi", ALIGN_LEFT, base::i18n::LEFT_TO_RIGHT}, + {"abcdefghi\nhijk", ALIGN_LEFT, base::i18n::LEFT_TO_RIGHT}, + {"nhij\nabcdefghi", ALIGN_LEFT, base::i18n::LEFT_TO_RIGHT}, // Hebrew, 2nd line shorter - {u"אבגדהוזח\n" - u"אבגד", - ALIGN_RIGHT, base::i18n::RIGHT_TO_LEFT}, + {"\u05d0\u05d1\u05d2\u05d3\u05d4\u05d5\u05d6\u05d7\n" + "\u05d0\u05d1\u05d2\u05d3", + ALIGN_RIGHT, + base::i18n::RIGHT_TO_LEFT}, // Hebrew, 2nd line longer - {u"אבגד\n" - u"אבגדהוזח", - ALIGN_RIGHT, base::i18n::RIGHT_TO_LEFT}, + {"\u05d0\u05d1\u05d2\u05d3\n" + "\u05d0\u05d1\u05d2\u05d3\u05d4\u05d5\u05d6\u05d7", + ALIGN_RIGHT, + base::i18n::RIGHT_TO_LEFT}, // Arabic, 2nd line shorter. - {u"\u0627\u0627\u0627\u0627\u0627\u0627\u0627\u0627\n" - u"\u0627\u0644\u0644\u063A", - ALIGN_RIGHT, base::i18n::RIGHT_TO_LEFT}, + {"\u0627\u0627\u0627\u0627\u0627\u0627\u0627\u0627\n" + "\u0627\u0644\u0644\u063A", + ALIGN_RIGHT, + base::i18n::RIGHT_TO_LEFT}, // Arabic, 2nd line longer. - {u"\u0627\u0644\u0644\u063A\n" - u"\u0627\u0627\u0627\u0627\u0627\u0627\u0627\u0627", - ALIGN_RIGHT, base::i18n::RIGHT_TO_LEFT}, + {"\u0627\u0644\u0644\u063A\n" + "\u0627\u0627\u0627\u0627\u0627\u0627\u0627\u0627", + ALIGN_RIGHT, + base::i18n::RIGHT_TO_LEFT}, }; const int kGlyphSize = 5; RenderTextHarfBuzz* render_text = GetRenderText(); @@ -5862,7 +5899,7 @@ for (size_t i = 0; i < base::size(kTestStrings); ++i) { SCOPED_TRACE(testing::Message("kTestStrings[") << i << "] = " << kTestStrings[i].text); - render_text->SetText(kTestStrings[i].text); + render_text->SetText(UTF8ToUTF16(kTestStrings[i].text)); EXPECT_EQ(kTestStrings[i].display_text_direction, render_text->GetDisplayTextDirection()); render_text->Draw(canvas()); @@ -5871,9 +5908,9 @@ EXPECT_EQ(0, test_api()->GetAlignmentOffset(0).x()); EXPECT_EQ(0, test_api()->GetAlignmentOffset(1).x()); } else { - std::vector<std::u16string> lines = - base::SplitString(kTestStrings[i].text, std::u16string(1, '\n'), - base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); + std::vector<std::u16string> lines = base::SplitString( + base::UTF8ToUTF16(kTestStrings[i].text), std::u16string(1, '\n'), + base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); ASSERT_EQ(2u, lines.size()); // Sanity check the input string lengths match the glyph lengths. @@ -5933,46 +5970,36 @@ TEST_F(RenderTextTest, Multiline_LineBreakerBehavior) { const int kGlyphSize = 5; const struct { - const char16_t* const text; + const char* const text; const WordWrapBehavior behavior; const Range char_ranges[3]; } kTestScenarios[] = { - {u"a single run", + {"a single run", IGNORE_LONG_WORDS, {Range(0, 2), Range(2, 9), Range(9, 12)}}, // 3 words: "That's ", ""good". ", "aaa" and 7 runs: "That", "'", "s ", // """, "good", "". ", "aaa". They all mixed together. - {u"That's \"good\". aaa", - IGNORE_LONG_WORDS, + {"That's \"good\". aaa", IGNORE_LONG_WORDS, {Range(0, 7), Range(7, 15), Range(15, 18)}}, // Test "\"" should be put into a new line correctly. - {u"a \"good\" one.", - IGNORE_LONG_WORDS, + {"a \"good\" one.", IGNORE_LONG_WORDS, {Range(0, 2), Range(2, 9), Range(9, 13)}}, // Test for full-width space. - {u"That's\u3000good.\u3000yyy", - IGNORE_LONG_WORDS, + {"That's\u3000good.\u3000yyy", IGNORE_LONG_WORDS, {Range(0, 7), Range(7, 13), Range(13, 16)}}, - {u"a single run", - TRUNCATE_LONG_WORDS, + {"a single run", TRUNCATE_LONG_WORDS, {Range(0, 2), Range(2, 6), Range(9, 12)}}, - {u"That's \"good\". aaa", - TRUNCATE_LONG_WORDS, + {"That's \"good\". aaa", TRUNCATE_LONG_WORDS, {Range(0, 4), Range(7, 11), Range(15, 18)}}, - {u"That's good. aaa", - TRUNCATE_LONG_WORDS, + {"That's good. aaa", TRUNCATE_LONG_WORDS, {Range(0, 4), Range(7, 11), Range(13, 16)}}, - {u"a \"good\" one.", - TRUNCATE_LONG_WORDS, + {"a \"good\" one.", TRUNCATE_LONG_WORDS, {Range(0, 2), Range(2, 6), Range(9, 13)}}, - {u"asingleword", - WRAP_LONG_WORDS, + {"asingleword", WRAP_LONG_WORDS, {Range(0, 4), Range(4, 8), Range(8, 11)}}, - {u"That's good", - WRAP_LONG_WORDS, + {"That's good", WRAP_LONG_WORDS, {Range(0, 4), Range(4, 7), Range(7, 11)}}, - {u"That's \"g\".", - WRAP_LONG_WORDS, + {"That's \"g\".", WRAP_LONG_WORDS, {Range(0, 4), Range(4, 7), Range(7, 11)}}, }; @@ -5983,7 +6010,7 @@ for (size_t i = 0; i < base::size(kTestScenarios); ++i) { SCOPED_TRACE(base::StringPrintf("kTestStrings[%" PRIuS "]", i)); - render_text->SetText(kTestScenarios[i].text); + render_text->SetText(UTF8ToUTF16(kTestScenarios[i].text)); render_text->SetWordWrapBehavior(kTestScenarios[i].behavior); render_text->Draw(canvas()); @@ -6153,8 +6180,8 @@ } TEST_F(RenderTextTest, NewlineWithoutMultilineFlag) { - const char16_t* kTestStrings[] = { - u"abc\ndef", u"a \n b ", u"ab\n", u"a\n\nb", u"\nab", u"\n", + const char* kTestStrings[] = { + "abc\ndef", "a \n b ", "ab\n", "a\n\nb", "\nab", "\n", }; RenderText* render_text = GetRenderText(); @@ -6162,7 +6189,7 @@ for (size_t i = 0; i < base::size(kTestStrings); ++i) { SCOPED_TRACE(base::StringPrintf("kTestStrings[%" PRIuS "]", i)); - render_text->SetText(kTestStrings[i]); + render_text->SetText(ASCIIToUTF16(kTestStrings[i])); render_text->Draw(canvas()); EXPECT_EQ(1U, test_api()->lines().size()); @@ -6224,18 +6251,18 @@ // LTR languages and right-to-left for RTL languages). TEST_F(RenderTextTest, HarfBuzz_HorizontalPositions) { const struct { - const char16_t* const text; + const char* const text; const char* expected_runs; } kTestStrings[] = { - {u"abc\u3042\u3044\u3046\u3048\u304A", "[0->2][3->7]"}, - {u"\u062A\u0641\u0627\u062D\u05EA\u05E4וז", "[7<-4][3<-0]"}, + {"abc\u3042\u3044\u3046\u3048\u304A", "[0->2][3->7]"}, + {"\u062A\u0641\u0627\u062D\u05EA\u05E4\u05D5\u05D6", "[7<-4][3<-0]"}, }; RenderTextHarfBuzz* render_text = GetRenderText(); for (size_t i = 0; i < base::size(kTestStrings); ++i) { SCOPED_TRACE(base::StringPrintf("kTestStrings[%" PRIuS "]", i)); - render_text->SetText(kTestStrings[i].text); + render_text->SetText(UTF8ToUTF16(kTestStrings[i].text)); EXPECT_EQ(kTestStrings[i].expected_runs, GetRunListStructureString()); @@ -6328,13 +6355,13 @@ // Ensure that graphemes with multiple code points do not get split. TEST_F(RenderTextTest, HarfBuzz_SubglyphGraphemeCases) { - const char16_t* cases[] = { + const char* cases[] = { // Ä (A with combining umlaut), followed by a "B". - u"A\u0308B", + "A\u0308B", // कि (Devangari letter KA with vowel I), followed by an "a". - u"\u0915\u093f\u0905", - // จำ (Thai characters CHO CHAN and SARA AM, followed by Thai digit 0. - u"\u0e08\u0e33\u0E50", + "\u0915\u093f\u0905", + // จำ (Thai charcters CHO CHAN and SARA AM, followed by Thai digit 0. + "\u0e08\u0e33\u0E50", }; RenderTextHarfBuzz* render_text = GetRenderText(); @@ -6342,7 +6369,7 @@ for (size_t i = 0; i < base::size(cases); ++i) { SCOPED_TRACE(base::StringPrintf("Case %" PRIuS, i)); - std::u16string text = cases[i]; + std::u16string text = UTF8ToUTF16(cases[i]); render_text->SetText(text); const internal::TextRunList* run_list = GetHarfBuzzRunList(); ASSERT_EQ(1U, run_list->size()); @@ -6412,7 +6439,7 @@ TEST_F(RenderTextTest, HarfBuzz_RunDirection) { RenderTextHarfBuzz* render_text = GetRenderText(); - const std::u16string mixed = u"אב1234גדabc"; + const std::u16string mixed = u"\u05D0\u05D11234\u05D2\u05D3abc"; render_text->SetText(mixed); // Get the run list for both display directions. @@ -6427,9 +6454,9 @@ RenderTextHarfBuzz* render_text = GetRenderText(); // This string, unescaped (logical order): // www.אב.גד/הוabc/def?זח=טי - const std::u16string mixed = - u"www.אב.גד/הו" - u"abc/def?זח=טי"; + const std::u16string mixed = UTF8ToUTF16( + "www.\u05D0\u05D1.\u05D2\u05D3/\u05D4\u05D5" + "abc/def?\u05D6\u05D7=\u05D8\u05D9"); render_text->SetText(mixed); // Normal LTR text should treat URL syntax as weak (as per the normal Bidi @@ -6455,13 +6482,11 @@ // The ▶ (U+25B6) "play character" should break runs. http://crbug.com/278913 render_text->SetText(u"x\u25B6y"); - EXPECT_EQ(std::vector<std::u16string>({u"x", u"▶", u"y"}), - GetRunListStrings()); + EXPECT_EQ(ToString16Vec({"x", "▶", "y"}), GetRunListStrings()); EXPECT_EQ("[0][1][2]", GetRunListStructureString()); render_text->SetText(u"x \u25B6 y"); - EXPECT_EQ(std::vector<std::u16string>({u"x", u" ", u"▶", u" ", u"y"}), - GetRunListStrings()); + EXPECT_EQ(ToString16Vec({"x", " ", "▶", " ", "y"}), GetRunListStrings()); EXPECT_EQ("[0][1][2][3][4]", GetRunListStructureString()); } @@ -6472,15 +6497,13 @@ // drawn with color emoji fonts, so runs should be separated. crbug.com/448909 // Windows requires wide strings for \Unnnnnnnn universal character names. render_text->SetText(u"x\U0001F601y\u2728"); - EXPECT_EQ(std::vector<std::u16string>({u"x", u"😁", u"y", u"✨"}), - GetRunListStrings()); + EXPECT_EQ(ToString16Vec({"x", "😁", "y", "✨"}), GetRunListStrings()); // U+1F601 is represented as a surrogate pair in UTF-16. EXPECT_EQ("[0][1->2][3][4]", GetRunListStructureString()); // Ensure non-latin 「foo」 brackets around Emoji correctly break runs. render_text->SetText(u"「🦋」「"); - EXPECT_EQ(std::vector<std::u16string>({u"「", u"🦋", u"」「"}), - GetRunListStrings()); + EXPECT_EQ(ToString16Vec({"「", "🦋", "」「"}), GetRunListStrings()); // Note 🦋 is a surrogate pair [1->2]. EXPECT_EQ("[0][1->2][3->4]", GetRunListStructureString()); } @@ -6489,8 +6512,7 @@ RenderText* render_text = GetRenderText(); render_text->SetMultiline(true); render_text->SetText(u"x\ny"); - EXPECT_EQ(std::vector<std::u16string>({u"x", u"\n", u"y"}), - GetRunListStrings()); + EXPECT_EQ(ToString16Vec({"x", "\n", "y"}), GetRunListStrings()); EXPECT_EQ("[0][1][2]", GetRunListStructureString()); // Validate that the character newline is an unknown glyph @@ -6525,8 +6547,7 @@ // not break between the codepoints, or the incorrect glyph will be chosen. render_text->SetText(u"z\u260E\uFE0Fy"); render_text->SetDisplayRect(Rect(1000, 50)); - EXPECT_EQ(std::vector<std::u16string>({u"z", u"☎\uFE0F", u"y"}), - GetRunListStrings()); + EXPECT_EQ(ToString16Vec({"z", "☎\uFE0F", "y"}), GetRunListStrings()); EXPECT_EQ("[0][1->2][3]", GetRunListStructureString()); // Also test moving the cursor across the telephone. @@ -6567,7 +6588,7 @@ // It should never happen in normal usage, but a variation selector can appear // by itself. In this case, it can form its own text run, with no glyphs. render_text->SetText(u"\uFE0F"); - EXPECT_EQ(std::vector<std::u16string>({u"\uFE0F"}), GetRunListStrings()); + EXPECT_EQ(ToString16Vec({"\uFE0F"}), GetRunListStrings()); EXPECT_EQ("[0]", GetRunListStructureString()); CheckBoundsForCursorPositions(); } @@ -6583,7 +6604,7 @@ // cause the typesetter to render tofu in this case, but it should not break // a text run. render_text->SetText(u"z\uFE0Fy"); - EXPECT_EQ(std::vector<std::u16string>({u"z\uFE0Fy"}), GetRunListStrings()); + EXPECT_EQ(ToString16Vec({"z\uFE0Fy"}), GetRunListStrings()); EXPECT_EQ("[0->2]", GetRunListStructureString()); CheckBoundsForCursorPositions(); } @@ -6594,8 +6615,7 @@ // When a variation selector appears either side of an emoji, ensure the one // after is in the same run. render_text->SetText(u"\uFE0F\u260E\uFE0Fy"); - EXPECT_EQ(std::vector<std::u16string>({u"\uFE0F", u"☎\uFE0F", u"y"}), - GetRunListStrings()); + EXPECT_EQ(ToString16Vec({"\uFE0F", "☎\uFE0F", "y"}), GetRunListStrings()); EXPECT_EQ("[0][1->2][3]", GetRunListStructureString()); CheckBoundsForCursorPositions(); } @@ -6608,8 +6628,7 @@ // ultimately up to the typeface but, however it choses, cursor and glyph // positions should behave. render_text->SetText(u"z\u260E\uFE0F\uFE0Fy"); - EXPECT_EQ(std::vector<std::u16string>({u"z", u"☎\uFE0F\uFE0F", u"y"}), - GetRunListStrings()); + EXPECT_EQ(ToString16Vec({"z", "☎\uFE0F\uFE0F", "y"}), GetRunListStrings()); EXPECT_EQ("[0][1->3][4]", GetRunListStructureString()); CheckBoundsForCursorPositions(); } @@ -6620,8 +6639,7 @@ // Two emoji with variation selectors appearing in a correct sequence should // be in the same run. render_text->SetText(u"z\u260E\uFE0F\u260E\uFE0Fy"); - EXPECT_EQ(std::vector<std::u16string>({u"z", u"☎\uFE0F☎\uFE0F", u"y"}), - GetRunListStrings()); + EXPECT_EQ(ToString16Vec({"z", "☎\uFE0F☎\uFE0F", "y"}), GetRunListStrings()); EXPECT_EQ("[0][1->4][5]", GetRunListStructureString()); CheckBoundsForCursorPositions(); } @@ -6632,26 +6650,26 @@ // ▶ (U+25B6, Geometric Shapes) and an ascii character should have // different runs. render_text->SetText(u"▶z"); - EXPECT_EQ(std::vector<std::u16string>({u"▶", u"z"}), GetRunListStrings()); + EXPECT_EQ(ToString16Vec({"▶", "z"}), GetRunListStrings()); EXPECT_EQ("[0][1]", GetRunListStructureString()); // ★ (U+2605, Miscellaneous Symbols) and an ascii character should have // different runs. render_text->SetText(u"★1"); - EXPECT_EQ(std::vector<std::u16string>({u"★", u"1"}), GetRunListStrings()); + EXPECT_EQ(ToString16Vec({"★", "1"}), GetRunListStrings()); EXPECT_EQ("[0][1]", GetRunListStructureString()); // 🐱 (U+1F431, a cat face, Miscellaneous Symbols and Pictographs) and an // ASCII period should have separate runs. render_text->SetText(u"🐱."); - EXPECT_EQ(std::vector<std::u16string>({u"🐱", u"."}), GetRunListStrings()); + EXPECT_EQ(ToString16Vec({"🐱", "."}), GetRunListStrings()); // U+1F431 is represented as a surrogate pair in UTF-16. EXPECT_EQ("[0->1][2]", GetRunListStructureString()); // 🥴 (U+1f974, Supplemental Symbols and Pictographs) and an ascii character // should have different runs. render_text->SetText(u"🥴$"); - EXPECT_EQ(std::vector<std::u16string>({u"🥴", u"$"}), GetRunListStrings()); + EXPECT_EQ(ToString16Vec({"🥴", "$"}), GetRunListStrings()); EXPECT_EQ("[0->1][2]", GetRunListStructureString()); } @@ -6715,12 +6733,12 @@ } TEST_F(RenderTextTest, GlyphBounds) { - const char16_t* kTestStrings[] = {u"asdf 1234 qwer", u"\u0647\u0654", - u"\u0645\u0631\u062D\u0628\u0627"}; + const char* kTestStrings[] = {"asdf 1234 qwer", "\u0647\u0654", + "\u0645\u0631\u062D\u0628\u0627"}; RenderText* render_text = GetRenderText(); for (size_t i = 0; i < base::size(kTestStrings); ++i) { - render_text->SetText(kTestStrings[i]); + render_text->SetText(UTF8ToUTF16(kTestStrings[i])); for (size_t j = 0; j < render_text->text().length(); ++j) EXPECT_FALSE(render_text->GetCursorSpan(Range(j, j + 1)).is_empty()); @@ -6834,13 +6852,13 @@ // for different languages. TEST_F(RenderTextTest, HarfBuzz_FallbackFontsSupportGlyphs) { // The word 'test' in different languages. - static const char16_t* kLanguageTests[] = { - u"test", u"اختبار", u"Δοκιμή", u"परीक्षा", u"تست", u"Փորձարկում", + static const wchar_t* kLanguageTests[] = { + L"test", L"اختبار", L"Δοκιμή", L"परीक्षा", L"تست", L"Փորձարկում", }; - for (const auto* text : kLanguageTests) { + for (const wchar_t* text : kLanguageTests) { RenderTextHarfBuzz* render_text = GetRenderText(); - render_text->SetText(text); + render_text->SetText(WideToUTF16(text)); const internal::TextRunList* run_list = GetHarfBuzzRunList(); ASSERT_EQ(1U, run_list->size()); @@ -6855,15 +6873,15 @@ // Ensure that the fallback fonts offered by GetFallbackFont() support glyphs // for different languages. TEST_F(RenderTextTest, HarfBuzz_MultiRunsSupportGlyphs) { - static const char16_t* kLanguageTests[] = { - u"www.اختبار.com", - u"(اختبار)", - u"/ זה (מבחן) /", + static const wchar_t* kLanguageTests[] = { + L"www.اختبار.com", + L"(اختبار)", + L"/ זה (מבחן) /", }; - for (const auto* text : kLanguageTests) { + for (const wchar_t* text : kLanguageTests) { RenderTextHarfBuzz* render_text = GetRenderText(); - render_text->SetText(text); + render_text->SetText(WideToUTF16(text)); int missing_glyphs = 0; const internal::TextRunList* run_list = GetHarfBuzzRunList(); @@ -6879,7 +6897,7 @@ struct FallbackFontCase { const char* test_name; - const char16_t* text; + const wchar_t* text; }; class RenderTextTestWithFallbackFontCase @@ -6895,7 +6913,7 @@ TEST_P(RenderTextTestWithFallbackFontCase, FallbackFont) { FallbackFontCase param = GetParam(); RenderTextHarfBuzz* render_text = GetRenderText(); - render_text->SetText(param.text); + render_text->SetText(WideToUTF16(param.text)); int missing_glyphs = 0; const internal::TextRunList* run_list = GetHarfBuzzRunList(); @@ -6907,17 +6925,17 @@ const FallbackFontCase kUnicodeDecomposeCases[] = { // Decompose to "\u0041\u0300". - {"letter_A_with_grave", u"\u00c0"}, + {"letter_A_with_grave", L"\u00c0"}, // Decompose to "\u004f\u0328\u0304". - {"letter_O_with_ogonek_macron", u"\u01ec"}, + {"letter_O_with_ogonek_macron", L"\u01ec"}, // Decompose to "\u0041\u030a". - {"angstrom_sign", u"\u212b"}, + {"angstrom_sign", L"\u212b"}, // Decompose to "\u1100\u1164\u11b6". - {"hangul_syllable_gyaelh", u"\uac63"}, + {"hangul_syllable_gyaelh", L"\uac63"}, // Decompose to "\u1107\u1170\u11af". - {"hangul_syllable_bwel", u"\ubdc0"}, + {"hangul_syllable_bwel", L"\ubdc0"}, // Decompose to "\U00044039". - {"cjk_ideograph_fad4", u"\ufad4"}, + {"cjk_ideograph_fad4", L"\ufad4"}, }; INSTANTIATE_TEST_SUITE_P(FallbackFontUnicodeDecompose, @@ -6929,64 +6947,64 @@ // codepoint can be rendered by the font. An error here can be by an incorrect // ItemizeText(...) leading to an invalid fallback font. const FallbackFontCase kComplexTextCases[] = { - {"simple1", u"test"}, - {"simple2", u"اختبار"}, - {"simple3", u"Δοκιμή"}, - {"simple4", u"परीक्षा"}, - {"simple5", u"تست"}, - {"simple6", u"Փորձարկում"}, - {"mixed1", u"www.اختبار.com"}, - {"mixed2", u"(اختبار)"}, - {"mixed3", u"/ זה (מבחן) /"}, + {"simple1", L"test"}, + {"simple2", L"اختبار"}, + {"simple3", L"Δοκιμή"}, + {"simple4", L"परीक्षा"}, + {"simple5", L"تست"}, + {"simple6", L"Փորձարկում"}, + {"mixed1", L"www.اختبار.com"}, + {"mixed2", L"(اختبار)"}, + {"mixed3", L"/ זה (מבחן) /"}, #if defined(OS_WIN) - {"asc_arb", u"abcښڛڜdef"}, - {"devanagari", u"ञटठडढणतथ"}, - {"ethiopic", u"መጩጪᎅⶹⶼ"}, - {"greek", u"ξοπρς"}, - {"kannada", u"ಠಡಢಣತಥ"}, - {"lao", u"ປຝພຟມ"}, - {"oriya", u"ଔକଖଗଘଙ"}, - {"telugu_lat", u"aaఉయ!"}, - {"common_math", u"ℳ: ¬ƒ(x)=½×¾"}, - {"picto_title", u"☞☛test☚☜"}, - {"common_numbers", u"𝟭𝟐⒓¹²"}, - {"common_puncts", u",.!"}, - {"common_space_math1", u" 𝓐"}, - {"common_space_math2", u" 𝓉"}, - {"common_split_spaces", u"♬ 𝓐"}, - {"common_mixed", u"\U0001d4c9\u24d4\U0001d42c"}, - {"arrows", u"↰↱↲↳↴↵⇚⇛⇜⇝⇞⇟"}, - {"arrows_space", u"↰ ↱ ↲ ↳ ↴ ↵ ⇚ ⇛ ⇜ ⇝ ⇞ ⇟"}, - {"emoji_title", u"▶Feel goods"}, - {"enclosed_alpha", u"ⒶⒷⒸⒹⒺⒻⒼ"}, - {"shapes", u" ▶▷▸▹►▻◀◁◂◃◄◅"}, - {"symbols", u"☂☎☏☝☫☬☭☮☯"}, - {"symbols_space", u"☂ ☎ ☏ ☝ ☫ ☬ ☭ ☮ ☯"}, - {"dingbats", u"✂✃✄✆✇✈"}, - {"cjk_compatibility_ideographs", u"賈滑串句龜"}, - {"lat_dev_ZWNJ", u"a\u200Cक"}, - {"paren_picto", u"(☾☹☽)"}, - {"emoji1", u"This is 💩!"}, - {"emoji2", u"Look [🔝]"}, - {"strange1", u"💔♬ 𝓐 𝓉ⓔ𝐬т FỖ𝕣 c卄尺𝕆ᵐ€ ♘👹"}, - {"strange2", u"˜”*°•.˜”*°• A test for chrome •°*”˜.•°*”˜"}, - {"strange3", u"𝐭єⓢт fσ𝐑 𝔠ʰ𝕣ό𝐌𝔢"}, - {"strange4", u"тẸⓈ𝔱 𝔽𝕠ᖇ 𝕔𝐡ŕ𝔬ⓜẸ"}, - {"url1", u"http://www.google.com"}, - {"url2", u"http://www.nowhere.com/Lörick.html"}, - {"url3", u"http://www.nowhere.com/تسجيل الدخول"}, - {"url4", u"https://xyz.com:8080/تس(1)جيل الدخول"}, - {"url5", u"http://www.script.com/test.php?abc=42&cde=12&f=%20%20"}, - {"punct1", u"This‐is‑a‒test–for—punctuations"}, - {"punct2", u"⁅All ‷magic‴ comes with a ‶price″⁆"}, - {"punct3", u"⍟ Complete my sentence… †"}, - {"parens", u"❝This❞ 「test」 has ((a)) 【lot】 [{of}] 〚parentheses〛"}, - {"games", u"Let play: ♗♘⚀⚁♠♣"}, - {"braille", u"⠞⠑⠎⠞ ⠋⠕⠗ ⠉⠓⠗⠕⠍⠑"}, - {"emoticon1", u"¯\\_(ツ)_/¯"}, - {"emoticon2", u"٩(⁎❛ᴗ❛⁎)۶"}, - {"emoticon3", u"(͡° ͜ʖ ͡°)"}, - {"emoticon4", u"[̲̅$̲̅(̲̅5̲̅)̲̅$̲̅]"}, + {"asc_arb", L"abcښڛڜdef"}, + {"devanagari", L"ञटठडढणतथ"}, + {"ethiopic", L"መጩጪᎅⶹⶼ"}, + {"greek", L"ξοπρς"}, + {"kannada", L"ಠಡಢಣತಥ"}, + {"lao", L"ປຝພຟມ"}, + {"oriya", L"ଔକଖଗଘଙ"}, + {"telugu_lat", L"aaఉయ!"}, + {"common_math", L"ℳ: ¬ƒ(x)=½×¾"}, + {"picto_title", L"☞☛test☚☜"}, + {"common_numbers", L"𝟭𝟐⒓¹²"}, + {"common_puncts", L",.!"}, + {"common_space_math1", L" 𝓐"}, + {"common_space_math2", L" 𝓉"}, + {"common_split_spaces", L"♬ 𝓐"}, + {"common_mixed", L"\U0001d4c9\u24d4\U0001d42c"}, + {"arrows", L"↰↱↲↳↴↵⇚⇛⇜⇝⇞⇟"}, + {"arrows_space", L"↰ ↱ ↲ ↳ ↴ ↵ ⇚ ⇛ ⇜ ⇝ ⇞ ⇟"}, + {"emoji_title", L"▶Feel goods"}, + {"enclosed_alpha", L"ⒶⒷⒸⒹⒺⒻⒼ"}, + {"shapes", L" ▶▷▸▹►▻◀◁◂◃◄◅"}, + {"symbols", L"☂☎☏☝☫☬☭☮☯"}, + {"symbols_space", L"☂ ☎ ☏ ☝ ☫ ☬ ☭ ☮ ☯"}, + {"dingbats", L"✂✃✄✆✇✈"}, + {"cjk_compatibility_ideographs", L"賈滑串句龜"}, + {"lat_dev_ZWNJ", L"a\u200Cक"}, + {"paren_picto", L"(☾☹☽)"}, + {"emoji1", L"This is 💩!"}, + {"emoji2", L"Look [🔝]"}, + {"strange1", L"💔♬ 𝓐 𝓉ⓔ𝐬т FỖ𝕣 c卄尺𝕆ᵐ€ ♘👹"}, + {"strange2", L"˜”*°•.˜”*°• A test for chrome •°*”˜.•°*”˜"}, + {"strange3", L"𝐭єⓢт fσ𝐑 𝔠ʰ𝕣ό𝐌𝔢"}, + {"strange4", L"тẸⓈ𝔱 𝔽𝕠ᖇ 𝕔𝐡ŕ𝔬ⓜẸ"}, + {"url1", L"http://www.google.com"}, + {"url2", L"http://www.nowhere.com/Lörick.html"}, + {"url3", L"http://www.nowhere.com/تسجيل الدخول"}, + {"url4", L"https://xyz.com:8080/تس(1)جيل الدخول"}, + {"url5", L"http://www.script.com/test.php?abc=42&cde=12&f=%20%20"}, + {"punct1", L"This‐is‑a‒test–for—punctuations"}, + {"punct2", L"⁅All ‷magic‴ comes with a ‶price″⁆"}, + {"punct3", L"⍟ Complete my sentence… †"}, + {"parens", L"❝This❞ 「test」 has ((a)) 【lot】 [{of}] 〚parentheses〛"}, + {"games", L"Let play: ♗♘⚀⚁♠♣"}, + {"braille", L"⠞⠑⠎⠞ ⠋⠕⠗ ⠉⠓⠗⠕⠍⠑"}, + {"emoticon1", L"¯\\_(ツ)_/¯"}, + {"emoticon2", L"٩(⁎❛ᴗ❛⁎)۶"}, + {"emoticon3", L"(͡° ͜ʖ ͡°)"}, + {"emoticon4", L"[̲̅$̲̅(̲̅5̲̅)̲̅$̲̅]"}, #endif }; @@ -7001,110 +7019,110 @@ const FallbackFontCase kCommonScriptCases[] = { #if defined(OS_WIN) // The following tests are made to work on win7 and win10. - {"common00", u"\u237b\u2ac1\u24f5\u259f\u2a87\u23ea\u25d4\u2220"}, - {"common01", u"\u2303\u2074\u2988\u32b6\u26a2\u24e5\u2a53\u2219"}, - {"common02", u"\u29b2\u25fc\u2366\u24ae\u2647\u258e\u2654\u25fe"}, - {"common03", u"\u21ea\u22b4\u29b0\u2a84\u0008\u2657\u2731\u2697"}, - {"common04", u"\u2b3c\u2932\u21c8\u23cf\u20a1\u2aa2\u2344\u0011"}, - {"common05", u"\u22c3\u2a56\u2340\u21b7\u26ba\u2798\u220f\u2404"}, - {"common06", u"\u21f9\u25fd\u008e\u21e6\u2686\u21e4\u259f\u29ee"}, - {"common07", u"\u231e\ufe39\u0008\u2349\u2262\u2270\uff09\u2b3b"}, - {"common08", u"\u24a3\u236e\u29b2\u2259\u26ea\u2705\u00ae\u2a23"}, - {"common09", u"\u33bd\u235e\u2018\u32ba\u2973\u02c1\u20b9\u25b4"}, - {"common10", u"\u2245\u2a4d\uff19\u2042\u2aa9\u2658\u276e\uff40"}, - {"common11", u"\u0007\u21b4\u23c9\u2593\u21ba\u00a0\u258f\u23b3"}, - {"common12", u"\u2938\u250c\u2240\u2676\u2297\u2b07\u237e\u2a04"}, - {"common13", u"\u2520\u233a\u20a5\u2744\u2445\u268a\u2716\ufe62"}, - {"common14", u"\ufe4d\u25d5\u2ae1\u2a35\u2323\u273c\u26be\u2a3b"}, - {"common15", u"\u2aa2\u0000\ufe65\u2962\u2573\u21f8\u2651\u02d2"}, - {"common16", u"\u225c\u2283\u2960\u4de7\uff12\uffe1\u0016\u2905"}, - {"common17", u"\uff07\u25aa\u2076\u259e\u226c\u2568\u0026\u2691"}, - {"common18", u"\u2388\u21c2\u208d\u2a7f\u22d0\u2583\u2ad5\u240f"}, - {"common19", u"\u230a\u27ac\u001e\u261e\u259d\u25c3\u33a5\u0011"}, - {"common20", u"\ufe54\u29c7\u2477\u21ed\u2069\u4dfc\u2ae2\u21e8"}, - {"common21", u"\u2131\u2ab7\u23b9\u2660\u2083\u24c7\u228d\u2a01"}, - {"common22", u"\u2587\u2572\u21df\uff3c\u02cd\ufffd\u2404\u22b3"}, - {"common23", u"\u4dc3\u02fe\uff09\u25a3\ufe14\u255c\u2128\u2698"}, - {"common24", u"\u2b36\u3382\u02f6\u2752\uff16\u22cf\u00b0\u21d6"}, - {"common25", u"\u2561\u23db\u2958\u2782\u22af\u2621\u24a3\u29ae"}, - {"common26", u"\u2693\u22e2\u2988\u2987\u33ba\u2a94\u298e\u2328"}, - {"common27", u"\u266c\u2aa5\u2405\uffeb\uff5c\u2902\u291e\u02e6"}, - {"common28", u"\u2634\u32b2\u3385\u2032\u33be\u2366\u2ac7\u23cf"}, - {"common29", u"\u2981\ua721\u25a9\u2320\u21cf\u295a\u2273\u2ac2"}, - {"common30", u"\u22d9\u2465\u2347\u2a94\u4dca\u2389\u23b0\u208d"}, - {"common31", u"\u21cc\u2af8\u2912\u23a4\u2271\u2303\u241e\u33a1"}, + {"common00", L"\u237b\u2ac1\u24f5\u259f\u2a87\u23ea\u25d4\u2220"}, + {"common01", L"\u2303\u2074\u2988\u32b6\u26a2\u24e5\u2a53\u2219"}, + {"common02", L"\u29b2\u25fc\u2366\u24ae\u2647\u258e\u2654\u25fe"}, + {"common03", L"\u21ea\u22b4\u29b0\u2a84\u0008\u2657\u2731\u2697"}, + {"common04", L"\u2b3c\u2932\u21c8\u23cf\u20a1\u2aa2\u2344\u0011"}, + {"common05", L"\u22c3\u2a56\u2340\u21b7\u26ba\u2798\u220f\u2404"}, + {"common06", L"\u21f9\u25fd\u008e\u21e6\u2686\u21e4\u259f\u29ee"}, + {"common07", L"\u231e\ufe39\u0008\u2349\u2262\u2270\uff09\u2b3b"}, + {"common08", L"\u24a3\u236e\u29b2\u2259\u26ea\u2705\u00ae\u2a23"}, + {"common09", L"\u33bd\u235e\u2018\u32ba\u2973\u02c1\u20b9\u25b4"}, + {"common10", L"\u2245\u2a4d\uff19\u2042\u2aa9\u2658\u276e\uff40"}, + {"common11", L"\u0007\u21b4\u23c9\u2593\u21ba\u00a0\u258f\u23b3"}, + {"common12", L"\u2938\u250c\u2240\u2676\u2297\u2b07\u237e\u2a04"}, + {"common13", L"\u2520\u233a\u20a5\u2744\u2445\u268a\u2716\ufe62"}, + {"common14", L"\ufe4d\u25d5\u2ae1\u2a35\u2323\u273c\u26be\u2a3b"}, + {"common15", L"\u2aa2\u0000\ufe65\u2962\u2573\u21f8\u2651\u02d2"}, + {"common16", L"\u225c\u2283\u2960\u4de7\uff12\uffe1\u0016\u2905"}, + {"common17", L"\uff07\u25aa\u2076\u259e\u226c\u2568\u0026\u2691"}, + {"common18", L"\u2388\u21c2\u208d\u2a7f\u22d0\u2583\u2ad5\u240f"}, + {"common19", L"\u230a\u27ac\u001e\u261e\u259d\u25c3\u33a5\u0011"}, + {"common20", L"\ufe54\u29c7\u2477\u21ed\u2069\u4dfc\u2ae2\u21e8"}, + {"common21", L"\u2131\u2ab7\u23b9\u2660\u2083\u24c7\u228d\u2a01"}, + {"common22", L"\u2587\u2572\u21df\uff3c\u02cd\ufffd\u2404\u22b3"}, + {"common23", L"\u4dc3\u02fe\uff09\u25a3\ufe14\u255c\u2128\u2698"}, + {"common24", L"\u2b36\u3382\u02f6\u2752\uff16\u22cf\u00b0\u21d6"}, + {"common25", L"\u2561\u23db\u2958\u2782\u22af\u2621\u24a3\u29ae"}, + {"common26", L"\u2693\u22e2\u2988\u2987\u33ba\u2a94\u298e\u2328"}, + {"common27", L"\u266c\u2aa5\u2405\uffeb\uff5c\u2902\u291e\u02e6"}, + {"common28", L"\u2634\u32b2\u3385\u2032\u33be\u2366\u2ac7\u23cf"}, + {"common29", L"\u2981\ua721\u25a9\u2320\u21cf\u295a\u2273\u2ac2"}, + {"common30", L"\u22d9\u2465\u2347\u2a94\u4dca\u2389\u23b0\u208d"}, + {"common31", L"\u21cc\u2af8\u2912\u23a4\u2271\u2303\u241e\u33a1"}, #elif defined(OS_ANDROID) - {"common00", u"\u2497\uff04\u277c\u21b6\u2076\u21e4\u2068\u21b3"}, - {"common01", u"\u2663\u2466\u338e\u226b\u2734\u21be\u3389\u00ab"}, - {"common02", u"\u2062\u2197\u3392\u2681\u33be\u206d\ufe10\ufe34"}, - {"common03", u"\u02db\u00b0\u02d3\u2745\u33d1\u21e4\u24e4\u33d6"}, - {"common04", u"\u21da\u261f\u26a1\u2586\u27af\u2560\u21cd\u25c6"}, - {"common05", u"\ufe51\uff17\u0027\u21fd\u24de\uff5e\u2606\u251f"}, - {"common06", u"\u2493\u2466\u21fc\u226f\u202d\u21a9\u0040\u265d"}, - {"common07", u"\u2103\u255a\u2153\u26be\u27ac\u222e\u2490\u21a4"}, - {"common08", u"\u270b\u2486\u246b\u263c\u27b6\u21d9\u219d\u25a9"}, - {"common09", u"\u002d\u2494\u25fd\u2321\u2111\u2511\u00d7\u2535"}, - {"common10", u"\u2523\u203e\u25b2\ufe18\u2499\u2229\ufd3e\ufe16"}, - {"common11", u"\u2133\u2716\u273f\u2064\u2248\u005c\u265f\u21e6"}, - {"common12", u"\u2060\u246a\u231b\u2726\u25bd\ufe40\u002e\u25ca"}, - {"common13", u"\ufe39\u24a2\ufe18\u254b\u249c\u3396\ua71f\u2466"}, - {"common14", u"\u21b8\u2236\u251a\uff11\u2077\u0035\u27bd\u2013"}, - {"common15", u"\u2668\u2551\u221a\u02bc\u2741\u2649\u2192\u00a1"}, - {"common16", u"\u2211\u21ca\u24dc\u2536\u201b\u21c8\u2530\u25fb"}, - {"common17", u"\u231a\u33d8\u2934\u27bb\u2109\u23ec\u20a9\u3000"}, - {"common18", u"\u2069\u205f\u33d3\u2466\u24a1\u24dd\u21ac\u21e3"}, - {"common19", u"\u2737\u219a\u21f1\u2285\u226a\u00b0\u27b2\u2746"}, - {"common20", u"\u264f\u2539\u2202\u264e\u2548\u2530\u2111\u2007"}, - {"common21", u"\u2799\u0035\u25e4\u265b\u24e2\u2044\u222b\u0021"}, - {"common22", u"\u2728\u00a2\u2533\ufe43\u33c9\u27a2\u02f9\u005d"}, - {"common23", u"\ufe68\u256c\u25b6\u276c\u2771\u33c4\u2712\u24b3"}, - {"common24", u"\ufe5d\ufe31\ufe3d\u205e\u2512\u33b8\u272b\ufe4f"}, - {"common25", u"\u24e7\u25fc\u2582\u2743\u2010\u2474\u2262\u251a"}, - {"common26", u"\u2020\u211c\u24b4\u33c7\u2007\uff0f\u267f\u00b4"}, - {"common27", u"\u266c\u3399\u2570\u33a4\u276e\u00a8\u2506\u24dc"}, - {"common28", u"\u2202\ufe43\u2511\u2191\u339a\u33b0\u02d7\u2473"}, - {"common29", u"\u2517\u2297\u2762\u2460\u25bd\u24a9\u21a7\ufe64"}, - {"common30", u"\u2105\u2722\u275d\u249c\u21a2\u2590\u2260\uff5d"}, - {"common31", u"\u33ba\u21c6\u2706\u02cb\ufe64\u02e6\u0374\u2493"}, + {"common00", L"\u2497\uff04\u277c\u21b6\u2076\u21e4\u2068\u21b3"}, + {"common01", L"\u2663\u2466\u338e\u226b\u2734\u21be\u3389\u00ab"}, + {"common02", L"\u2062\u2197\u3392\u2681\u33be\u206d\ufe10\ufe34"}, + {"common03", L"\u02db\u00b0\u02d3\u2745\u33d1\u21e4\u24e4\u33d6"}, + {"common04", L"\u21da\u261f\u26a1\u2586\u27af\u2560\u21cd\u25c6"}, + {"common05", L"\ufe51\uff17\u0027\u21fd\u24de\uff5e\u2606\u251f"}, + {"common06", L"\u2493\u2466\u21fc\u226f\u202d\u21a9\u0040\u265d"}, + {"common07", L"\u2103\u255a\u2153\u26be\u27ac\u222e\u2490\u21a4"}, + {"common08", L"\u270b\u2486\u246b\u263c\u27b6\u21d9\u219d\u25a9"}, + {"common09", L"\u002d\u2494\u25fd\u2321\u2111\u2511\u00d7\u2535"}, + {"common10", L"\u2523\u203e\u25b2\ufe18\u2499\u2229\ufd3e\ufe16"}, + {"common11", L"\u2133\u2716\u273f\u2064\u2248\u005c\u265f\u21e6"}, + {"common12", L"\u2060\u246a\u231b\u2726\u25bd\ufe40\u002e\u25ca"}, + {"common13", L"\ufe39\u24a2\ufe18\u254b\u249c\u3396\ua71f\u2466"}, + {"common14", L"\u21b8\u2236\u251a\uff11\u2077\u0035\u27bd\u2013"}, + {"common15", L"\u2668\u2551\u221a\u02bc\u2741\u2649\u2192\u00a1"}, + {"common16", L"\u2211\u21ca\u24dc\u2536\u201b\u21c8\u2530\u25fb"}, + {"common17", L"\u231a\u33d8\u2934\u27bb\u2109\u23ec\u20a9\u3000"}, + {"common18", L"\u2069\u205f\u33d3\u2466\u24a1\u24dd\u21ac\u21e3"}, + {"common19", L"\u2737\u219a\u21f1\u2285\u226a\u00b0\u27b2\u2746"}, + {"common20", L"\u264f\u2539\u2202\u264e\u2548\u2530\u2111\u2007"}, + {"common21", L"\u2799\u0035\u25e4\u265b\u24e2\u2044\u222b\u0021"}, + {"common22", L"\u2728\u00a2\u2533\ufe43\u33c9\u27a2\u02f9\u005d"}, + {"common23", L"\ufe68\u256c\u25b6\u276c\u2771\u33c4\u2712\u24b3"}, + {"common24", L"\ufe5d\ufe31\ufe3d\u205e\u2512\u33b8\u272b\ufe4f"}, + {"common25", L"\u24e7\u25fc\u2582\u2743\u2010\u2474\u2262\u251a"}, + {"common26", L"\u2020\u211c\u24b4\u33c7\u2007\uff0f\u267f\u00b4"}, + {"common27", L"\u266c\u3399\u2570\u33a4\u276e\u00a8\u2506\u24dc"}, + {"common28", L"\u2202\ufe43\u2511\u2191\u339a\u33b0\u02d7\u2473"}, + {"common29", L"\u2517\u2297\u2762\u2460\u25bd\u24a9\u21a7\ufe64"}, + {"common30", L"\u2105\u2722\u275d\u249c\u21a2\u2590\u2260\uff5d"}, + {"common31", L"\u33ba\u21c6\u2706\u02cb\ufe64\u02e6\u0374\u2493"}, #elif defined(OS_APPLE) - {"common00", u"\u2153\u24e0\u2109\u02f0\u2a8f\u25ed\u02c5\u2716"}, - {"common01", u"\u02f0\u208c\u2203\u2518\u2067\u2270\u21f1\ufe66"}, - {"common02", u"\u2686\u2585\u2b15\u246f\u23e3\u21b4\u2394\ufe31"}, - {"common03", u"\u23c1\u2a97\u201e\u2200\u3389\u25d3\u02c2\u259d"}, + {"common00", L"\u2153\u24e0\u2109\u02f0\u2a8f\u25ed\u02c5\u2716"}, + {"common01", L"\u02f0\u208c\u2203\u2518\u2067\u2270\u21f1\ufe66"}, + {"common02", L"\u2686\u2585\u2b15\u246f\u23e3\u21b4\u2394\ufe31"}, + {"common03", L"\u23c1\u2a97\u201e\u2200\u3389\u25d3\u02c2\u259d"}, #else // The following tests are made for the mock fonts (see test_fonts). - {"common00", u"\u2153\u24e0\u2109\u02f0\u2a8f\u25ed\u02c5\u2716"}, - {"common01", u"\u02f0\u208c\u2203\u2518\u2067\u2270\u21f1\ufe66"}, - {"common02", u"\u2686\u2585\u2b15\u246f\u23e3\u21b4\u2394\ufe31"}, - {"common03", u"\u23c1\u2a97\u201e\u2200\u3389\u25d3\u02c2\u259d"}, - {"common04", u"\u2075\u4dec\u252a\uff15\u4df6\u2668\u27fa\ufe17"}, - {"common05", u"\u260b\u2049\u3036\u2a85\u2b15\u23c7\u230a\u2374"}, - {"common06", u"\u2771\u27fa\u255d\uff0b\u2213\u3396\u2a85\u2276"}, - {"common07", u"\u211e\u2b06\u2255\u2727\u26c3\u33cf\u267d\u2ab2"}, - {"common08", u"\u2373\u20b3\u22b8\u2a0f\u02fd\u2585\u3036\ufe48"}, - {"common09", u"\u256d\u2940\u21d8\u4dde\u23a1\u226b\u3374\u2a99"}, - {"common10", u"\u270f\u24e5\u26c1\u2131\u21f5\u25af\u230f\u27fe"}, - {"common11", u"\u27aa\u23a2\u02ef\u2373\u2257\u2749\u2496\ufe31"}, - {"common12", u"\u230a\u25fb\u2117\u3386\u32cc\u21c5\u24c4\u207e"}, - {"common13", u"\u2467\u2791\u3393\u33bb\u02ca\u25de\ua788\u278f"}, - {"common14", u"\ua719\u25ed\u20a8\u20a1\u4dd8\u2295\u24eb\u02c8"}, - {"common15", u"\u22b6\u2520\u2036\uffee\u21df\u002d\u277a\u2b24"}, - {"common16", u"\u21f8\u211b\u22a0\u25b6\u263e\u2704\u221a\u2758"}, - {"common17", u"\ufe10\u2060\u24ac\u3385\u27a1\u2059\u2689\u2278"}, - {"common18", u"\u269b\u211b\u33a4\ufe36\u239e\u267f\u2423\u24a2"}, - {"common19", u"\u4ded\u262d\u225e\u248b\u21df\u279d\u2518\u21ba"}, - {"common20", u"\u225a\uff16\u21d4\u21c6\u02ba\u2545\u23aa\u005e"}, - {"common21", u"\u20a5\u265e\u3395\u2a6a\u2555\u22a4\u2086\u23aa"}, - {"common22", u"\u203f\u3250\u2240\u24e9\u21cb\u258f\u24b1\u3259"}, - {"common23", u"\u27bd\u263b\uff1f\u2199\u2547\u258d\u201f\u2507"}, - {"common24", u"\u2482\u2548\u02dc\u231f\u24cd\u2198\u220e\u20ad"}, - {"common25", u"\u2ff7\u2540\ufe48\u2197\u276b\u2574\u2062\u3398"}, - {"common26", u"\u2663\u21cd\u263f\u23e5\u22d7\u2518\u21b9\u2628"}, - {"common27", u"\u21fa\ufe66\u2739\u2051\u21f4\u3399\u2599\u25f7"}, - {"common28", u"\u29d3\u25ec\u27a6\u24e0\u2735\u25b4\u2737\u25db"}, - {"common29", u"\u2622\u22e8\u33d2\u21d3\u2502\u2153\u2669\u25f2"}, - {"common30", u"\u2121\u21af\u2729\u203c\u337a\u2464\u2b08\u2e24"}, - {"common31", u"\u33cd\u007b\u02d2\u22cc\u32be\u2ffa\u2787\u02e9"}, + {"common00", L"\u2153\u24e0\u2109\u02f0\u2a8f\u25ed\u02c5\u2716"}, + {"common01", L"\u02f0\u208c\u2203\u2518\u2067\u2270\u21f1\ufe66"}, + {"common02", L"\u2686\u2585\u2b15\u246f\u23e3\u21b4\u2394\ufe31"}, + {"common03", L"\u23c1\u2a97\u201e\u2200\u3389\u25d3\u02c2\u259d"}, + {"common04", L"\u2075\u4dec\u252a\uff15\u4df6\u2668\u27fa\ufe17"}, + {"common05", L"\u260b\u2049\u3036\u2a85\u2b15\u23c7\u230a\u2374"}, + {"common06", L"\u2771\u27fa\u255d\uff0b\u2213\u3396\u2a85\u2276"}, + {"common07", L"\u211e\u2b06\u2255\u2727\u26c3\u33cf\u267d\u2ab2"}, + {"common08", L"\u2373\u20b3\u22b8\u2a0f\u02fd\u2585\u3036\ufe48"}, + {"common09", L"\u256d\u2940\u21d8\u4dde\u23a1\u226b\u3374\u2a99"}, + {"common10", L"\u270f\u24e5\u26c1\u2131\u21f5\u25af\u230f\u27fe"}, + {"common11", L"\u27aa\u23a2\u02ef\u2373\u2257\u2749\u2496\ufe31"}, + {"common12", L"\u230a\u25fb\u2117\u3386\u32cc\u21c5\u24c4\u207e"}, + {"common13", L"\u2467\u2791\u3393\u33bb\u02ca\u25de\ua788\u278f"}, + {"common14", L"\ua719\u25ed\u20a8\u20a1\u4dd8\u2295\u24eb\u02c8"}, + {"common15", L"\u22b6\u2520\u2036\uffee\u21df\u002d\u277a\u2b24"}, + {"common16", L"\u21f8\u211b\u22a0\u25b6\u263e\u2704\u221a\u2758"}, + {"common17", L"\ufe10\u2060\u24ac\u3385\u27a1\u2059\u2689\u2278"}, + {"common18", L"\u269b\u211b\u33a4\ufe36\u239e\u267f\u2423\u24a2"}, + {"common19", L"\u4ded\u262d\u225e\u248b\u21df\u279d\u2518\u21ba"}, + {"common20", L"\u225a\uff16\u21d4\u21c6\u02ba\u2545\u23aa\u005e"}, + {"common21", L"\u20a5\u265e\u3395\u2a6a\u2555\u22a4\u2086\u23aa"}, + {"common22", L"\u203f\u3250\u2240\u24e9\u21cb\u258f\u24b1\u3259"}, + {"common23", L"\u27bd\u263b\uff1f\u2199\u2547\u258d\u201f\u2507"}, + {"common24", L"\u2482\u2548\u02dc\u231f\u24cd\u2198\u220e\u20ad"}, + {"common25", L"\u2ff7\u2540\ufe48\u2197\u276b\u2574\u2062\u3398"}, + {"common26", L"\u2663\u21cd\u263f\u23e5\u22d7\u2518\u21b9\u2628"}, + {"common27", L"\u21fa\ufe66\u2739\u2051\u21f4\u3399\u2599\u25f7"}, + {"common28", L"\u29d3\u25ec\u27a6\u24e0\u2735\u25b4\u2737\u25db"}, + {"common29", L"\u2622\u22e8\u33d2\u21d3\u2502\u2153\u2669\u25f2"}, + {"common30", L"\u2121\u21af\u2729\u203c\u337a\u2464\u2b08\u2e24"}, + {"common31", L"\u33cd\u007b\u02d2\u22cc\u32be\u2ffa\u2787\u02e9"}, #endif }; @@ -7157,16 +7175,16 @@ } TEST_F(RenderTextTest, ZeroWidthCharacters) { - static const char16_t* kEmptyText[] = { - u"\u200C", // ZERO WIDTH NON-JOINER - u"\u200D", // ZERO WIDTH JOINER - u"\u200B", // ZERO WIDTH SPACE - u"\uFEFF", // ZERO WIDTH NO-BREAK SPACE + static const wchar_t* kEmptyText[] = { + L"\u200C", // ZERO WIDTH NON-JOINER + L"\u200D", // ZERO WIDTH JOINER + L"\u200B", // ZERO WIDTH SPACE + L"\uFEFF", // ZERO WIDTH NO-BREAK SPACE }; - for (const auto* text : kEmptyText) { + for (const wchar_t* text : kEmptyText) { RenderTextHarfBuzz* render_text = GetRenderText(); - render_text->SetText(text); + render_text->SetText(WideToUTF16(text)); const internal::TextRunList* run_list = GetHarfBuzzRunList(); EXPECT_EQ(0, run_list->width()); @@ -7184,8 +7202,10 @@ // crbug.com/459812. This appears to be a preexisting issue that wasn't // revealed by the prior unit tests. // "TEST_______", - "TEST some stuff", "WWWWWWWWWW", "gAXAXAXAXAXAXA", "gÅXÅXÅXÅXÅXÅXÅ", - "هٔهٔهٔهٔمرحبا"}; + "TEST some stuff", "WWWWWWWWWW", "gAXAXAXAXAXAXA", + "g\u00C5X\u00C5X\u00C5X\u00C5X\u00C5X\u00C5X\u00C5", + ("\u0647\u0654\u0647\u0654\u0647\u0654\u0647\u0654\u0645\u0631\u062D" + "\u0628\u0627")}; const Size kCanvasSize(300, 50); const int kTestSize = 10; @@ -7200,7 +7220,7 @@ for (auto* string : kTestStrings) { paint_canvas.clear(SK_ColorWHITE); - render_text->SetText(base::UTF8ToUTF16(string)); + render_text->SetText(UTF8ToUTF16(string)); render_text->ApplyBaselineStyle(SUPERSCRIPT, Range(1, 2)); render_text->ApplyBaselineStyle(SUPERIOR, Range(3, 4)); render_text->ApplyBaselineStyle(INFERIOR, Range(5, 6)); @@ -7271,7 +7291,7 @@ for (auto* string : kTestStrings) { paint_canvas.clear(SK_ColorWHITE); - render_text->SetText(base::UTF8ToUTF16(string)); + render_text->SetText(UTF8ToUTF16(string)); const Size string_size = render_text->GetStringSize(); int fake_width = string_size.width() / 2; int fake_height = string_size.height() / 2; @@ -7778,37 +7798,37 @@ // Tests text selection made at end points of individual lines of multiline // text. TEST_F(RenderTextTest, LineEndSelections) { - const char16_t* const ltr = u"abc\n\ndef"; - const char16_t* const rtl = u"שנב\n\nגקכ"; - const char16_t* const ltr_single = u"abc def ghi"; - const char16_t* const rtl_single = u"שנב גקכ עין"; + const char* const ltr = "abc\n\ndef"; + const char* const rtl = "שנב\n\nגקכ"; + const char* const ltr_single = "abc def ghi"; + const char* const rtl_single = "שנב גקכ עין"; const int left_x = -100; const int right_x = 200; struct { - const char16_t* const text; + const char* const text; const int line_num; const int x; - const char16_t* const selected_text; + const char* const selected_text; } cases[] = { - {ltr, 1, left_x, u"abc\n"}, - {ltr, 1, right_x, u"abc\n"}, - {ltr, 2, left_x, u"abc\n\n"}, + {ltr, 1, left_x, "abc\n"}, + {ltr, 1, right_x, "abc\n"}, + {ltr, 2, left_x, "abc\n\n"}, {ltr, 2, right_x, ltr}, - {rtl, 1, left_x, u"שנב\n"}, - {rtl, 1, right_x, u"שנב\n"}, + {rtl, 1, left_x, "שנב\n"}, + {rtl, 1, right_x, "שנב\n"}, {rtl, 2, left_x, rtl}, - {rtl, 2, right_x, u"שנב\n\n"}, + {rtl, 2, right_x, "שנב\n\n"}, - {ltr_single, 1, left_x, u"abc "}, - {ltr_single, 1, right_x, u"abc def "}, - {ltr_single, 2, left_x, u"abc def "}, + {ltr_single, 1, left_x, "abc "}, + {ltr_single, 1, right_x, "abc def "}, + {ltr_single, 2, left_x, "abc def "}, {ltr_single, 2, right_x, ltr_single}, - {rtl_single, 1, left_x, u"שנב גקכ "}, - {rtl_single, 1, right_x, u"שנב "}, + {rtl_single, 1, left_x, "שנב גקכ "}, + {rtl_single, 1, right_x, "שנב "}, {rtl_single, 2, left_x, rtl_single}, - {rtl_single, 2, right_x, u"שנב גקכ "}, + {rtl_single, 2, right_x, "שנב גקכ "}, }; SetGlyphWidth(5); @@ -7818,7 +7838,7 @@ for (size_t i = 0; i < base::size(cases); i++) { SCOPED_TRACE(base::StringPrintf("Testing case %" PRIuS "", i)); - render_text->SetText(cases[i].text); + render_text->SetText(UTF8ToUTF16(cases[i].text)); EXPECT_EQ(3u, render_text->GetNumLines()); // Position the cursor at the logical beginning of text. @@ -7826,7 +7846,8 @@ render_text->MoveCursorToPoint( Point(cases[i].x, GetCursorYForTesting(cases[i].line_num)), true); - EXPECT_EQ(cases[i].selected_text, GetSelectedText(render_text)); + EXPECT_EQ(UTF8ToUTF16(cases[i].selected_text), + GetSelectedText(render_text)); } } @@ -8242,8 +8263,7 @@ const int test_font_size_override = default_font_size + 5; render_text->SetText(u"0123456789"); render_text->ApplyFontSizeOverride(test_font_size_override, gfx::Range(3, 7)); - EXPECT_EQ(std::vector<std::u16string>({u"012", u"3456", u"789"}), - GetRunListStrings()); + EXPECT_EQ(ToString16Vec({"012", "3456", "789"}), GetRunListStrings()); const internal::TextRunList* run_list = GetHarfBuzzRunList(); ASSERT_EQ(3U, run_list->size());
diff --git a/ui/gfx/text_elider_unittest.cc b/ui/gfx/text_elider_unittest.cc index 4df7150..d1b5017 100644 --- a/ui/gfx/text_elider_unittest.cc +++ b/ui/gfx/text_elider_unittest.cc
@@ -27,26 +27,44 @@ #include "ui/gfx/font_render_params.h" #include "ui/gfx/text_utils.h" +using base::ASCIIToUTF16; +using base::UTF16ToUTF8; +using base::UTF16ToWide; +using base::UTF8ToUTF16; + namespace gfx { namespace { -struct FileTestcase { - const base::FilePath::StringType input; - const std::u16string output; - // If this value is specified, we will try to cut the path down to the render - // width of this string; if not specified, output will be used. - const std::u16string using_width_of = std::u16string(); +struct Testcase { + const std::string input; + const std::string output; }; -struct Testcase { +struct FileTestcase { + const base::FilePath::StringType input; + const std::string output; + // If this value is specified, we will try to cut the path down to the render + // width of this string; if not specified, output will be used. + const std::string using_width_of = std::string(); +}; + +struct UTF16Testcase { const std::u16string input; const std::u16string output; }; +struct TestData { + const std::string a; + const std::string b; + const int compare_result; +}; + } // namespace TEST(TextEliderTest, ElideEmail) { + const std::string kEllipsisStr(kEllipsis); + // Test emails and their expected elided forms (from which the available // widths will be derived). // For elided forms in which both the username and domain must be elided: @@ -54,43 +72,48 @@ // dependent. To avoid this, the username is prefixed with the characters // expected to remain in the domain. Testcase testcases[] = { - {u"g@g.c", u"g@g.c"}, - {u"g@g.c", u"…"}, - {u"ga@co.ca", u"ga@c…a"}, - {u"short@small.com", u"s…@s…"}, - {u"short@small.com", u"s…@small.com"}, - {u"short@longbutlotsofspace.com", u"short@longbutlotsofspace.com"}, - {u"short@longbutnotverymuchspace.com", u"short@long….com"}, - {u"la_short@longbutverytightspace.ca", u"la…@l…a"}, - {u"longusername@gmail.com", u"long…@gmail.com"}, - {u"elidetothemax@justfits.com", u"e…@justfits.com"}, - {u"thatom_somelongemail@thatdoesntfit.com", u"thatom…@tha…om"}, - {u"namefits@butthedomaindoesnt.com", u"namefits@butthedo…snt.com"}, - {u"widthtootight@nospace.com", u"…"}, - {u"nospaceforusername@l", u"…"}, - {u"little@littlespace.com", u"l…@l…"}, - {u"l@llllllllllllllllllllllll.com", u"l@lllll….com"}, - {u"messed\"up@whyanat\"++@notgoogley.com", - u"messed\"up@whyanat\"++@notgoogley.com"}, - {u"messed\"up@whyanat\"++@notgoogley.com", - u"messed\"up@why…@notgoogley.com"}, - {u"noca_messed\"up@whyanat\"++@notgoogley.ca", u"noca…@no…ca"}, - {u"at\"@@@@@@@@@...@@.@.@.@@@\"@madness.com", - u"at\"@@@@@@@@@...@@.@.…@madness.com"}, + {"g@g.c", "g@g.c"}, + {"g@g.c", kEllipsisStr}, + {"ga@co.ca", "ga@c" + kEllipsisStr + "a"}, + {"short@small.com", "s" + kEllipsisStr + "@s" + kEllipsisStr}, + {"short@small.com", "s" + kEllipsisStr + "@small.com"}, + {"short@longbutlotsofspace.com", "short@longbutlotsofspace.com"}, + {"short@longbutnotverymuchspace.com", + "short@long" + kEllipsisStr + ".com"}, + {"la_short@longbutverytightspace.ca", + "la" + kEllipsisStr + "@l" + kEllipsisStr + "a"}, + {"longusername@gmail.com", "long" + kEllipsisStr + "@gmail.com"}, + {"elidetothemax@justfits.com", "e" + kEllipsisStr + "@justfits.com"}, + {"thatom_somelongemail@thatdoesntfit.com", + "thatom" + kEllipsisStr + "@tha" + kEllipsisStr + "om"}, + {"namefits@butthedomaindoesnt.com", + "namefits@butthedo" + kEllipsisStr + "snt.com"}, + {"widthtootight@nospace.com", kEllipsisStr}, + {"nospaceforusername@l", kEllipsisStr}, + {"little@littlespace.com", "l" + kEllipsisStr + "@l" + kEllipsisStr}, + {"l@llllllllllllllllllllllll.com", "l@lllll" + kEllipsisStr + ".com"}, + {"messed\"up@whyanat\"++@notgoogley.com", + "messed\"up@whyanat\"++@notgoogley.com"}, + {"messed\"up@whyanat\"++@notgoogley.com", + "messed\"up@why" + kEllipsisStr + "@notgoogley.com"}, + {"noca_messed\"up@whyanat\"++@notgoogley.ca", + "noca" + kEllipsisStr + "@no" + kEllipsisStr + "ca"}, + {"at\"@@@@@@@@@...@@.@.@.@@@\"@madness.com", + "at\"@@@@@@@@@...@@.@." + kEllipsisStr + "@madness.com"}, // Special case: "m..." takes more than half of the available width; thus // the domain must elide to "l..." and not "l...l" as it must allow enough // space for the minimal username elision although its half of the // available width would normally allow it to elide to "l...l". - {u"mmmmm@llllllllll", u"m…@l…"}, + {"mmmmm@llllllllll", "m" + kEllipsisStr + "@l" + kEllipsisStr}, }; const FontList font_list; for (size_t i = 0; i < base::size(testcases); ++i) { - const std::u16string expected_output = testcases[i].output; - EXPECT_EQ( - expected_output, - ElideText(testcases[i].input, font_list, - GetStringWidthF(expected_output, font_list), ELIDE_EMAIL)); + const std::u16string expected_output = UTF8ToUTF16(testcases[i].output); + EXPECT_EQ(expected_output, + ElideText(UTF8ToUTF16(testcases[i].input), font_list, + GetStringWidthF(expected_output, font_list), + ELIDE_EMAIL)); } } @@ -98,69 +121,74 @@ const int test_widths_extra_spaces[] = { 10, 1000, - 100'000, + 100000, }; - const char16_t* const test_emails[] = { - u"a@c", - u"test@email.com", - u"short@verysuperdupperlongdomain.com", - u"supermegalongusername@withasuperlonnnggggdomain.gouv.qc.ca", + const char* test_emails[] = { + "a@c", + "test@email.com", + "short@verysuperdupperlongdomain.com", + "supermegalongusername@withasuperlonnnggggdomain.gouv.qc.ca", }; const FontList font_list; for (const auto* test_email : test_emails) { - const int mimimum_width = GetStringWidth(test_email, font_list); + const std::u16string test_email16 = UTF8ToUTF16(test_email); + const int mimimum_width = GetStringWidth(test_email16, font_list); for (int extra_space : test_widths_extra_spaces) { // Extra space is available: the email should not be elided. - EXPECT_EQ(test_email, - ElideText(test_email, font_list, mimimum_width + extra_space, + EXPECT_EQ(test_email16, + ElideText(test_email16, font_list, mimimum_width + extra_space, ELIDE_EMAIL)); } } } TEST(TextEliderTest, TestFilenameEliding) { + const std::string kEllipsisStr(kEllipsis); const base::FilePath::StringType kPathSeparator = base::FilePath::StringType().append(1, base::FilePath::kSeparators[0]); FileTestcase testcases[] = { - {FILE_PATH_LITERAL(""), u""}, - {FILE_PATH_LITERAL("."), u"."}, - {FILE_PATH_LITERAL("filename.exe"), u"filename.exe"}, - {FILE_PATH_LITERAL(".longext"), u".longext"}, - {FILE_PATH_LITERAL("pie"), u"pie"}, + {FILE_PATH_LITERAL(""), ""}, + {FILE_PATH_LITERAL("."), "."}, + {FILE_PATH_LITERAL("filename.exe"), "filename.exe"}, + {FILE_PATH_LITERAL(".longext"), ".longext"}, + {FILE_PATH_LITERAL("pie"), "pie"}, {FILE_PATH_LITERAL("c:") + kPathSeparator + FILE_PATH_LITERAL("path") + kPathSeparator + FILE_PATH_LITERAL("filename.pie"), - u"filename.pie"}, + "filename.pie"}, {FILE_PATH_LITERAL("c:") + kPathSeparator + FILE_PATH_LITERAL("path") + kPathSeparator + FILE_PATH_LITERAL("longfilename.pie"), - u"long….pie"}, - {FILE_PATH_LITERAL("http://path.com/filename.pie"), u"filename.pie"}, - {FILE_PATH_LITERAL("http://path.com/longfilename.pie"), u"long….pie"}, - {FILE_PATH_LITERAL("piesmashingtacularpants"), u"pie…"}, - {FILE_PATH_LITERAL(".piesmashingtacularpants"), u".pie…"}, - {FILE_PATH_LITERAL("cheese."), u"cheese."}, - {FILE_PATH_LITERAL("file name.longext"), u"file….longext"}, - {FILE_PATH_LITERAL("fil ename.longext"), u"fil….longext", - u"fil ….longext"}, - {FILE_PATH_LITERAL("filename.longext"), u"file….longext"}, + "long" + kEllipsisStr + ".pie"}, + {FILE_PATH_LITERAL("http://path.com/filename.pie"), "filename.pie"}, + {FILE_PATH_LITERAL("http://path.com/longfilename.pie"), + "long" + kEllipsisStr + ".pie"}, + {FILE_PATH_LITERAL("piesmashingtacularpants"), "pie" + kEllipsisStr}, + {FILE_PATH_LITERAL(".piesmashingtacularpants"), ".pie" + kEllipsisStr}, + {FILE_PATH_LITERAL("cheese."), "cheese."}, + {FILE_PATH_LITERAL("file name.longext"), + "file" + kEllipsisStr + ".longext"}, + {FILE_PATH_LITERAL("fil ename.longext"), + "fil" + kEllipsisStr + ".longext", "fil " + kEllipsisStr + ".longext"}, + {FILE_PATH_LITERAL("filename.longext"), + "file" + kEllipsisStr + ".longext"}, {FILE_PATH_LITERAL("filename.middleext.longext"), - u"filename.mid….longext"}, + "filename.mid" + kEllipsisStr + ".longext"}, {FILE_PATH_LITERAL("filename.superduperextremelylongext"), - u"filename.sup…emelylongext"}, + "filename.sup" + kEllipsisStr + "emelylongext"}, {FILE_PATH_LITERAL("filenamereallylongtext.superdeduperextremelylongext"), - u"filenamereall…emelylongext"}, + "filenamereall" + kEllipsisStr + "emelylongext"}, {FILE_PATH_LITERAL( "file.name.really.long.text.superduperextremelylongext"), - u"file.name.re…emelylongext"}}; + "file.name.re" + kEllipsisStr + "emelylongext"}}; static const FontList font_list; for (size_t i = 0; i < base::size(testcases); ++i) { base::FilePath filepath(testcases[i].input); - std::u16string expected = testcases[i].output; - std::u16string using_width_of = testcases[i].using_width_of.empty() - ? testcases[i].output - : testcases[i].using_width_of; + std::u16string expected = UTF8ToUTF16(testcases[i].output); + std::u16string using_width_of = UTF8ToUTF16( + testcases[i].using_width_of.empty() ? testcases[i].output + : testcases[i].using_width_of); expected = base::i18n::GetDisplayStringInLTRDirectionality(expected); EXPECT_EQ(expected, ElideFilename(filepath, font_list, @@ -172,71 +200,76 @@ const FontList font_list; const float kTestWidth = GetStringWidthF(u"Test", font_list); struct TestData { - const char16_t* input; + const char* input; float width; - const char16_t* output; + const char* output; } cases[] = { - {u"", 0, u""}, - {u"Test", 0, u""}, - {u"", kTestWidth, u""}, - {u"Tes", kTestWidth, u"Tes"}, - {u"Test", kTestWidth, u"Test"}, - {u"Tests", kTestWidth, u"Test"}, + { "", 0, "" }, + { "Test", 0, "" }, + { "", kTestWidth, "" }, + { "Tes", kTestWidth, "Tes" }, + { "Test", kTestWidth, "Test" }, + { "Tests", kTestWidth, "Test" }, }; for (size_t i = 0; i < base::size(cases); ++i) { - std::u16string result = - ElideText(cases[i].input, font_list, cases[i].width, TRUNCATE); - EXPECT_EQ(cases[i].output, result); + std::u16string result = ElideText(UTF8ToUTF16(cases[i].input), font_list, + cases[i].width, TRUNCATE); + EXPECT_EQ(cases[i].output, UTF16ToUTF8(result)); } } TEST(TextEliderTest, ElideTextEllipsis) { const FontList font_list; const float kTestWidth = GetStringWidthF(u"Test", font_list); - const float kEllipsisWidth = GetStringWidthF(u"…", font_list); + const char* kEllipsis = "\xE2\x80\xA6"; + const float kEllipsisWidth = + GetStringWidthF(UTF8ToUTF16(kEllipsis), font_list); struct TestData { - const char16_t* input; + const char* input; float width; - const char16_t* output; + const char* output; } cases[] = { - {u"", 0, u""}, - {u"Test", 0, u""}, - {u"Test", kEllipsisWidth, u"…"}, - {u"", kTestWidth, u""}, - {u"Tes", kTestWidth, u"Tes"}, - {u"Test", kTestWidth, u"Test"}, + { "", 0, "" }, + { "Test", 0, "" }, + { "Test", kEllipsisWidth, kEllipsis }, + { "", kTestWidth, "" }, + { "Tes", kTestWidth, "Tes" }, + { "Test", kTestWidth, "Test" }, }; for (size_t i = 0; i < base::size(cases); ++i) { - std::u16string result = - ElideText(cases[i].input, font_list, cases[i].width, ELIDE_TAIL); - EXPECT_EQ(cases[i].output, result); + std::u16string result = ElideText(UTF8ToUTF16(cases[i].input), font_list, + cases[i].width, ELIDE_TAIL); + EXPECT_EQ(cases[i].output, UTF16ToUTF8(result)); } } TEST(TextEliderTest, ElideTextEllipsisFront) { const FontList font_list; const float kTestWidth = GetStringWidthF(u"Test", font_list); - const float kEllipsisWidth = GetStringWidthF(u"…", font_list); - const float kEllipsis23Width = GetStringWidthF(u"…23", font_list); + const std::string kEllipsisStr(kEllipsis); + const float kEllipsisWidth = + GetStringWidthF(UTF8ToUTF16(kEllipsis), font_list); + const float kEllipsis23Width = + GetStringWidthF(UTF8ToUTF16(kEllipsisStr + "23"), font_list); struct TestData { - const char16_t* input; + const char* input; float width; const std::u16string output; } cases[] = { - {u"", 0, std::u16string()}, - {u"Test", 0, std::u16string()}, - {u"Test", kEllipsisWidth, u"…"}, - {u"", kTestWidth, std::u16string()}, - {u"Tes", kTestWidth, u"Tes"}, - {u"Test", kTestWidth, u"Test"}, - {u"Test123", kEllipsis23Width, u"…23"}, + {"", 0, std::u16string()}, + {"Test", 0, std::u16string()}, + {"Test", kEllipsisWidth, UTF8ToUTF16(kEllipsisStr)}, + {"", kTestWidth, std::u16string()}, + {"Tes", kTestWidth, u"Tes"}, + {"Test", kTestWidth, u"Test"}, + {"Test123", kEllipsis23Width, UTF8ToUTF16(kEllipsisStr + "23")}, }; for (size_t i = 0; i < base::size(cases); ++i) { - std::u16string result = - ElideText(cases[i].input, font_list, cases[i].width, ELIDE_HEAD); + std::u16string result = ElideText(UTF8ToUTF16(cases[i].input), font_list, + cases[i].width, ELIDE_HEAD); EXPECT_EQ(cases[i].output, result); } } @@ -265,13 +298,15 @@ base::test::SingleThreadTaskEnvironment::MainThreadType::UI); #endif const FontList font_list; - std::vector<std::u16string> pairs; // The below is 'MUSICAL SYMBOL G CLEF' (U+1D11E), which is represented in // UTF-16 as two code units forming a surrogate pair: 0xD834 0xDD1E. - pairs.push_back(u"\U0001d11e"); + const char16_t kSurrogate[] = {0xD834, 0xDD1E, 0}; // The below is a Devanagari two-character combining sequence U+0921 U+093F. // The sequence forms a single display character and should not be separated. - pairs.push_back(u"\u0921\u093f"); + const char16_t kCombiningSequence[] = {0x921, 0x93F, 0}; + std::vector<std::u16string> pairs; + pairs.push_back(kSurrogate); + pairs.push_back(kCombiningSequence); for (const std::u16string& pair : pairs) { char16_t first_char = pair[0]; @@ -300,33 +335,34 @@ } TEST(TextEliderTest, ElideTextLongStrings) { + const std::u16string kEllipsisStr = UTF8ToUTF16(kEllipsis); std::u16string data_scheme(u"data:text/plain,"); size_t data_scheme_length = data_scheme.length(); std::u16string ten_a(10, 'a'); std::u16string hundred_a(100, 'a'); std::u16string thousand_a(1000, 'a'); - std::u16string ten_thousand_a(10'000, 'a'); - std::u16string hundred_thousand_a(100'000, 'a'); - std::u16string million_a(1'000'000, 'a'); + std::u16string ten_thousand_a(10000, 'a'); + std::u16string hundred_thousand_a(100000, 'a'); + std::u16string million_a(1000000, 'a'); // TODO(gbillock): Improve these tests by adding more string diversity and // doing string compares instead of length compares. See bug 338836. size_t number_of_as = 156; - std::u16string long_string_end(data_scheme + - std::u16string(number_of_as, 'a') + u"…"); - Testcase testcases_end[] = { - {data_scheme + ten_a, data_scheme + ten_a}, - {data_scheme + hundred_a, data_scheme + hundred_a}, - {data_scheme + thousand_a, long_string_end}, - {data_scheme + ten_thousand_a, long_string_end}, - {data_scheme + hundred_thousand_a, long_string_end}, - {data_scheme + million_a, long_string_end}, + std::u16string long_string_end( + data_scheme + std::u16string(number_of_as, 'a') + kEllipsisStr); + UTF16Testcase testcases_end[] = { + { data_scheme + ten_a, data_scheme + ten_a }, + { data_scheme + hundred_a, data_scheme + hundred_a }, + { data_scheme + thousand_a, long_string_end }, + { data_scheme + ten_thousand_a, long_string_end }, + { data_scheme + hundred_thousand_a, long_string_end }, + { data_scheme + million_a, long_string_end }, }; const FontList font_list; - float ellipsis_width = GetStringWidthF(u"…", font_list); + float ellipsis_width = GetStringWidthF(kEllipsisStr, font_list); for (size_t i = 0; i < base::size(testcases_end); ++i) { // Compare sizes rather than actual contents because if the test fails, // output is rather long. @@ -334,19 +370,20 @@ ElideText(testcases_end[i].input, font_list, GetStringWidthF(testcases_end[i].output, font_list), ELIDE_TAIL).size()); - EXPECT_EQ(u"…", ElideText(testcases_end[i].input, font_list, ellipsis_width, - ELIDE_TAIL)); + EXPECT_EQ(kEllipsisStr, + ElideText(testcases_end[i].input, font_list, ellipsis_width, + ELIDE_TAIL)); } size_t number_of_trailing_as = (data_scheme_length + number_of_as) / 2; std::u16string long_string_middle( data_scheme + std::u16string(number_of_as - number_of_trailing_as, 'a') + - u"…" + std::u16string(number_of_trailing_as, 'a')); + kEllipsisStr + std::u16string(number_of_trailing_as, 'a')); #if !defined(OS_IOS) - long_string_middle += u"…"; + long_string_middle += kEllipsisStr; #endif - Testcase testcases_middle[] = { + UTF16Testcase testcases_middle[] = { {data_scheme + ten_a, data_scheme + ten_a}, {data_scheme + hundred_a, data_scheme + hundred_a}, {data_scheme + thousand_a, long_string_middle}, @@ -363,17 +400,17 @@ GetStringWidthF(testcases_middle[i].output, font_list), ELIDE_MIDDLE) .size()); - EXPECT_EQ(u"…", ElideText(testcases_middle[i].input, font_list, - ellipsis_width, ELIDE_MIDDLE)); + EXPECT_EQ(kEllipsisStr, ElideText(testcases_middle[i].input, font_list, + ellipsis_width, ELIDE_MIDDLE)); } - std::u16string long_string_beginning(u"…" + + std::u16string long_string_beginning(kEllipsisStr + std::u16string(number_of_as, 'a')); #if !defined(OS_IOS) - long_string_beginning += u"…"; + long_string_beginning += kEllipsisStr; #endif - Testcase testcases_beginning[] = { + UTF16Testcase testcases_beginning[] = { {data_scheme + ten_a, data_scheme + ten_a}, {data_scheme + hundred_a, data_scheme + hundred_a}, {data_scheme + thousand_a, long_string_beginning}, @@ -387,8 +424,8 @@ testcases_beginning[i].input, font_list, GetStringWidthF(testcases_beginning[i].output, font_list), ELIDE_HEAD).size()); - EXPECT_EQ(u"…", ElideText(testcases_beginning[i].input, font_list, - ellipsis_width, ELIDE_HEAD)); + EXPECT_EQ(kEllipsisStr, ElideText(testcases_beginning[i].input, font_list, + ellipsis_width, ELIDE_HEAD)); } } @@ -398,11 +435,11 @@ TEST(TextEliderTest, StringSlicerBasicTest) { // Must store strings in variables (StringSlicer retains a reference to them). std::u16string text(u"Hello, world!"); - std::u16string ellipsis(u"…"); + std::u16string ellipsis(kEllipsisUTF16); StringSlicer slicer(text, ellipsis, false, false); EXPECT_EQ(u"", slicer.CutString(0, false)); - EXPECT_EQ(u"…", slicer.CutString(0, true)); + EXPECT_EQ(std::u16string(kEllipsisUTF16), slicer.CutString(0, true)); EXPECT_EQ(u"Hell", slicer.CutString(4, false)); EXPECT_EQ(u"Hell…", slicer.CutString(4, true)); @@ -422,7 +459,7 @@ TEST(TextEliderTest, StringSlicerWhitespace_UseDefault) { // Must store strings in variables (StringSlicer retains a reference to them). std::u16string text(u"Hello, world!"); - std::u16string ellipsis(u"…"); + std::u16string ellipsis(kEllipsisUTF16); // Eliding the end of a string should result in whitespace being removed // before the ellipsis by default. @@ -450,7 +487,7 @@ TEST(TextEliderTest, StringSlicerWhitespace_NoTrim) { // Must store strings in variables (StringSlicer retains a reference to them). std::u16string text(u"Hello, world!"); - std::u16string ellipsis(u"…"); + std::u16string ellipsis(kEllipsisUTF16); // Eliding the end of a string should not result in whitespace being removed // before the ellipsis in no-trim mode. @@ -478,7 +515,7 @@ TEST(TextEliderTest, StringSlicerWhitespace_Trim) { // Must store strings in variables (StringSlicer retains a reference to them). std::u16string text(u"Hello, world!"); - std::u16string ellipsis(u"…"); + std::u16string ellipsis(kEllipsisUTF16); // Eliding the end of a string should result in whitespace being removed // before the ellipsis in trim mode. @@ -506,7 +543,7 @@ TEST(TextEliderTest, StringSlicer_ElideMiddle_MultipleWhitespace) { // Must store strings in variables (StringSlicer retains a reference to them). std::u16string text(u"Hello world!"); - std::u16string ellipsis(u"…"); + std::u16string ellipsis(kEllipsisUTF16); // Eliding the middle of a string should not result in whitespace being // removed around the ellipsis in default whitespace mode. @@ -542,23 +579,24 @@ TEST(TextEliderTest, StringSlicerSurrogate) { // The below is 'MUSICAL SYMBOL G CLEF' (U+1D11E), which is represented in // UTF-16 as two code units forming a surrogate pair: 0xD834 0xDD1E. - const std::u16string kSurrogate = u"\U0001d11e"; + const std::u16string kSurrogate = u"𝄞"; ASSERT_EQ(2u, kSurrogate.size()); ASSERT_EQ(u'\xD834', kSurrogate[0]); ASSERT_EQ(u'\xDD1E', kSurrogate[1]); std::u16string text(u"abc" + kSurrogate + u"xyz"); - std::u16string ellipsis(u"…"); + std::u16string ellipsis(kEllipsisUTF16); StringSlicer slicer(text, ellipsis, false, false); // Cut surrogate on the right. Should round left and exclude the surrogate. - EXPECT_EQ(u"…", slicer.CutString(0, true)); + EXPECT_EQ(std::u16string(kEllipsisUTF16), slicer.CutString(0, true)); EXPECT_EQ(u"abc…", slicer.CutString(4, true)); - EXPECT_EQ(text + u"…", slicer.CutString(text.length(), true)); + EXPECT_EQ(text + kEllipsisUTF16, slicer.CutString(text.length(), true)); // Cut surrogate on the left. Should round right and exclude the surrogate. StringSlicer slicer_begin(text, ellipsis, false, true); - EXPECT_EQ(u"…xyz", slicer_begin.CutString(4, true)); + EXPECT_EQ(std::u16string(kEllipsisUTF16) + u"xyz", + slicer_begin.CutString(4, true)); // Cut surrogate in the middle. Should round right and exclude the surrogate. std::u16string short_text(u"abc" + kSurrogate); @@ -569,8 +607,9 @@ std::u16string dangling_trailing_text = kSurrogate.substr(1); StringSlicer slicer_dangling_trailing(dangling_trailing_text, ellipsis, false, false); - EXPECT_EQ(u"…", slicer_dangling_trailing.CutString(0, true)); - EXPECT_EQ(dangling_trailing_text + u"…", + EXPECT_EQ(std::u16string(kEllipsisUTF16), + slicer_dangling_trailing.CutString(0, true)); + EXPECT_EQ(dangling_trailing_text + kEllipsisUTF16, slicer_dangling_trailing.CutString(1, true)); } @@ -580,8 +619,10 @@ // LATIN SMALL LETTER E + COMBINING ACUTE ACCENT + COMBINING CEDILLA // LATIN SMALL LETTER X + COMBINING ENCLOSING KEYCAP // DEVANAGARI LETTER DDA + DEVANAGARI VOWEL SIGN I - std::u16string text(u"e\u0301\u0327 x\u20e3 \u0921\u093f"); - std::u16string ellipsis(u"…"); + const char16_t kText[] = {'e', 0x301, 0x327, ' ', 'x', + 0x20E3, ' ', 0x921, 0x93F, 0}; + std::u16string text(kText); + std::u16string ellipsis(kEllipsisUTF16); StringSlicer slicer(text, ellipsis, false, false); // Attempt to cut the string for all lengths. When a combining sequence is @@ -589,31 +630,33 @@ // Whitespace is also cut adjacent to the ellipsis. // First sequence: - EXPECT_EQ(u"…", slicer.CutString(0, true)); - EXPECT_EQ(u"…", slicer.CutString(1, true)); - EXPECT_EQ(u"…", slicer.CutString(2, true)); - EXPECT_EQ(text.substr(0, 3) + u"…", slicer.CutString(3, true)); + EXPECT_EQ(std::u16string(kEllipsisUTF16), slicer.CutString(0, true)); + EXPECT_EQ(std::u16string(kEllipsisUTF16), slicer.CutString(1, true)); + EXPECT_EQ(std::u16string(kEllipsisUTF16), slicer.CutString(2, true)); + EXPECT_EQ(text.substr(0, 3) + kEllipsisUTF16, slicer.CutString(3, true)); // Second sequence: - EXPECT_EQ(text.substr(0, 3) + u"…", slicer.CutString(4, true)); - EXPECT_EQ(text.substr(0, 3) + u"…", slicer.CutString(5, true)); - EXPECT_EQ(text.substr(0, 6) + u"…", slicer.CutString(6, true)); + EXPECT_EQ(text.substr(0, 3) + kEllipsisUTF16, slicer.CutString(4, true)); + EXPECT_EQ(text.substr(0, 3) + kEllipsisUTF16, slicer.CutString(5, true)); + EXPECT_EQ(text.substr(0, 6) + kEllipsisUTF16, slicer.CutString(6, true)); // Third sequence: - EXPECT_EQ(text.substr(0, 6) + u"…", slicer.CutString(7, true)); - EXPECT_EQ(text.substr(0, 6) + u"…", slicer.CutString(8, true)); - EXPECT_EQ(text + u"…", slicer.CutString(9, true)); + EXPECT_EQ(text.substr(0, 6) + kEllipsisUTF16, slicer.CutString(7, true)); + EXPECT_EQ(text.substr(0, 6) + kEllipsisUTF16, slicer.CutString(8, true)); + EXPECT_EQ(text + kEllipsisUTF16, slicer.CutString(9, true)); // Cut string in the middle, splitting the second sequence in half. Should // round both left and right, excluding the second sequence. StringSlicer slicer_mid(text, ellipsis, true, false); - EXPECT_EQ(text.substr(0, 4) + u"…" + text.substr(6), + EXPECT_EQ(text.substr(0, 4) + kEllipsisUTF16 + text.substr(6), slicer_mid.CutString(9, true)); // String that starts with a dangling combining mark. char16_t dangling_mark_chars[] = {text[1], 0}; std::u16string dangling_mark_text(dangling_mark_chars); StringSlicer slicer_dangling_mark(dangling_mark_text, ellipsis, false, false); - EXPECT_EQ(u"…", slicer_dangling_mark.CutString(0, true)); - EXPECT_EQ(dangling_mark_text + u"…", slicer_dangling_mark.CutString(1, true)); + EXPECT_EQ(std::u16string(kEllipsisUTF16), + slicer_dangling_mark.CutString(0, true)); + EXPECT_EQ(dangling_mark_text + kEllipsisUTF16, + slicer_dangling_mark.CutString(1, true)); } TEST(TextEliderTest, StringSlicerCombiningSurrogate) { @@ -621,46 +664,49 @@ // The following string contains a single combining character sequence: // MUSICAL SYMBOL G CLEF (U+1D11E) + MUSICAL SYMBOL COMBINING FLAG-1 (U+1D16E) // Represented as four UTF-16 code units. - std::u16string text(u"\U0001d11e\U0001d16e"); - std::u16string ellipsis(u"…"); + const char16_t kText[] = {0xD834, 0xDD1E, 0xD834, 0xDD6E, 0}; + std::u16string text(kText); + std::u16string ellipsis(kEllipsisUTF16); StringSlicer slicer(text, ellipsis, false, false); // Attempt to cut the string for all lengths. Should always round left and // exclude the combining sequence. - EXPECT_EQ(u"…", slicer.CutString(0, true)); - EXPECT_EQ(u"…", slicer.CutString(1, true)); - EXPECT_EQ(u"…", slicer.CutString(2, true)); - EXPECT_EQ(u"…", slicer.CutString(3, true)); - EXPECT_EQ(text + u"…", slicer.CutString(4, true)); + EXPECT_EQ(std::u16string(kEllipsisUTF16), slicer.CutString(0, true)); + EXPECT_EQ(std::u16string(kEllipsisUTF16), slicer.CutString(1, true)); + EXPECT_EQ(std::u16string(kEllipsisUTF16), slicer.CutString(2, true)); + EXPECT_EQ(std::u16string(kEllipsisUTF16), slicer.CutString(3, true)); + EXPECT_EQ(text + kEllipsisUTF16, slicer.CutString(4, true)); // Cut string in the middle. Should exclude the sequence. StringSlicer slicer_mid(text, ellipsis, true, false); - EXPECT_EQ(u"…", slicer_mid.CutString(4, true)); + EXPECT_EQ(std::u16string(kEllipsisUTF16), slicer_mid.CutString(4, true)); } TEST(TextEliderTest, ElideString) { struct TestData { - const char16_t* input; + const char* input; size_t max_len; bool result; - const char16_t* output; + const char* output; } cases[] = { - {u"Hello", 0, true, u""}, - {u"", 0, false, u""}, - {u"Hello, my name is Tom", 1, true, u"H"}, - {u"Hello, my name is Tom", 2, true, u"He"}, - {u"Hello, my name is Tom", 3, true, u"H.m"}, - {u"Hello, my name is Tom", 4, true, u"H..m"}, - {u"Hello, my name is Tom", 5, true, u"H...m"}, - {u"Hello, my name is Tom", 6, true, u"He...m"}, - {u"Hello, my name is Tom", 7, true, u"He...om"}, - {u"Hello, my name is Tom", 10, true, u"Hell...Tom"}, - {u"Hello, my name is Tom", 100, false, u"Hello, my name is Tom"}}; + { "Hello", 0, true, "" }, + { "", 0, false, "" }, + { "Hello, my name is Tom", 1, true, "H" }, + { "Hello, my name is Tom", 2, true, "He" }, + { "Hello, my name is Tom", 3, true, "H.m" }, + { "Hello, my name is Tom", 4, true, "H..m" }, + { "Hello, my name is Tom", 5, true, "H...m" }, + { "Hello, my name is Tom", 6, true, "He...m" }, + { "Hello, my name is Tom", 7, true, "He...om" }, + { "Hello, my name is Tom", 10, true, "Hell...Tom" }, + { "Hello, my name is Tom", 100, false, "Hello, my name is Tom" } + }; for (size_t i = 0; i < base::size(cases); ++i) { std::u16string output; EXPECT_EQ(cases[i].result, - ElideString(cases[i].input, cases[i].max_len, &output)); - EXPECT_EQ(cases[i].output, output); + ElideString(UTF8ToUTF16(cases[i].input), + cases[i].max_len, &output)); + EXPECT_EQ(cases[i].output, UTF16ToUTF8(output)); } } @@ -670,51 +716,50 @@ const float test_width = GetStringWidthF(u"Test", font_list); struct TestData { - const char16_t* input; + const char* input; float available_pixel_width; int available_pixel_height; bool truncated_y; - const char16_t* output; + const char* output; } cases[] = { - {u"", 0, 0, false, nullptr}, - {u"", 1, 1, false, nullptr}, - {u"Test", test_width, 0, true, nullptr}, - {u"Test", test_width, 1, false, u"Test"}, - {u"Test", test_width, line_height, false, u"Test"}, - {u"Test Test", test_width, line_height, true, u"Test"}, - {u"Test Test", test_width, line_height + 1, false, u"Test|Test"}, - {u"Test Test", test_width, line_height * 2, false, u"Test|Test"}, - {u"Test Test", test_width, line_height * 3, false, u"Test|Test"}, - {u"Test Test", test_width * 2, line_height * 2, false, u"Test|Test"}, - {u"Test Test", test_width * 3, line_height, false, u"Test Test"}, - {u"Test\nTest", test_width * 3, line_height * 2, false, u"Test|Test"}, - {u"Te\nst Te", test_width, line_height * 3, false, u"Te|st|Te"}, - {u"\nTest", test_width, line_height * 2, false, u"|Test"}, - {u"\nTest", test_width, line_height, true, u""}, - {u"\n\nTest", test_width, line_height * 3, false, u"||Test"}, - {u"\n\nTest", test_width, line_height * 2, true, u"|"}, - {u"Test\n", 2 * test_width, line_height * 5, false, u"Test|"}, - {u"Test\n\n", 2 * test_width, line_height * 5, false, u"Test||"}, - {u"Test\n\n\n", 2 * test_width, line_height * 5, false, u"Test|||"}, - {u"Test\nTest\n\n", 2 * test_width, line_height * 5, false, - u"Test|Test||"}, - {u"Test\n\nTest\n", 2 * test_width, line_height * 5, false, - u"Test||Test|"}, - {u"Test\n\n\nTest", 2 * test_width, line_height * 5, false, - u"Test|||Test"}, - {u"Te ", test_width, line_height, false, u"Te"}, - {u"Te Te Test", test_width, 3 * line_height, false, u"Te|Te|Test"}, + {"", 0, 0, false, nullptr}, + {"", 1, 1, false, nullptr}, + {"Test", test_width, 0, true, nullptr}, + {"Test", test_width, 1, false, "Test"}, + {"Test", test_width, line_height, false, "Test"}, + {"Test Test", test_width, line_height, true, "Test"}, + {"Test Test", test_width, line_height + 1, false, "Test|Test"}, + {"Test Test", test_width, line_height * 2, false, "Test|Test"}, + {"Test Test", test_width, line_height * 3, false, "Test|Test"}, + {"Test Test", test_width * 2, line_height * 2, false, "Test|Test"}, + {"Test Test", test_width * 3, line_height, false, "Test Test"}, + {"Test\nTest", test_width * 3, line_height * 2, false, "Test|Test"}, + {"Te\nst Te", test_width, line_height * 3, false, "Te|st|Te"}, + {"\nTest", test_width, line_height * 2, false, "|Test"}, + {"\nTest", test_width, line_height, true, ""}, + {"\n\nTest", test_width, line_height * 3, false, "||Test"}, + {"\n\nTest", test_width, line_height * 2, true, "|"}, + {"Test\n", 2 * test_width, line_height * 5, false, "Test|"}, + {"Test\n\n", 2 * test_width, line_height * 5, false, "Test||"}, + {"Test\n\n\n", 2 * test_width, line_height * 5, false, "Test|||"}, + {"Test\nTest\n\n", 2 * test_width, line_height * 5, false, "Test|Test||"}, + {"Test\n\nTest\n", 2 * test_width, line_height * 5, false, "Test||Test|"}, + {"Test\n\n\nTest", 2 * test_width, line_height * 5, false, "Test|||Test"}, + {"Te ", test_width, line_height, false, "Te"}, + {"Te Te Test", test_width, 3 * line_height, false, "Te|Te|Test"}, }; for (size_t i = 0; i < base::size(cases); ++i) { std::vector<std::u16string> lines; EXPECT_EQ(cases[i].truncated_y ? INSUFFICIENT_SPACE_VERTICAL : 0, - ElideRectangleText(cases[i].input, font_list, + ElideRectangleText(UTF8ToUTF16(cases[i].input), + font_list, cases[i].available_pixel_width, cases[i].available_pixel_height, - TRUNCATE_LONG_WORDS, &lines)); + TRUNCATE_LONG_WORDS, + &lines)); if (cases[i].output) { - const std::u16string result = base::JoinString(lines, u"|"); + const std::string result = UTF16ToUTF8(base::JoinString(lines, u"|")); EXPECT_EQ(cases[i].output, result) << "Case " << i << " failed!"; } else { EXPECT_TRUE(lines.empty()) << "Case " << i << " failed!"; @@ -731,27 +776,27 @@ std::vector<std::u16string> lines; - auto result_for_width = [&](const char16_t* input, float width) { + auto result_for_width = [&](const char* input, float width) { lines.clear(); - return ElideRectangleText(input, font_list, width, line_height * 4, - WRAP_LONG_WORDS, &lines); + return ElideRectangleText(ASCIIToUTF16(input), font_list, width, + line_height * 4, WRAP_LONG_WORDS, &lines); }; // Test base case. - EXPECT_EQ(0, result_for_width(u"Test", test_width)); + EXPECT_EQ(0, result_for_width("Test", test_width)); EXPECT_EQ(1u, lines.size()); EXPECT_EQ(u"Test", lines[0]); // First word truncated. EXPECT_EQ(INSUFFICIENT_SPACE_FOR_FIRST_WORD, - result_for_width(u"Test", tes_width)); + result_for_width("Test", tes_width)); EXPECT_EQ(2u, lines.size()); EXPECT_EQ(u"Tes", lines[0]); EXPECT_EQ(u"t", lines[1]); // Two words truncated. EXPECT_EQ(INSUFFICIENT_SPACE_FOR_FIRST_WORD, - result_for_width(u"Test\nTest", tes_width)); + result_for_width("Test\nTest", tes_width)); EXPECT_EQ(4u, lines.size()); EXPECT_EQ(u"Tes", lines[0]); EXPECT_EQ(u"t", lines[1]); @@ -759,14 +804,14 @@ EXPECT_EQ(u"t", lines[3]); // Word truncated, but not the first. - EXPECT_EQ(0, result_for_width(u"T Test", tes_width)); + EXPECT_EQ(0, result_for_width("T Test", tes_width)); EXPECT_EQ(3u, lines.size()); EXPECT_EQ(u"T", lines[0]); EXPECT_EQ(u"Tes", lines[1]); EXPECT_EQ(u"t", lines[2]); // Leading \n. - EXPECT_EQ(0, result_for_width(u"\nTest", tes_width)); + EXPECT_EQ(0, result_for_width("\nTest", tes_width)); EXPECT_EQ(3u, lines.size()); EXPECT_EQ(u"", lines[0]); EXPECT_EQ(u"Tes", lines[1]); @@ -782,17 +827,17 @@ INSUFFICIENT_SPACE_HORIZONTAL | INSUFFICIENT_SPACE_VERTICAL; struct TestData { - const char16_t* input; + const char* input; float available_pixel_width; int available_pixel_height; bool wrap_words; bool truncated_x; - const char16_t* output; + const char* output; } cases[] = { - {u"Test T.", test_t_width, line_height * 2, false, false, u"Test|T."}, - {u"Test T ?", test_t_width, line_height * 2, false, false, u"Test|T ?"}, - {u"Test. Test", test_width, line_height * 3, false, true, u"Test|Test"}, - {u"Test. Test", test_width, line_height * 3, true, false, u"Test|.|Test"}, + { "Test T.", test_t_width, line_height * 2, false, false, "Test|T." }, + { "Test T ?", test_t_width, line_height * 2, false, false, "Test|T ?" }, + { "Test. Test", test_width, line_height * 3, false, true, "Test|Test" }, + { "Test. Test", test_width, line_height * 3, true, false, "Test|.|Test" }, }; for (size_t i = 0; i < base::size(cases); ++i) { @@ -800,12 +845,13 @@ const WordWrapBehavior wrap_behavior = (cases[i].wrap_words ? WRAP_LONG_WORDS : TRUNCATE_LONG_WORDS); EXPECT_EQ(cases[i].truncated_x ? INSUFFICIENT_SPACE_HORIZONTAL : 0, - ElideRectangleText( - cases[i].input, font_list, cases[i].available_pixel_width, - cases[i].available_pixel_height, wrap_behavior, &lines) & + ElideRectangleText(UTF8ToUTF16(cases[i].input), font_list, + cases[i].available_pixel_width, + cases[i].available_pixel_height, wrap_behavior, + &lines) & kResultMask); if (cases[i].output) { - const std::u16string result = base::JoinString(lines, u"|"); + const std::string result = UTF16ToUTF8(base::JoinString(lines, u"|")); EXPECT_EQ(cases[i].output, result) << "Case " << i << " failed!"; } else { EXPECT_TRUE(lines.empty()) << "Case " << i << " failed!"; @@ -816,58 +862,60 @@ TEST(TextEliderTest, ElideRectangleTextLongWords) { const FontList font_list; const int kAvailableHeight = 1000; - const std::u16string kElidedTesting = u"Tes…"; + const std::u16string kElidedTesting = + UTF8ToUTF16(std::string("Tes") + kEllipsis); const float elided_width = GetStringWidthF(kElidedTesting, font_list); const float test_width = GetStringWidthF(u"Test", font_list); constexpr int kResultMask = INSUFFICIENT_SPACE_HORIZONTAL | INSUFFICIENT_SPACE_VERTICAL; struct TestData { - const char16_t* input; + const char* input; float available_pixel_width; WordWrapBehavior wrap_behavior; bool truncated_x; - const char16_t* output; + const char* output; } cases[] = { - {u"Testing", test_width, IGNORE_LONG_WORDS, false, u"Testing"}, - {u"X Testing", test_width, IGNORE_LONG_WORDS, false, u"X|Testing"}, - {u"Test Testing", test_width, IGNORE_LONG_WORDS, false, u"Test|Testing"}, - {u"Test\nTesting", test_width, IGNORE_LONG_WORDS, false, u"Test|Testing"}, - {u"Test Tests ", test_width, IGNORE_LONG_WORDS, false, u"Test|Tests"}, - {u"Test Tests T", test_width, IGNORE_LONG_WORDS, false, u"Test|Tests|T"}, + { "Testing", test_width, IGNORE_LONG_WORDS, false, "Testing" }, + { "X Testing", test_width, IGNORE_LONG_WORDS, false, "X|Testing" }, + { "Test Testing", test_width, IGNORE_LONG_WORDS, false, "Test|Testing" }, + { "Test\nTesting", test_width, IGNORE_LONG_WORDS, false, "Test|Testing" }, + { "Test Tests ", test_width, IGNORE_LONG_WORDS, false, "Test|Tests" }, + { "Test Tests T", test_width, IGNORE_LONG_WORDS, false, "Test|Tests|T" }, - {u"Testing", elided_width, ELIDE_LONG_WORDS, true, u"Tes…"}, - {u"X Testing", elided_width, ELIDE_LONG_WORDS, true, u"X|Tes…"}, - {u"Test Testing", elided_width, ELIDE_LONG_WORDS, true, u"Test|Tes…"}, - {u"Test\nTesting", elided_width, ELIDE_LONG_WORDS, true, u"Test|Tes…"}, + { "Testing", elided_width, ELIDE_LONG_WORDS, true, "Tes..." }, + { "X Testing", elided_width, ELIDE_LONG_WORDS, true, "X|Tes..." }, + { "Test Testing", elided_width, ELIDE_LONG_WORDS, true, "Test|Tes..." }, + { "Test\nTesting", elided_width, ELIDE_LONG_WORDS, true, "Test|Tes..." }, - {u"Testing", test_width, TRUNCATE_LONG_WORDS, true, u"Test"}, - {u"X Testing", test_width, TRUNCATE_LONG_WORDS, true, u"X|Test"}, - {u"Test Testing", test_width, TRUNCATE_LONG_WORDS, true, u"Test|Test"}, - {u"Test\nTesting", test_width, TRUNCATE_LONG_WORDS, true, u"Test|Test"}, - {u"Test Tests ", test_width, TRUNCATE_LONG_WORDS, true, u"Test|Test"}, - {u"Test Tests T", test_width, TRUNCATE_LONG_WORDS, true, u"Test|Test|T"}, + { "Testing", test_width, TRUNCATE_LONG_WORDS, true, "Test" }, + { "X Testing", test_width, TRUNCATE_LONG_WORDS, true, "X|Test" }, + { "Test Testing", test_width, TRUNCATE_LONG_WORDS, true, "Test|Test" }, + { "Test\nTesting", test_width, TRUNCATE_LONG_WORDS, true, "Test|Test" }, + { "Test Tests ", test_width, TRUNCATE_LONG_WORDS, true, "Test|Test" }, + { "Test Tests T", test_width, TRUNCATE_LONG_WORDS, true, "Test|Test|T" }, - {u"Testing", test_width, WRAP_LONG_WORDS, false, u"Test|ing"}, - {u"X Testing", test_width, WRAP_LONG_WORDS, false, u"X|Test|ing"}, - {u"Test Testing", test_width, WRAP_LONG_WORDS, false, u"Test|Test|ing"}, - {u"Test\nTesting", test_width, WRAP_LONG_WORDS, false, u"Test|Test|ing"}, - {u"Test Tests ", test_width, WRAP_LONG_WORDS, false, u"Test|Test|s"}, - {u"Test Tests T", test_width, WRAP_LONG_WORDS, false, u"Test|Test|s T"}, - {u"TestTestTest", test_width, WRAP_LONG_WORDS, false, u"Test|Test|Test"}, - {u"TestTestTestT", test_width, WRAP_LONG_WORDS, false, - u"Test|Test|Test|T"}, + { "Testing", test_width, WRAP_LONG_WORDS, false, "Test|ing" }, + { "X Testing", test_width, WRAP_LONG_WORDS, false, "X|Test|ing" }, + { "Test Testing", test_width, WRAP_LONG_WORDS, false, "Test|Test|ing" }, + { "Test\nTesting", test_width, WRAP_LONG_WORDS, false, "Test|Test|ing" }, + { "Test Tests ", test_width, WRAP_LONG_WORDS, false, "Test|Test|s" }, + { "Test Tests T", test_width, WRAP_LONG_WORDS, false, "Test|Test|s T" }, + { "TestTestTest", test_width, WRAP_LONG_WORDS, false, "Test|Test|Test" }, + { "TestTestTestT", test_width, WRAP_LONG_WORDS, false, "Test|Test|Test|T" }, }; for (size_t i = 0; i < base::size(cases); ++i) { std::vector<std::u16string> lines; - EXPECT_EQ(cases[i].truncated_x ? INSUFFICIENT_SPACE_HORIZONTAL : 0, - ElideRectangleText( - cases[i].input, font_list, cases[i].available_pixel_width, - kAvailableHeight, cases[i].wrap_behavior, &lines) & - kResultMask); - std::u16string expected_output(cases[i].output); - const std::u16string result = base::JoinString(lines, u"|"); + EXPECT_EQ( + cases[i].truncated_x ? INSUFFICIENT_SPACE_HORIZONTAL : 0, + ElideRectangleText(UTF8ToUTF16(cases[i].input), font_list, + cases[i].available_pixel_width, kAvailableHeight, + cases[i].wrap_behavior, &lines) & + kResultMask); + std::string expected_output(cases[i].output); + base::ReplaceSubstringsAfterOffset(&expected_output, 0, "...", kEllipsis); + const std::string result = UTF16ToUTF8(base::JoinString(lines, u"|")); EXPECT_EQ(expected_output, result) << "Case " << i << " failed!"; } } @@ -885,10 +933,14 @@ #endif const float kAvailableWidth = 235; const int kAvailableHeight = 1000; - const char16_t text[] = u"that Russian place we used to go to after fencing"; + const char text[] = "that Russian place we used to go to after fencing"; std::vector<std::u16string> lines; - EXPECT_EQ(0, ElideRectangleText(text, font_list, kAvailableWidth, - kAvailableHeight, WRAP_LONG_WORDS, &lines)); + EXPECT_EQ(0, ElideRectangleText(UTF8ToUTF16(text), + font_list, + kAvailableWidth, + kAvailableHeight, + WRAP_LONG_WORDS, + &lines)); ASSERT_EQ(2u, lines.size()); EXPECT_LE(GetStringWidthF(lines[0], font_list), kAvailableWidth); EXPECT_LE(GetStringWidthF(lines[1], font_list), kAvailableWidth); @@ -902,10 +954,10 @@ FontList font_list; font_list = FontList("Noto Sans UI,ui-sans, 12px"); SetFontRenderParamsDeviceScaleFactor(1.25f); -#define WIDTH(x) GetStringWidthF((x), font_list) - EXPECT_EQ(WIDTH(u"The administrator for this account has"), - WIDTH(u"The ") + WIDTH(u"administrator ") + WIDTH(u"for ") + - WIDTH(u"this ") + WIDTH(u"account ") + WIDTH(u"has")); +#define WIDTH(x) GetStringWidthF(UTF8ToUTF16(x), font_list) + EXPECT_EQ(WIDTH("The administrator for this account has"), + WIDTH("The ") + WIDTH("administrator ") + WIDTH("for ") + + WIDTH("this ") + WIDTH("account ") + WIDTH("has")); #undef WIDTH SetFontRenderParamsDeviceScaleFactor(1.0f); } @@ -913,172 +965,181 @@ TEST(TextEliderTest, ElideRectangleString) { struct TestData { - const char16_t* input; + const char* input; int max_rows; int max_cols; bool result; - const char16_t* output; + const char* output; } cases[] = { - {u"", 0, 0, false, u""}, - {u"", 1, 1, false, u""}, - {u"Hi, my name is\nTom", 0, 0, true, u"..."}, - {u"Hi, my name is\nTom", 1, 0, true, u"\n..."}, - {u"Hi, my name is\nTom", 0, 1, true, u"..."}, - {u"Hi, my name is\nTom", 1, 1, true, u"H\n..."}, - {u"Hi, my name is\nTom", 2, 1, true, u"H\ni\n..."}, - {u"Hi, my name is\nTom", 3, 1, true, u"H\ni\n,\n..."}, - {u"Hi, my name is\nTom", 4, 1, true, u"H\ni\n,\n \n..."}, - {u"Hi, my name is\nTom", 5, 1, true, u"H\ni\n,\n \nm\n..."}, - {u"Hi, my name is\nTom", 0, 2, true, u"..."}, - {u"Hi, my name is\nTom", 1, 2, true, u"Hi\n..."}, - {u"Hi, my name is\nTom", 2, 2, true, u"Hi\n, \n..."}, - {u"Hi, my name is\nTom", 3, 2, true, u"Hi\n, \nmy\n..."}, - {u"Hi, my name is\nTom", 4, 2, true, u"Hi\n, \nmy\n n\n..."}, - {u"Hi, my name is\nTom", 5, 2, true, u"Hi\n, \nmy\n n\nam\n..."}, - {u"Hi, my name is\nTom", 0, 3, true, u"..."}, - {u"Hi, my name is\nTom", 1, 3, true, u"Hi,\n..."}, - {u"Hi, my name is\nTom", 2, 3, true, u"Hi,\n my\n..."}, - {u"Hi, my name is\nTom", 3, 3, true, u"Hi,\n my\n na\n..."}, - {u"Hi, my name is\nTom", 4, 3, true, u"Hi,\n my\n na\nme \n..."}, - {u"Hi, my name is\nTom", 5, 3, true, u"Hi,\n my\n na\nme \nis\n..."}, - {u"Hi, my name is\nTom", 1, 4, true, u"Hi, \n..."}, - {u"Hi, my name is\nTom", 2, 4, true, u"Hi, \nmy n\n..."}, - {u"Hi, my name is\nTom", 3, 4, true, u"Hi, \nmy n\name \n..."}, - {u"Hi, my name is\nTom", 4, 4, true, u"Hi, \nmy n\name \nis\n..."}, - {u"Hi, my name is\nTom", 5, 4, false, u"Hi, \nmy n\name \nis\nTom"}, - {u"Hi, my name is\nTom", 1, 5, true, u"Hi, \n..."}, - {u"Hi, my name is\nTom", 2, 5, true, u"Hi, \nmy na\n..."}, - {u"Hi, my name is\nTom", 3, 5, true, u"Hi, \nmy na\nme \n..."}, - {u"Hi, my name is\nTom", 4, 5, true, u"Hi, \nmy na\nme \nis\n..."}, - {u"Hi, my name is\nTom", 5, 5, false, u"Hi, \nmy na\nme \nis\nTom"}, - {u"Hi, my name is\nTom", 1, 6, true, u"Hi, \n..."}, - {u"Hi, my name is\nTom", 2, 6, true, u"Hi, \nmy \n..."}, - {u"Hi, my name is\nTom", 3, 6, true, u"Hi, \nmy \nname \n..."}, - {u"Hi, my name is\nTom", 4, 6, true, u"Hi, \nmy \nname \nis\n..."}, - {u"Hi, my name is\nTom", 5, 6, false, u"Hi, \nmy \nname \nis\nTom"}, - {u"Hi, my name is\nTom", 1, 7, true, u"Hi, \n..."}, - {u"Hi, my name is\nTom", 2, 7, true, u"Hi, \nmy \n..."}, - {u"Hi, my name is\nTom", 3, 7, true, u"Hi, \nmy \nname \n..."}, - {u"Hi, my name is\nTom", 4, 7, true, u"Hi, \nmy \nname \nis\n..."}, - {u"Hi, my name is\nTom", 5, 7, false, u"Hi, \nmy \nname \nis\nTom"}, - {u"Hi, my name is\nTom", 1, 8, true, u"Hi, my \n..."}, - {u"Hi, my name is\nTom", 2, 8, true, u"Hi, my \nname \n..."}, - {u"Hi, my name is\nTom", 3, 8, true, u"Hi, my \nname \nis\n..."}, - {u"Hi, my name is\nTom", 4, 8, false, u"Hi, my \nname \nis\nTom"}, - {u"Hi, my name is\nTom", 1, 9, true, u"Hi, my \n..."}, - {u"Hi, my name is\nTom", 2, 9, true, u"Hi, my \nname is\n..."}, - {u"Hi, my name is\nTom", 3, 9, false, u"Hi, my \nname is\nTom"}, - {u"Hi, my name is\nTom", 1, 10, true, u"Hi, my \n..."}, - {u"Hi, my name is\nTom", 2, 10, true, u"Hi, my \nname is\n..."}, - {u"Hi, my name is\nTom", 3, 10, false, u"Hi, my \nname is\nTom"}, - {u"Hi, my name is\nTom", 1, 11, true, u"Hi, my \n..."}, - {u"Hi, my name is\nTom", 2, 11, true, u"Hi, my \nname is\n..."}, - {u"Hi, my name is\nTom", 3, 11, false, u"Hi, my \nname is\nTom"}, - {u"Hi, my name is\nTom", 1, 12, true, u"Hi, my \n..."}, - {u"Hi, my name is\nTom", 2, 12, true, u"Hi, my \nname is\n..."}, - {u"Hi, my name is\nTom", 3, 12, false, u"Hi, my \nname is\nTom"}, - {u"Hi, my name is\nTom", 1, 13, true, u"Hi, my name \n..."}, - {u"Hi, my name is\nTom", 2, 13, true, u"Hi, my name \nis\n..."}, - {u"Hi, my name is\nTom", 3, 13, false, u"Hi, my name \nis\nTom"}, - {u"Hi, my name is\nTom", 1, 20, true, u"Hi, my name is\n..."}, - {u"Hi, my name is\nTom", 2, 20, false, u"Hi, my name is\nTom"}, - {u"Hi, my name is Tom", 1, 40, false, u"Hi, my name is Tom"}, + { "", 0, 0, false, "" }, + { "", 1, 1, false, "" }, + { "Hi, my name is\nTom", 0, 0, true, "..." }, + { "Hi, my name is\nTom", 1, 0, true, "\n..." }, + { "Hi, my name is\nTom", 0, 1, true, "..." }, + { "Hi, my name is\nTom", 1, 1, true, "H\n..." }, + { "Hi, my name is\nTom", 2, 1, true, "H\ni\n..." }, + { "Hi, my name is\nTom", 3, 1, true, "H\ni\n,\n..." }, + { "Hi, my name is\nTom", 4, 1, true, "H\ni\n,\n \n..." }, + { "Hi, my name is\nTom", 5, 1, true, "H\ni\n,\n \nm\n..." }, + { "Hi, my name is\nTom", 0, 2, true, "..." }, + { "Hi, my name is\nTom", 1, 2, true, "Hi\n..." }, + { "Hi, my name is\nTom", 2, 2, true, "Hi\n, \n..." }, + { "Hi, my name is\nTom", 3, 2, true, "Hi\n, \nmy\n..." }, + { "Hi, my name is\nTom", 4, 2, true, "Hi\n, \nmy\n n\n..." }, + { "Hi, my name is\nTom", 5, 2, true, "Hi\n, \nmy\n n\nam\n..." }, + { "Hi, my name is\nTom", 0, 3, true, "..." }, + { "Hi, my name is\nTom", 1, 3, true, "Hi,\n..." }, + { "Hi, my name is\nTom", 2, 3, true, "Hi,\n my\n..." }, + { "Hi, my name is\nTom", 3, 3, true, "Hi,\n my\n na\n..." }, + { "Hi, my name is\nTom", 4, 3, true, "Hi,\n my\n na\nme \n..." }, + { "Hi, my name is\nTom", 5, 3, true, "Hi,\n my\n na\nme \nis\n..." }, + { "Hi, my name is\nTom", 1, 4, true, "Hi, \n..." }, + { "Hi, my name is\nTom", 2, 4, true, "Hi, \nmy n\n..." }, + { "Hi, my name is\nTom", 3, 4, true, "Hi, \nmy n\name \n..." }, + { "Hi, my name is\nTom", 4, 4, true, "Hi, \nmy n\name \nis\n..." }, + { "Hi, my name is\nTom", 5, 4, false, "Hi, \nmy n\name \nis\nTom" }, + { "Hi, my name is\nTom", 1, 5, true, "Hi, \n..." }, + { "Hi, my name is\nTom", 2, 5, true, "Hi, \nmy na\n..." }, + { "Hi, my name is\nTom", 3, 5, true, "Hi, \nmy na\nme \n..." }, + { "Hi, my name is\nTom", 4, 5, true, "Hi, \nmy na\nme \nis\n..." }, + { "Hi, my name is\nTom", 5, 5, false, "Hi, \nmy na\nme \nis\nTom" }, + { "Hi, my name is\nTom", 1, 6, true, "Hi, \n..." }, + { "Hi, my name is\nTom", 2, 6, true, "Hi, \nmy \n..." }, + { "Hi, my name is\nTom", 3, 6, true, "Hi, \nmy \nname \n..." }, + { "Hi, my name is\nTom", 4, 6, true, "Hi, \nmy \nname \nis\n..." }, + { "Hi, my name is\nTom", 5, 6, false, "Hi, \nmy \nname \nis\nTom" }, + { "Hi, my name is\nTom", 1, 7, true, "Hi, \n..." }, + { "Hi, my name is\nTom", 2, 7, true, "Hi, \nmy \n..." }, + { "Hi, my name is\nTom", 3, 7, true, "Hi, \nmy \nname \n..." }, + { "Hi, my name is\nTom", 4, 7, true, "Hi, \nmy \nname \nis\n..." }, + { "Hi, my name is\nTom", 5, 7, false, "Hi, \nmy \nname \nis\nTom" }, + { "Hi, my name is\nTom", 1, 8, true, "Hi, my \n..." }, + { "Hi, my name is\nTom", 2, 8, true, "Hi, my \nname \n..." }, + { "Hi, my name is\nTom", 3, 8, true, "Hi, my \nname \nis\n..." }, + { "Hi, my name is\nTom", 4, 8, false, "Hi, my \nname \nis\nTom" }, + { "Hi, my name is\nTom", 1, 9, true, "Hi, my \n..." }, + { "Hi, my name is\nTom", 2, 9, true, "Hi, my \nname is\n..." }, + { "Hi, my name is\nTom", 3, 9, false, "Hi, my \nname is\nTom" }, + { "Hi, my name is\nTom", 1, 10, true, "Hi, my \n..." }, + { "Hi, my name is\nTom", 2, 10, true, "Hi, my \nname is\n..." }, + { "Hi, my name is\nTom", 3, 10, false, "Hi, my \nname is\nTom" }, + { "Hi, my name is\nTom", 1, 11, true, "Hi, my \n..." }, + { "Hi, my name is\nTom", 2, 11, true, "Hi, my \nname is\n..." }, + { "Hi, my name is\nTom", 3, 11, false, "Hi, my \nname is\nTom" }, + { "Hi, my name is\nTom", 1, 12, true, "Hi, my \n..." }, + { "Hi, my name is\nTom", 2, 12, true, "Hi, my \nname is\n..." }, + { "Hi, my name is\nTom", 3, 12, false, "Hi, my \nname is\nTom" }, + { "Hi, my name is\nTom", 1, 13, true, "Hi, my name \n..." }, + { "Hi, my name is\nTom", 2, 13, true, "Hi, my name \nis\n..." }, + { "Hi, my name is\nTom", 3, 13, false, "Hi, my name \nis\nTom" }, + { "Hi, my name is\nTom", 1, 20, true, "Hi, my name is\n..." }, + { "Hi, my name is\nTom", 2, 20, false, "Hi, my name is\nTom" }, + { "Hi, my name is Tom", 1, 40, false, "Hi, my name is Tom" }, }; std::u16string output; for (size_t i = 0; i < base::size(cases); ++i) { EXPECT_EQ(cases[i].result, - ElideRectangleString(cases[i].input, cases[i].max_rows, - cases[i].max_cols, true, &output)); - EXPECT_EQ(cases[i].output, output); + ElideRectangleString(UTF8ToUTF16(cases[i].input), + cases[i].max_rows, cases[i].max_cols, + true, &output)); + EXPECT_EQ(cases[i].output, UTF16ToUTF8(output)); } } TEST(TextEliderTest, ElideRectangleStringNotStrict) { struct TestData { - const char16_t* input; + const char* input; int max_rows; int max_cols; bool result; - const char16_t* output; + const char* output; } cases[] = { - {u"", 0, 0, false, u""}, - {u"", 1, 1, false, u""}, - {u"Hi, my name_is\nDick", 0, 0, true, u"..."}, - {u"Hi, my name_is\nDick", 1, 0, true, u"\n..."}, - {u"Hi, my name_is\nDick", 0, 1, true, u"..."}, - {u"Hi, my name_is\nDick", 1, 1, true, u"H\n..."}, - {u"Hi, my name_is\nDick", 2, 1, true, u"H\ni\n..."}, - {u"Hi, my name_is\nDick", 3, 1, true, u"H\ni\n,\n..."}, - {u"Hi, my name_is\nDick", 4, 1, true, u"H\ni\n,\n \n..."}, - {u"Hi, my name_is\nDick", 5, 1, true, u"H\ni\n,\n \nm\n..."}, - {u"Hi, my name_is\nDick", 0, 2, true, u"..."}, - {u"Hi, my name_is\nDick", 1, 2, true, u"Hi\n..."}, - {u"Hi, my name_is\nDick", 2, 2, true, u"Hi\n, \n..."}, - {u"Hi, my name_is\nDick", 3, 2, true, u"Hi\n, \nmy\n..."}, - {u"Hi, my name_is\nDick", 4, 2, true, u"Hi\n, \nmy\n n\n..."}, - {u"Hi, my name_is\nDick", 5, 2, true, u"Hi\n, \nmy\n n\nam\n..."}, - {u"Hi, my name_is\nDick", 0, 3, true, u"..."}, - {u"Hi, my name_is\nDick", 1, 3, true, u"Hi,\n..."}, - {u"Hi, my name_is\nDick", 2, 3, true, u"Hi,\n my\n..."}, - {u"Hi, my name_is\nDick", 3, 3, true, u"Hi,\n my\n na\n..."}, - {u"Hi, my name_is\nDick", 4, 3, true, u"Hi,\n my\n na\nme_\n..."}, - {u"Hi, my name_is\nDick", 5, 3, true, u"Hi,\n my\n na\nme_\nis\n..."}, - {u"Hi, my name_is\nDick", 1, 4, true, u"Hi, ..."}, - {u"Hi, my name_is\nDick", 2, 4, true, u"Hi, my n\n..."}, - {u"Hi, my name_is\nDick", 3, 4, true, u"Hi, my n\name_\n..."}, - {u"Hi, my name_is\nDick", 4, 4, true, u"Hi, my n\name_\nis\n..."}, - {u"Hi, my name_is\nDick", 5, 4, false, u"Hi, my n\name_\nis\nDick"}, - {u"Hi, my name_is\nDick", 1, 5, true, u"Hi, ..."}, - {u"Hi, my name_is\nDick", 2, 5, true, u"Hi, my na\n..."}, - {u"Hi, my name_is\nDick", 3, 5, true, u"Hi, my na\nme_is\n..."}, - {u"Hi, my name_is\nDick", 4, 5, true, u"Hi, my na\nme_is\n\n..."}, - {u"Hi, my name_is\nDick", 5, 5, false, u"Hi, my na\nme_is\n\nDick"}, - {u"Hi, my name_is\nDick", 1, 6, true, u"Hi, ..."}, - {u"Hi, my name_is\nDick", 2, 6, true, u"Hi, my nam\n..."}, - {u"Hi, my name_is\nDick", 3, 6, true, u"Hi, my nam\ne_is\n..."}, - {u"Hi, my name_is\nDick", 4, 6, false, u"Hi, my nam\ne_is\nDick"}, - {u"Hi, my name_is\nDick", 5, 6, false, u"Hi, my nam\ne_is\nDick"}, - {u"Hi, my name_is\nDick", 1, 7, true, u"Hi, ..."}, - {u"Hi, my name_is\nDick", 2, 7, true, u"Hi, my name\n..."}, - {u"Hi, my name_is\nDick", 3, 7, true, u"Hi, my name\n_is\n..."}, - {u"Hi, my name_is\nDick", 4, 7, false, u"Hi, my name\n_is\nDick"}, - {u"Hi, my name_is\nDick", 5, 7, false, u"Hi, my name\n_is\nDick"}, - {u"Hi, my name_is\nDick", 1, 8, true, u"Hi, my n\n..."}, - {u"Hi, my name_is\nDick", 2, 8, true, u"Hi, my n\name_is\n..."}, - {u"Hi, my name_is\nDick", 3, 8, false, u"Hi, my n\name_is\nDick"}, - {u"Hi, my name_is\nDick", 1, 9, true, u"Hi, my ..."}, - {u"Hi, my name_is\nDick", 2, 9, true, u"Hi, my name_is\n..."}, - {u"Hi, my name_is\nDick", 3, 9, false, u"Hi, my name_is\nDick"}, - {u"Hi, my name_is\nDick", 1, 10, true, u"Hi, my ..."}, - {u"Hi, my name_is\nDick", 2, 10, true, u"Hi, my name_is\n..."}, - {u"Hi, my name_is\nDick", 3, 10, false, u"Hi, my name_is\nDick"}, - {u"Hi, my name_is\nDick", 1, 11, true, u"Hi, my ..."}, - {u"Hi, my name_is\nDick", 2, 11, true, u"Hi, my name_is\n..."}, - {u"Hi, my name_is\nDick", 3, 11, false, u"Hi, my name_is\nDick"}, - {u"Hi, my name_is\nDick", 1, 12, true, u"Hi, my ..."}, - {u"Hi, my name_is\nDick", 2, 12, true, u"Hi, my name_is\n..."}, - {u"Hi, my name_is\nDick", 3, 12, false, u"Hi, my name_is\nDick"}, - {u"Hi, my name_is\nDick", 1, 13, true, u"Hi, my ..."}, - {u"Hi, my name_is\nDick", 2, 13, true, u"Hi, my name_is\n..."}, - {u"Hi, my name_is\nDick", 3, 13, false, u"Hi, my name_is\nDick"}, - {u"Hi, my name_is\nDick", 1, 20, true, u"Hi, my name_is\n..."}, - {u"Hi, my name_is\nDick", 2, 20, false, u"Hi, my name_is\nDick"}, - {u"Hi, my name_is Dick", 1, 40, false, u"Hi, my name_is Dick"}, + { "", 0, 0, false, "" }, + { "", 1, 1, false, "" }, + { "Hi, my name_is\nDick", 0, 0, true, "..." }, + { "Hi, my name_is\nDick", 1, 0, true, "\n..." }, + { "Hi, my name_is\nDick", 0, 1, true, "..." }, + { "Hi, my name_is\nDick", 1, 1, true, "H\n..." }, + { "Hi, my name_is\nDick", 2, 1, true, "H\ni\n..." }, + { "Hi, my name_is\nDick", 3, 1, true, "H\ni\n,\n..." }, + { "Hi, my name_is\nDick", 4, 1, true, "H\ni\n,\n \n..." }, + { "Hi, my name_is\nDick", 5, 1, true, "H\ni\n,\n \nm\n..." }, + { "Hi, my name_is\nDick", 0, 2, true, "..." }, + { "Hi, my name_is\nDick", 1, 2, true, "Hi\n..." }, + { "Hi, my name_is\nDick", 2, 2, true, "Hi\n, \n..." }, + { "Hi, my name_is\nDick", 3, 2, true, "Hi\n, \nmy\n..." }, + { "Hi, my name_is\nDick", 4, 2, true, "Hi\n, \nmy\n n\n..." }, + { "Hi, my name_is\nDick", 5, 2, true, "Hi\n, \nmy\n n\nam\n..." }, + { "Hi, my name_is\nDick", 0, 3, true, "..." }, + { "Hi, my name_is\nDick", 1, 3, true, "Hi,\n..." }, + { "Hi, my name_is\nDick", 2, 3, true, "Hi,\n my\n..." }, + { "Hi, my name_is\nDick", 3, 3, true, "Hi,\n my\n na\n..." }, + { "Hi, my name_is\nDick", 4, 3, true, "Hi,\n my\n na\nme_\n..." }, + { "Hi, my name_is\nDick", 5, 3, true, "Hi,\n my\n na\nme_\nis\n..." }, + { "Hi, my name_is\nDick", 1, 4, true, "Hi, ..." }, + { "Hi, my name_is\nDick", 2, 4, true, "Hi, my n\n..." }, + { "Hi, my name_is\nDick", 3, 4, true, "Hi, my n\name_\n..." }, + { "Hi, my name_is\nDick", 4, 4, true, "Hi, my n\name_\nis\n..." }, + { "Hi, my name_is\nDick", 5, 4, false, "Hi, my n\name_\nis\nDick" }, + { "Hi, my name_is\nDick", 1, 5, true, "Hi, ..." }, + { "Hi, my name_is\nDick", 2, 5, true, "Hi, my na\n..." }, + { "Hi, my name_is\nDick", 3, 5, true, "Hi, my na\nme_is\n..." }, + { "Hi, my name_is\nDick", 4, 5, true, "Hi, my na\nme_is\n\n..." }, + { "Hi, my name_is\nDick", 5, 5, false, "Hi, my na\nme_is\n\nDick" }, + { "Hi, my name_is\nDick", 1, 6, true, "Hi, ..." }, + { "Hi, my name_is\nDick", 2, 6, true, "Hi, my nam\n..." }, + { "Hi, my name_is\nDick", 3, 6, true, "Hi, my nam\ne_is\n..." }, + { "Hi, my name_is\nDick", 4, 6, false, "Hi, my nam\ne_is\nDick" }, + { "Hi, my name_is\nDick", 5, 6, false, "Hi, my nam\ne_is\nDick" }, + { "Hi, my name_is\nDick", 1, 7, true, "Hi, ..." }, + { "Hi, my name_is\nDick", 2, 7, true, "Hi, my name\n..." }, + { "Hi, my name_is\nDick", 3, 7, true, "Hi, my name\n_is\n..." }, + { "Hi, my name_is\nDick", 4, 7, false, "Hi, my name\n_is\nDick" }, + { "Hi, my name_is\nDick", 5, 7, false, "Hi, my name\n_is\nDick" }, + { "Hi, my name_is\nDick", 1, 8, true, "Hi, my n\n..." }, + { "Hi, my name_is\nDick", 2, 8, true, "Hi, my n\name_is\n..." }, + { "Hi, my name_is\nDick", 3, 8, false, "Hi, my n\name_is\nDick" }, + { "Hi, my name_is\nDick", 1, 9, true, "Hi, my ..." }, + { "Hi, my name_is\nDick", 2, 9, true, "Hi, my name_is\n..." }, + { "Hi, my name_is\nDick", 3, 9, false, "Hi, my name_is\nDick" }, + { "Hi, my name_is\nDick", 1, 10, true, "Hi, my ..." }, + { "Hi, my name_is\nDick", 2, 10, true, "Hi, my name_is\n..." }, + { "Hi, my name_is\nDick", 3, 10, false, "Hi, my name_is\nDick" }, + { "Hi, my name_is\nDick", 1, 11, true, "Hi, my ..." }, + { "Hi, my name_is\nDick", 2, 11, true, "Hi, my name_is\n..." }, + { "Hi, my name_is\nDick", 3, 11, false, "Hi, my name_is\nDick" }, + { "Hi, my name_is\nDick", 1, 12, true, "Hi, my ..." }, + { "Hi, my name_is\nDick", 2, 12, true, "Hi, my name_is\n..." }, + { "Hi, my name_is\nDick", 3, 12, false, "Hi, my name_is\nDick" }, + { "Hi, my name_is\nDick", 1, 13, true, "Hi, my ..." }, + { "Hi, my name_is\nDick", 2, 13, true, "Hi, my name_is\n..." }, + { "Hi, my name_is\nDick", 3, 13, false, "Hi, my name_is\nDick" }, + { "Hi, my name_is\nDick", 1, 20, true, "Hi, my name_is\n..." }, + { "Hi, my name_is\nDick", 2, 20, false, "Hi, my name_is\nDick" }, + { "Hi, my name_is Dick", 1, 40, false, "Hi, my name_is Dick" }, }; std::u16string output; for (size_t i = 0; i < base::size(cases); ++i) { EXPECT_EQ(cases[i].result, - ElideRectangleString(cases[i].input, cases[i].max_rows, - cases[i].max_cols, false, &output)); - EXPECT_EQ(cases[i].output, output); + ElideRectangleString(UTF8ToUTF16(cases[i].input), + cases[i].max_rows, cases[i].max_cols, + false, &output)); + EXPECT_EQ(cases[i].output, UTF16ToUTF8(output)); } } TEST(TextEliderTest, ElideRectangleWide16) { // Two greek words separated by space. - const std::u16string str(u"Παγκόσμιος Ιστός"); - const std::u16string out1(u"Παγκ\nόσμι\n..."); - const std::u16string out2(u"Παγκόσμιος \nΙστός"); + const std::u16string str( + u"\x03a0\x03b1\x03b3\x03ba\x03cc\x03c3\x03bc\x03b9" + u"\x03bf\x03c2\x0020\x0399\x03c3\x03c4\x03cc\x03c2"); + const std::u16string out1( + u"\x03a0\x03b1\x03b3\x03ba\n" + u"\x03cc\x03c3\x03bc\x03b9\n" + u"..."); + const std::u16string out2( + u"\x03a0\x03b1\x03b3\x03ba\x03cc\x03c3\x03bc\x03b9\x03bf\x03c2\x0020\n" + u"\x0399\x03c3\x03c4\x03cc\x03c2"); std::u16string output; EXPECT_TRUE(ElideRectangleString(str, 2, 4, true, &output)); EXPECT_EQ(out1, output); @@ -1087,8 +1148,13 @@ } TEST(TextEliderTest, ElideRectangleWide32) { - const std::u16string str(u"𝒜𝒜𝒜𝒜 aaaaa"); - const std::u16string out(u"𝒜𝒜𝒜\n𝒜 \naaa\n..."); + // Four U+1D49C MATHEMATICAL SCRIPT CAPITAL A followed by space "aaaaa". + const std::u16string str(UTF8ToUTF16( + "\xF0\x9D\x92\x9C\xF0\x9D\x92\x9C\xF0\x9D\x92\x9C\xF0\x9D\x92\x9C" + " aaaaa")); + const std::u16string out( + UTF8ToUTF16("\xF0\x9D\x92\x9C\xF0\x9D\x92\x9C\xF0\x9D\x92\x9C\n" + "\xF0\x9D\x92\x9C \naaa\n...")); std::u16string output; EXPECT_TRUE(ElideRectangleString(str, 3, 3, true, &output)); EXPECT_EQ(out, output); @@ -1102,31 +1168,36 @@ EXPECT_EQ(std::u16string(), TruncateString(str, 0, CHARACTER_BREAK)); // Test breaking at character 1. - EXPECT_EQ(u"…", TruncateString(str, 1, WORD_BREAK)); - EXPECT_EQ(u"…", TruncateString(str, 1, CHARACTER_BREAK)); + EXPECT_EQ(L"\x2026", UTF16ToWide(TruncateString(str, 1, WORD_BREAK))); + EXPECT_EQ(L"\x2026", UTF16ToWide(TruncateString(str, 1, CHARACTER_BREAK))); // Test breaking in the middle of the first word. - EXPECT_EQ(u"f…", TruncateString(str, 2, WORD_BREAK)); - EXPECT_EQ(u"f…", TruncateString(str, 2, CHARACTER_BREAK)); + EXPECT_EQ(L"f\x2026", UTF16ToWide(TruncateString(str, 2, WORD_BREAK))); + EXPECT_EQ(L"f\x2026", UTF16ToWide(TruncateString(str, 2, CHARACTER_BREAK))); // Test breaking in between words. - EXPECT_EQ(u"fooooey…", TruncateString(str, 9, WORD_BREAK)); - EXPECT_EQ(u"fooooey…", TruncateString(str, 9, CHARACTER_BREAK)); + EXPECT_EQ(L"fooooey\x2026", UTF16ToWide(TruncateString(str, 9, WORD_BREAK))); + EXPECT_EQ(L"fooooey\x2026", + UTF16ToWide(TruncateString(str, 9, CHARACTER_BREAK))); // Test breaking at the start of a later word. - EXPECT_EQ(u"fooooey…", TruncateString(str, 11, WORD_BREAK)); - EXPECT_EQ(u"fooooey…", TruncateString(str, 11, CHARACTER_BREAK)); + EXPECT_EQ(L"fooooey\x2026", UTF16ToWide(TruncateString(str, 11, WORD_BREAK))); + EXPECT_EQ(L"fooooey\x2026", + UTF16ToWide(TruncateString(str, 11, CHARACTER_BREAK))); // Test breaking in the middle of a word. - EXPECT_EQ(u"fooooey…", TruncateString(str, 12, WORD_BREAK)); - EXPECT_EQ(u"fooooey…", TruncateString(str, 12, CHARACTER_BREAK)); - EXPECT_EQ(u"fooooey…", TruncateString(str, 14, WORD_BREAK)); - EXPECT_EQ(u"fooooey bx…", TruncateString(str, 14, CHARACTER_BREAK)); + EXPECT_EQ(L"fooooey\x2026", UTF16ToWide(TruncateString(str, 12, WORD_BREAK))); + EXPECT_EQ(L"fooooey\x2026", + UTF16ToWide(TruncateString(str, 12, CHARACTER_BREAK))); + EXPECT_EQ(L"fooooey\x2026", UTF16ToWide(TruncateString(str, 14, WORD_BREAK))); + EXPECT_EQ(L"fooooey bx\x2026", + UTF16ToWide(TruncateString(str, 14, CHARACTER_BREAK))); // Test breaking in whitespace at the end of the string. - EXPECT_EQ(u"fooooey bxxxar baz…", TruncateString(str, 22, WORD_BREAK)); - EXPECT_EQ(u"fooooey bxxxar baz…", - TruncateString(str, 22, CHARACTER_BREAK)); + EXPECT_EQ(L"fooooey bxxxar baz\x2026", + UTF16ToWide(TruncateString(str, 22, WORD_BREAK))); + EXPECT_EQ(L"fooooey bxxxar baz\x2026", + UTF16ToWide(TruncateString(str, 22, CHARACTER_BREAK))); // Test breaking at the end of the string. EXPECT_EQ(str, TruncateString(str, str.length(), WORD_BREAK)); @@ -1141,18 +1212,19 @@ std::u16string str2 = u" foo"; // Test breaking in leading whitespace. - EXPECT_EQ(u"…", TruncateString(str2, 2, WORD_BREAK)); - EXPECT_EQ(u"…", TruncateString(str2, 2, CHARACTER_BREAK)); + EXPECT_EQ(L"\x2026", UTF16ToWide(TruncateString(str2, 2, WORD_BREAK))); + EXPECT_EQ(L"\x2026", UTF16ToWide(TruncateString(str2, 2, CHARACTER_BREAK))); // Test breaking at the beginning of the first word, with leading whitespace. - EXPECT_EQ(u"…", TruncateString(str2, 3, WORD_BREAK)); - EXPECT_EQ(u"…", TruncateString(str2, 3, CHARACTER_BREAK)); + EXPECT_EQ(L"\x2026", UTF16ToWide(TruncateString(str2, 3, WORD_BREAK))); + EXPECT_EQ(L"\x2026", UTF16ToWide(TruncateString(str2, 3, CHARACTER_BREAK))); // Test breaking in the middle of the first word, with leading whitespace. - EXPECT_EQ(u"…", TruncateString(str2, 4, WORD_BREAK)); - EXPECT_EQ(u"…", TruncateString(str2, 4, CHARACTER_BREAK)); - EXPECT_EQ(u" f…", TruncateString(str2, 5, WORD_BREAK)); - EXPECT_EQ(u" f…", TruncateString(str2, 5, CHARACTER_BREAK)); + EXPECT_EQ(L"\x2026", UTF16ToWide(TruncateString(str2, 4, WORD_BREAK))); + EXPECT_EQ(L"\x2026", UTF16ToWide(TruncateString(str2, 4, CHARACTER_BREAK))); + EXPECT_EQ(L" f\x2026", UTF16ToWide(TruncateString(str2, 5, WORD_BREAK))); + EXPECT_EQ(L" f\x2026", + UTF16ToWide(TruncateString(str2, 5, CHARACTER_BREAK))); } } // namespace gfx
diff --git a/ui/message_center/notification_list_unittest.cc b/ui/message_center/notification_list_unittest.cc index c2e019dc..5c181f1 100644 --- a/ui/message_center/notification_list_unittest.cc +++ b/ui/message_center/notification_list_unittest.cc
@@ -11,7 +11,6 @@ #include "base/i18n/time_formatting.h" #include "base/macros.h" -#include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" @@ -22,6 +21,8 @@ #include "ui/message_center/public/cpp/notification_types.h" #include "ui/message_center/public/cpp/notifier_id.h" +using base::UTF8ToUTF16; + namespace message_center { using NotificationState = NotificationList::NotificationState; @@ -60,13 +61,13 @@ const RichNotificationData& optional_fields, std::string* id_out) { *id_out = base::StringPrintf(kIdFormat, counter_); - std::unique_ptr<Notification> notification( - new Notification(NOTIFICATION_TYPE_SIMPLE, *id_out, - u"id" + base::NumberToString16(counter_), - u"message" + base::NumberToString16(counter_), - gfx::Image(), kDisplaySource, GURL(), - NotifierId(NotifierType::APPLICATION, kExtensionId), - optional_fields, nullptr)); + std::unique_ptr<Notification> notification(new Notification( + NOTIFICATION_TYPE_SIMPLE, *id_out, + UTF8ToUTF16(base::StringPrintf(kTitleFormat, counter_)), + UTF8ToUTF16(base::StringPrintf(kMessageFormat, counter_)), gfx::Image(), + UTF8ToUTF16(kDisplaySource), GURL(), + NotifierId(NotifierType::APPLICATION, kExtensionId), optional_fields, + nullptr)); return notification; } @@ -103,7 +104,9 @@ } static const char kIdFormat[]; - static const char16_t kDisplaySource[]; + static const char kTitleFormat[]; + static const char kMessageFormat[]; + static const char kDisplaySource[]; static const char kExtensionId[]; std::unique_ptr<FakeMessageCenter> message_center_; @@ -125,7 +128,9 @@ } const char NotificationListTest::kIdFormat[] = "id%ld"; -const char16_t NotificationListTest::kDisplaySource[] = u"source"; +const char NotificationListTest::kTitleFormat[] = "id%ld"; +const char NotificationListTest::kMessageFormat[] = "message%ld"; +const char NotificationListTest::kDisplaySource[] = "source"; const char NotificationListTest::kExtensionId[] = "ext"; TEST_F(NotificationListTest, Basic) { @@ -169,11 +174,11 @@ std::string id0 = AddNotification(); std::string replaced = id0 + "_replaced"; EXPECT_EQ(1u, notification_list_->NotificationCount(blockers_)); - std::unique_ptr<Notification> notification( - new Notification(NOTIFICATION_TYPE_SIMPLE, replaced, u"newtitle", - u"newbody", gfx::Image(), kDisplaySource, GURL(), - NotifierId(NotifierType::APPLICATION, kExtensionId), - RichNotificationData(), nullptr)); + std::unique_ptr<Notification> notification(new Notification( + NOTIFICATION_TYPE_SIMPLE, replaced, u"newtitle", u"newbody", gfx::Image(), + UTF8ToUTF16(kDisplaySource), GURL(), + NotifierId(NotifierType::APPLICATION, kExtensionId), + RichNotificationData(), nullptr)); notification_list_->UpdateNotificationMessage(id0, std::move(notification)); EXPECT_EQ(1u, notification_list_->NotificationCount(blockers_)); const NotificationList::Notifications notifications = @@ -460,11 +465,11 @@ EXPECT_EQ(0u, GetPopupCounts()); RichNotificationData optional; - std::unique_ptr<Notification> notification( - new Notification(NOTIFICATION_TYPE_SIMPLE, replaced, u"newtitle", - u"newbody", gfx::Image(), kDisplaySource, GURL(), - NotifierId(NotifierType::APPLICATION, kExtensionId), - optional, nullptr)); + std::unique_ptr<Notification> notification(new Notification( + NOTIFICATION_TYPE_SIMPLE, replaced, u"newtitle", u"newbody", + gfx::Image(), UTF8ToUTF16(kDisplaySource), GURL(), + NotifierId(NotifierType::APPLICATION, kExtensionId), optional, + nullptr)); notification_list_->UpdateNotificationMessage(id0, std::move(notification)); EXPECT_EQ(1u, notification_list_->NotificationCount(blockers_)); EXPECT_EQ(has_message_center_view ? 0U : 1U, GetPopupCounts()); @@ -493,7 +498,7 @@ optional.renotify = true; std::unique_ptr<Notification> notification(new Notification( NOTIFICATION_TYPE_SIMPLE, replaced, u"newtitle", u"newbody", gfx::Image(), - kDisplaySource, GURL(), + UTF8ToUTF16(kDisplaySource), GURL(), NotifierId(NotifierType::APPLICATION, kExtensionId), optional, nullptr)); notification_list_->UpdateNotificationMessage(id0, std::move(notification)); EXPECT_EQ(1u, notification_list_->NotificationCount(blockers_)); @@ -517,7 +522,7 @@ priority.priority = DEFAULT_PRIORITY; std::unique_ptr<Notification> notification(new Notification( NOTIFICATION_TYPE_SIMPLE, id0, u"newtitle", u"newbody", gfx::Image(), - kDisplaySource, GURL(), + UTF8ToUTF16(kDisplaySource), GURL(), NotifierId(NotifierType::APPLICATION, kExtensionId), priority, nullptr)); notification_list_->UpdateNotificationMessage(id0, std::move(notification)); EXPECT_EQ(1u, GetPopupCounts()); @@ -527,7 +532,7 @@ // update with no promotion change for id0, it won't appear as a toast. notification = std::make_unique<Notification>( NOTIFICATION_TYPE_SIMPLE, id0, u"newtitle2", u"newbody2", gfx::Image(), - kDisplaySource, GURL(), + UTF8ToUTF16(kDisplaySource), GURL(), NotifierId(NotifierType::APPLICATION, kExtensionId), priority, nullptr); notification_list_->UpdateNotificationMessage(id0, std::move(notification)); EXPECT_EQ(0u, GetPopupCounts()); @@ -536,7 +541,7 @@ priority.priority = HIGH_PRIORITY; notification = std::make_unique<Notification>( NOTIFICATION_TYPE_SIMPLE, id1, u"newtitle", u"newbody", gfx::Image(), - kDisplaySource, GURL(), + UTF8ToUTF16(kDisplaySource), GURL(), NotifierId(NotifierType::APPLICATION, kExtensionId), priority, nullptr); notification_list_->UpdateNotificationMessage(id1, std::move(notification)); EXPECT_EQ(0u, GetPopupCounts()); @@ -545,7 +550,7 @@ priority.renotify = true; notification = std::make_unique<Notification>( NOTIFICATION_TYPE_SIMPLE, id1, u"newtitle", u"newbody", gfx::Image(), - kDisplaySource, GURL(), + UTF8ToUTF16(kDisplaySource), GURL(), NotifierId(NotifierType::APPLICATION, kExtensionId), priority, nullptr); notification_list_->UpdateNotificationMessage(id1, std::move(notification)); EXPECT_EQ(1u, GetPopupCounts()); @@ -643,11 +648,11 @@ EXPECT_TRUE(n1_state.is_read); const std::string replaced("test-replaced-id"); - std::unique_ptr<Notification> notification( - new Notification(NOTIFICATION_TYPE_SIMPLE, replaced, u"newtitle", - u"newbody", gfx::Image(), kDisplaySource, GURL(), - NotifierId(NotifierType::APPLICATION, kExtensionId), - RichNotificationData(), nullptr)); + std::unique_ptr<Notification> notification(new Notification( + NOTIFICATION_TYPE_SIMPLE, replaced, u"newtitle", u"newbody", gfx::Image(), + UTF8ToUTF16(kDisplaySource), GURL(), + NotifierId(NotifierType::APPLICATION, kExtensionId), + RichNotificationData(), nullptr)); notification_list_->UpdateNotificationMessage(id1, std::move(notification)); Notification* n1 = GetNotification(id1); EXPECT_TRUE(n1 == nullptr);
diff --git a/ui/ozone/platform/wayland/host/wayland_cursor_factory.cc b/ui/ozone/platform/wayland/host/wayland_cursor_factory.cc index 0be6904c..855e347e 100644 --- a/ui/ozone/platform/wayland/host/wayland_cursor_factory.cc +++ b/ui/ozone/platform/wayland/host/wayland_cursor_factory.cc
@@ -157,6 +157,8 @@ // wl_cursor_theme_load() can return nullptr. We don't check that here but // have to be cautious when we actually load the shape. current_theme_->theme.reset(loaded_theme); + current_theme_->cache.clear(); + NotifyObserversOnThemeLoaded(); } }
diff --git a/ui/views/accessibility/ax_virtual_view_unittest.cc b/ui/views/accessibility/ax_virtual_view_unittest.cc index 160659a4..aef2de7 100644 --- a/ui/views/accessibility/ax_virtual_view_unittest.cc +++ b/ui/views/accessibility/ax_virtual_view_unittest.cc
@@ -46,14 +46,13 @@ class AXVirtualViewTest : public ViewsTestBase { public: - AXVirtualViewTest() = default; + AXVirtualViewTest() : ax_mode_setter_(ui::kAXModeComplete) {} AXVirtualViewTest(const AXVirtualViewTest&) = delete; AXVirtualViewTest& operator=(const AXVirtualViewTest&) = delete; ~AXVirtualViewTest() override = default; void SetUp() override { ViewsTestBase::SetUp(); - ui::AXPlatformNode::NotifyAddAXModeFlags(ui::kAXModeComplete); widget_ = new Widget; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); @@ -112,6 +111,7 @@ std::vector< std::pair<const ui::AXPlatformNodeDelegate*, const ax::mojom::Event>> accessibility_events_; + ui::testing::ScopedAxModeSetter ax_mode_setter_; }; TEST_F(AXVirtualViewTest, AccessibilityRoleAndName) {
diff --git a/ui/views/accessibility/view_ax_platform_node_delegate_auralinux_unittest.cc b/ui/views/accessibility/view_ax_platform_node_delegate_auralinux_unittest.cc index 09c03eb2..5056e86 100644 --- a/ui/views/accessibility/view_ax_platform_node_delegate_auralinux_unittest.cc +++ b/ui/views/accessibility/view_ax_platform_node_delegate_auralinux_unittest.cc
@@ -16,12 +16,12 @@ class ViewAXPlatformNodeDelegateAuraLinuxTest : public ViewsTestBase { public: - ViewAXPlatformNodeDelegateAuraLinuxTest() = default; + ViewAXPlatformNodeDelegateAuraLinuxTest() + : ax_mode_setter_(ui::kAXModeComplete) {} ~ViewAXPlatformNodeDelegateAuraLinuxTest() override = default; - void SetUp() override { - ViewsTestBase::SetUp(); - ui::AXPlatformNode::NotifyAddAXModeFlags(ui::kAXModeComplete); - } + + private: + ui::testing::ScopedAxModeSetter ax_mode_setter_; }; TEST_F(ViewAXPlatformNodeDelegateAuraLinuxTest, TextfieldAccessibility) {
diff --git a/ui/views/accessibility/view_ax_platform_node_delegate_unittest.cc b/ui/views/accessibility/view_ax_platform_node_delegate_unittest.cc index 3ad8483..de1d0a6 100644 --- a/ui/views/accessibility/view_ax_platform_node_delegate_unittest.cc +++ b/ui/views/accessibility/view_ax_platform_node_delegate_unittest.cc
@@ -103,7 +103,7 @@ class ViewAXPlatformNodeDelegateTest : public ViewsTestBase { public: - ViewAXPlatformNodeDelegateTest() = default; + ViewAXPlatformNodeDelegateTest() : ax_mode_setter_(ui::kAXModeComplete) {} ViewAXPlatformNodeDelegateTest(const ViewAXPlatformNodeDelegateTest&) = delete; ViewAXPlatformNodeDelegateTest& operator=( @@ -112,7 +112,6 @@ void SetUp() override { ViewsTestBase::SetUp(); - ui::AXPlatformNode::NotifyAddAXModeFlags(ui::kAXModeComplete); widget_ = new Widget; Widget::InitParams params = @@ -206,6 +205,7 @@ Widget* widget_ = nullptr; Button* button_ = nullptr; Label* label_ = nullptr; + ui::testing::ScopedAxModeSetter ax_mode_setter_; }; class ViewAXPlatformNodeDelegateTableTest
diff --git a/ui/views/controls/message_box_view.cc b/ui/views/controls/message_box_view.cc index d94b81c..bfd76ace 100644 --- a/ui/views/controls/message_box_view.cc +++ b/ui/views/controls/message_box_view.cc
@@ -109,11 +109,11 @@ } else { add_label(message, true, gfx::ALIGN_LEFT); } - auto scroll_view = std::make_unique<ScrollView>(); - scroll_view->ClipHeightTo(0, provider->GetDistanceMetric( - DISTANCE_DIALOG_SCROLLABLE_AREA_MAX_HEIGHT)); - scroll_view->SetContents(std::move(message_contents)); - scroll_view_ = AddChildView(std::move(scroll_view)); + scroll_view_ = AddChildView(std::make_unique<ScrollView>()); + scroll_view_->ClipHeightTo( + 0, + provider->GetDistanceMetric(DISTANCE_DIALOG_SCROLLABLE_AREA_MAX_HEIGHT)); + scroll_view_->SetContents(std::move(message_contents)); // Don't enable text selection if multiple labels are used, since text // selection can't span multiple labels. if (message_labels_.size() == 1u)
diff --git a/ui/views/controls/scroll_view.cc b/ui/views/controls/scroll_view.cc index 129b2c0e..3273b0a 100644 --- a/ui/views/controls/scroll_view.cc +++ b/ui/views/controls/scroll_view.cc
@@ -158,13 +158,6 @@ scroll_view_->ScrollContentsRegionToBeVisible(scroll_rect); } - // TODO(https://crbug.com/947053): this override should not be necessary, but - // there are some assumptions that this calls Layout(). - void ChildPreferredSizeChanged(View* child) override { - if (parent()) - parent()->Layout(); - } - void ViewHierarchyChanged( const ViewHierarchyChangedDetails& details) override { if (details.is_add && GetIsContentsViewport() && Contains(details.parent)) @@ -464,12 +457,11 @@ } gfx::Size ScrollView::CalculatePreferredSize() const { - if (!is_bounded()) - return View::CalculatePreferredSize(); - - gfx::Size size = contents_->GetPreferredSize(); - size.SetToMax(gfx::Size(size.width(), min_height_)); - size.SetToMin(gfx::Size(size.width(), max_height_)); + gfx::Size size = contents_ ? contents_->GetPreferredSize() : gfx::Size(); + if (is_bounded()) { + size.SetToMax(gfx::Size(size.width(), min_height_)); + size.SetToMin(gfx::Size(size.width(), max_height_)); + } gfx::Insets insets = GetInsets(); size.Enlarge(insets.width(), insets.height()); return size; @@ -481,7 +473,8 @@ gfx::Insets insets = GetInsets(); width = std::max(0, width - insets.width()); - int height = contents_->GetHeightForWidth(width) + insets.height(); + int height = contents_ ? contents_->GetHeightForWidth(width) + insets.height() + : insets.height(); return base::ClampToRange(height, min_height_, max_height_); } @@ -897,10 +890,7 @@ *member = parent->AddChildView(std::move(new_view)); else *member = nullptr; - // TODO(https://crbug.com/947053): this should call InvalidateLayout(), but - // there are some assumptions that it call Layout(). These assumptions should - // be updated. - Layout(); + InvalidateLayout(); } void ScrollView::ScrollContentsRegionToBeVisible(const gfx::Rect& rect) {
diff --git a/ui/views/controls/scroll_view_unittest.cc b/ui/views/controls/scroll_view_unittest.cc index 1b61137..2ec875f 100644 --- a/ui/views/controls/scroll_view_unittest.cc +++ b/ui/views/controls/scroll_view_unittest.cc
@@ -634,12 +634,14 @@ } // Assertions around adding a header. -TEST_F(ScrollViewTest, Header) { - auto* header = scroll_view_->SetHeader(std::make_unique<CustomView>()); +TEST_F(WidgetScrollViewTest, Header) { + auto contents_ptr = std::make_unique<View>(); + auto* contents = contents_ptr.get(); + ScrollView* scroll_view = AddScrollViewWithContents(std::move(contents_ptr)); + auto* header = scroll_view->SetHeader(std::make_unique<CustomView>()); View* header_parent = header->parent(); - View* contents = InstallContents(); - scroll_view_->Layout(); + widget()->LayoutRootViewIfNecessary(); // |header|s preferred size is empty, which should result in all space going // to contents. EXPECT_EQ("0,0 100x0", header->parent()->bounds().ToString()); @@ -657,8 +659,8 @@ // Get the header a height of 20. header->SetPreferredSize(gfx::Size(10, 20)); - EXPECT_TRUE(ViewTestApi(scroll_view_.get()).needs_layout()); - scroll_view_->Layout(); + EXPECT_TRUE(ViewTestApi(scroll_view).needs_layout()); + widget()->LayoutRootViewIfNecessary(); EXPECT_EQ("0,0 100x20", header->parent()->bounds().ToString()); EXPECT_EQ("0,20 100x80", contents->parent()->bounds().ToString()); if (contents->layer()) { @@ -668,9 +670,10 @@ EXPECT_EQ("0,0 0x0", contents->bounds().ToString()); // Remove the header. - scroll_view_->SetHeader(nullptr); + scroll_view->SetHeader(nullptr); // SetHeader(nullptr) deletes header. header = nullptr; + widget()->LayoutRootViewIfNecessary(); EXPECT_EQ("0,0 100x0", header_parent->bounds().ToString()); EXPECT_EQ("0,0 100x100", contents->parent()->bounds().ToString()); } @@ -2270,6 +2273,21 @@ EXPECT_EQ(gfx::ScrollOffset(10, 0), test_api.CurrentOffset()); } +TEST_F(WidgetScrollViewTest, UnboundedScrollViewUsesContentPreferredSize) { + auto contents = std::make_unique<View>(); + constexpr gfx::Size kContentsPreferredSize(500, 500); + contents->SetPreferredSize(kContentsPreferredSize); + ScrollView* scroll_view = + AddScrollViewWithContents(std::move(contents), true); + EXPECT_EQ(kContentsPreferredSize, scroll_view->GetPreferredSize()); + + constexpr gfx::Insets kInsets(20); + scroll_view->SetBorder(CreateEmptyBorder(kInsets)); + gfx::Size preferred_size_with_insets(kContentsPreferredSize); + preferred_size_with_insets.Enlarge(kInsets.width(), kInsets.height()); + EXPECT_EQ(preferred_size_with_insets, scroll_view->GetPreferredSize()); +} + INSTANTIATE_TEST_SUITE_P(All, WidgetScrollViewTestRTLAndLayers, ::testing::Values(UiConfig::kLtr,
diff --git a/ui/views/controls/textfield/textfield_unittest.cc b/ui/views/controls/textfield/textfield_unittest.cc index 9125b66..c7f5d644 100644 --- a/ui/views/controls/textfield/textfield_unittest.cc +++ b/ui/views/controls/textfield/textfield_unittest.cc
@@ -77,6 +77,9 @@ #include "ui/base/cocoa/text_services_context_menu.h" #endif +using base::ASCIIToUTF16; +using base::UTF8ToUTF16; + namespace views { namespace test { @@ -425,8 +428,8 @@ } void TextfieldTest::SetClipboardText(ui::ClipboardBuffer clipboard_buffer, - const std::u16string& text) { - ui::ScopedClipboardWriter(clipboard_buffer).WriteText(text); + const std::string& text) { + ui::ScopedClipboardWriter(clipboard_buffer).WriteText(ASCIIToUTF16(text)); } void TextfieldTest::ContentsChanged(Textfield* sender, @@ -1427,7 +1430,7 @@ EXPECT_EQ(u"password", textfield_->GetText()); EXPECT_TRUE(last_contents_.empty()); model_->SelectAll(false); - SetClipboardText(ui::ClipboardBuffer::kCopyPaste, u"foo"); + SetClipboardText(ui::ClipboardBuffer::kCopyPaste, "foo"); // Cut and copy should be disabled. EXPECT_FALSE(textfield_->IsCommandIdEnabled(Textfield::kCut)); @@ -1791,7 +1794,7 @@ VerifyTextfieldContextMenuContents(true, true, GetContextMenuModel()); // Exercise the "paste enabled?" check in the verifier. - SetClipboardText(ui::ClipboardBuffer::kCopyPaste, u"Test"); + SetClipboardText(ui::ClipboardBuffer::kCopyPaste, "Test"); VerifyTextfieldContextMenuContents(true, true, GetContextMenuModel()); } @@ -1890,10 +1893,10 @@ TEST_F(TextfieldTest, DragUpOrDownSelectsToEnd) { InitTextfield(); textfield_->SetText(u"hello world"); - const std::u16string expected_left = - gfx::RenderText::kDragToEndIfOutsideVerticalBounds ? u"hello" : u"lo"; - const std::u16string expected_right = - gfx::RenderText::kDragToEndIfOutsideVerticalBounds ? u" world" : u" w"; + const std::u16string expected_left = base::ASCIIToUTF16( + gfx::RenderText::kDragToEndIfOutsideVerticalBounds ? "hello" : "lo"); + const std::u16string expected_right = base::ASCIIToUTF16( + gfx::RenderText::kDragToEndIfOutsideVerticalBounds ? " world" : " w"); const int right_x = GetCursorPositionX(7); const int left_x = GetCursorPositionX(3); @@ -2163,7 +2166,7 @@ EXPECT_EQ(u"read only", textfield_->GetSelectedText()); // Cut should be disabled. - SetClipboardText(ui::ClipboardBuffer::kCopyPaste, u"Test"); + SetClipboardText(ui::ClipboardBuffer::kCopyPaste, "Test"); EXPECT_FALSE(textfield_->IsCommandIdEnabled(Textfield::kCut)); textfield_->ExecuteCommand(Textfield::kCut, 0); SendKeyEvent(ui::VKEY_X, false, true); @@ -2179,14 +2182,14 @@ EXPECT_EQ(u"read only", textfield_->GetText()); // Copy should work normally. - SetClipboardText(ui::ClipboardBuffer::kCopyPaste, u"Test"); + SetClipboardText(ui::ClipboardBuffer::kCopyPaste, "Test"); EXPECT_TRUE(textfield_->IsCommandIdEnabled(Textfield::kCopy)); textfield_->ExecuteCommand(Textfield::kCopy, 0); EXPECT_EQ(u"read only", GetClipboardText(ui::ClipboardBuffer::kCopyPaste)); - SetClipboardText(ui::ClipboardBuffer::kCopyPaste, u"Test"); + SetClipboardText(ui::ClipboardBuffer::kCopyPaste, "Test"); SendKeyEvent(ui::VKEY_C, false, true); EXPECT_EQ(u"read only", GetClipboardText(ui::ClipboardBuffer::kCopyPaste)); - SetClipboardText(ui::ClipboardBuffer::kCopyPaste, u"Test"); + SetClipboardText(ui::ClipboardBuffer::kCopyPaste, "Test"); SendAlternateCopy(); EXPECT_EQ(u"read only", GetClipboardText(ui::ClipboardBuffer::kCopyPaste)); @@ -2527,7 +2530,7 @@ EXPECT_EQ(ui::ClipboardBuffer::kCopyPaste, GetAndResetCopiedToClipboard()); // Reset clipboard text. - SetClipboardText(ui::ClipboardBuffer::kCopyPaste, u""); + SetClipboardText(ui::ClipboardBuffer::kCopyPaste, ""); // Ensure [Shift]+[Delete] is a no-op in case there is no selection. textfield_->SetText(u"123"); @@ -2565,7 +2568,7 @@ // Ensure kPaste, [Ctrl]+[V], and [Shift]+[Insert] pastes; // also ensure that [Ctrl]+[Alt]+[V] does nothing. - SetClipboardText(ui::ClipboardBuffer::kCopyPaste, u"abc"); + SetClipboardText(ui::ClipboardBuffer::kCopyPaste, "abc"); textfield_->SetText(std::u16string()); EXPECT_TRUE(textfield_->IsCommandIdEnabled(Textfield::kPaste)); textfield_->ExecuteCommand(Textfield::kPaste, 0); @@ -3249,7 +3252,7 @@ EXPECT_EQ(u"0123", GetClipboardText(ui::ClipboardBuffer::kSelection)); // Middle clicking with an empty selection clipboard should still focus. - SetClipboardText(ui::ClipboardBuffer::kSelection, std::u16string()); + SetClipboardText(ui::ClipboardBuffer::kSelection, std::string()); textfield_->GetFocusManager()->ClearFocus(); EXPECT_FALSE(textfield_->HasFocus()); textfield_->OnMousePressed(middle); @@ -3261,7 +3264,7 @@ // Middle clicking in the selection should insert the selection clipboard // contents into the middle of the selection, and move the cursor to the end // of the pasted content. - SetClipboardText(ui::ClipboardBuffer::kCopyPaste, u"foo"); + SetClipboardText(ui::ClipboardBuffer::kCopyPaste, "foo"); textfield_->SetSelectedRange(gfx::Range(2, 6)); textfield_->OnMousePressed(middle); EXPECT_EQ(u"0123foo01230123", textfield_->GetText()); @@ -3301,7 +3304,7 @@ EXPECT_EQ(u"ab cd ef", GetClipboardText(ui::ClipboardBuffer::kSelection)); EXPECT_EQ(ui::ClipboardBuffer::kMaxValue, GetAndResetCopiedToClipboard()); - SetClipboardText(ui::ClipboardBuffer::kSelection, u"other"); + SetClipboardText(ui::ClipboardBuffer::kSelection, "other"); textfield_->SelectAll(false); EXPECT_EQ(u"other", GetClipboardText(ui::ClipboardBuffer::kSelection)); EXPECT_EQ(ui::ClipboardBuffer::kMaxValue, GetAndResetCopiedToClipboard()); @@ -3377,7 +3380,7 @@ // Set text which may fall back to a font which has taller baseline than // the default font. - textfield_->SetText(u"๑"); + textfield_->SetText(UTF8ToUTF16("\xE0\xB9\x91")); const int new_baseline = textfield_->GetBaseline(); // Regardless of the text, the baseline must be the same. @@ -3422,7 +3425,7 @@ textfield_->GetAccessibleNodeData(&data); const std::string& name = data.GetStringAttribute(ax::mojom::StringAttribute::kName); - EXPECT_EQ(test_tooltip_text, base::ASCIIToUTF16(name)); + EXPECT_EQ(test_tooltip_text, ASCIIToUTF16(name)); } #if BUILDFLAG(IS_CHROMEOS_ASH) @@ -3765,12 +3768,12 @@ } TEST_F(TextfieldTest, FocusChangesScrollToStart) { - const std::u16string kText = u"abcdef"; + const std::string& kText = "abcdef"; InitTextfield(); - textfield_->SetText(kText); - EXPECT_EQ(std::u16string(), textfield_->GetSelectedText()); + textfield_->SetText(ASCIIToUTF16(kText)); + EXPECT_EQ(base::ASCIIToUTF16(std::string()), textfield_->GetSelectedText()); textfield_->AboutToRequestFocusFromTabTraversal(false); - EXPECT_EQ(kText, textfield_->GetSelectedText()); + EXPECT_EQ(base::ASCIIToUTF16(kText), textfield_->GetSelectedText()); if (PlatformStyle::kTextfieldScrollsToStartOnFocusChange) EXPECT_EQ(0U, textfield_->GetCursorPosition()); else @@ -3926,9 +3929,9 @@ #endif // defined(OS_MAC) TEST_F(TextfieldTest, AccessibilitySelectionEvents) { - const std::u16string kText = u"abcdef"; + const std::string& kText = "abcdef"; InitTextfield(); - textfield_->SetText(kText); + textfield_->SetText(ASCIIToUTF16(kText)); EXPECT_TRUE(textfield_->HasFocus()); int previous_selection_fired_count = textfield_->GetAccessibilitySelectionFiredCount();
diff --git a/ui/views/controls/textfield/textfield_unittest.h b/ui/views/controls/textfield/textfield_unittest.h index fef1348c..4d796ad 100644 --- a/ui/views/controls/textfield/textfield_unittest.h +++ b/ui/views/controls/textfield/textfield_unittest.h
@@ -42,7 +42,7 @@ ui::ClipboardBuffer GetAndResetCopiedToClipboard(); std::u16string GetClipboardText(ui::ClipboardBuffer type); - void SetClipboardText(ui::ClipboardBuffer type, const std::u16string& text); + void SetClipboardText(ui::ClipboardBuffer type, const std::string& text); // TextfieldController: void ContentsChanged(Textfield* sender,
diff --git a/ui/views/examples/native_theme_example.cc b/ui/views/examples/native_theme_example.cc index bf0d7a86c..28eb339 100644 --- a/ui/views/examples/native_theme_example.cc +++ b/ui/views/examples/native_theme_example.cc
@@ -39,11 +39,13 @@ void InsertColorRow(GridLayout* layout, base::StringPiece16 label_string, ui::NativeTheme::ColorId color_id) { - auto label_view = std::make_unique<Label>(std::u16string(label_string)); + layout->StartRow(GridLayout::kFixedSize, 0); + auto* label_view = + layout->AddView(std::make_unique<Label>(std::u16string(label_string))); label_view->SetHorizontalAlignment(gfx::HorizontalAlignment::ALIGN_LEFT); label_view->SetSelectable(true); - auto color_view = std::make_unique<Label>(); + auto* color_view = layout->AddView(std::make_unique<Label>()); color_view->SetHorizontalAlignment(gfx::HorizontalAlignment::ALIGN_LEFT); auto background_color = color_view->GetNativeTheme()->GetSystemColor(color_id); @@ -57,16 +59,12 @@ color_view->SetBackgroundColor(background_color); color_view->SetBackground(CreateSolidBackground(background_color)); color_view->SetSelectable(true); - - layout->StartRow(GridLayout::kFixedSize, 0); - layout->AddView(std::move(label_view)); - layout->AddView(std::move(color_view)); } // Returns a view of two columns where the first contains the identifier names // of ui::NativeTheme::ColorId and the second contains the color. -std::unique_ptr<View> CreateAllColorsView() { - auto container = std::make_unique<View>(); +void CreateAllColorsView(ScrollView* scroll_view) { + auto* container = scroll_view->SetContents(std::make_unique<View>()); auto* layout = container->SetLayoutManager(std::make_unique<GridLayout>()); auto* column_set = layout->AddColumnSet(0); column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1.0, @@ -163,9 +161,22 @@ InsertColorRow(layout, COLOR_LABEL_ARGS(kColorId_DefaultIconColor)); // Expands the view to allow for scrolling. container->SizeToPreferredSize(); - return container; } +class AllColorsScrollView : public ScrollView { + public: + AllColorsScrollView() { + constexpr int kMaxHeight = 300; + ClipHeightTo(0, kMaxHeight); + } + + protected: + void OnThemeChanged() override { + ScrollView::OnThemeChanged(); + CreateAllColorsView(this); + } +}; + } // namespace NativeThemeExample::NativeThemeExample() @@ -175,9 +186,7 @@ void NativeThemeExample::CreateExampleView(View* container) { container->SetLayoutManager(std::make_unique<FillLayout>()); - auto scroll_view = std::make_unique<ScrollView>(); - scroll_view->SetContents(CreateAllColorsView()); - container->AddChildView(std::move(scroll_view)); + container->AddChildView(std::make_unique<AllColorsScrollView>()); } } // namespace examples
diff --git a/ui/views/examples/textarea_example.cc b/ui/views/examples/textarea_example.cc index d3205e9..cf1ddf2 100644 --- a/ui/views/examples/textarea_example.cc +++ b/ui/views/examples/textarea_example.cc
@@ -18,16 +18,16 @@ TextareaExample::TextareaExample() : ExampleBase("Textarea") {} void TextareaExample::CreateExampleView(View* container) { - constexpr char16_t kLongText[] = - u"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do " - u"eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad " - u"minim veniam, quis nostrud exercitation ullamco laboris nisi ut " - u"aliquip ex ea commodo consequat.\nDuis aute irure dolor in " - u"reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla " - u"pariatur.\n\nExcepteur sint occaecat cupidatat non proident, sunt in " - u"culpa qui officia deserunt mollit anim id est laborum."; + constexpr char kLongText[] = + "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod" + " tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim " + "veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea " + "commodo consequat.\nDuis aute irure dolor in reprehenderit in voluptate " + "velit esse cillum dolore eu fugiat nulla pariatur.\n\nExcepteur sint " + "occaecat cupidatat non proident, sunt in culpa qui officia deserunt " + "mollit anim id est laborum."; auto textarea = std::make_unique<Textarea>(); - textarea->SetText(kLongText); + textarea->SetText(base::UTF8ToUTF16(kLongText)); container->SetLayoutManager(std::make_unique<views::FillLayout>()); container->AddChildView(std::move(textarea)); }
diff --git a/url/gurl_unittest.cc b/url/gurl_unittest.cc index 35204704..6d23d65 100644 --- a/url/gurl_unittest.cc +++ b/url/gurl_unittest.cc
@@ -117,7 +117,8 @@ } TEST(GURLTest, Copy) { - GURL url(u"http://user:pass@google.com:99/foo;bar?q=a#ref"); + GURL url(base::UTF8ToUTF16( + "http://user:pass@google.com:99/foo;bar?q=a#ref")); GURL url2(url); EXPECT_TRUE(url2.is_valid()); @@ -150,7 +151,8 @@ } TEST(GURLTest, Assign) { - GURL url(u"http://user:pass@google.com:99/foo;bar?q=a#ref"); + GURL url(base::UTF8ToUTF16( + "http://user:pass@google.com:99/foo;bar?q=a#ref")); GURL url2; url2 = url; @@ -192,7 +194,8 @@ } TEST(GURLTest, CopyFileSystem) { - GURL url(u"filesystem:https://user:pass@google.com:99/t/foo;bar?q=a#ref"); + GURL url(base::UTF8ToUTF16( + "filesystem:https://user:pass@google.com:99/t/foo;bar?q=a#ref")); GURL url2(url); EXPECT_TRUE(url2.is_valid());
diff --git a/weblayer/browser/autofill_client_impl.cc b/weblayer/browser/autofill_client_impl.cc index 82e3e9b..eed753d 100644 --- a/weblayer/browser/autofill_client_impl.cc +++ b/weblayer/browser/autofill_client_impl.cc
@@ -224,6 +224,7 @@ void AutofillClientImpl::ConfirmSaveAddressProfile( const autofill::AutofillProfile& profile, const autofill::AutofillProfile* original_profile, + SaveAddressProfilePromptOptions options, AddressProfileSavePromptCallback callback) { NOTREACHED(); }
diff --git a/weblayer/browser/autofill_client_impl.h b/weblayer/browser/autofill_client_impl.h index ece9bab..b7b0aa2d 100644 --- a/weblayer/browser/autofill_client_impl.h +++ b/weblayer/browser/autofill_client_impl.h
@@ -103,6 +103,7 @@ void ConfirmSaveAddressProfile( const autofill::AutofillProfile& profile, const autofill::AutofillProfile* original_profile, + SaveAddressProfilePromptOptions options, AddressProfileSavePromptCallback callback) override; bool HasCreditCardScanFeature() override; void ScanCreditCard(CreditCardScanCallback callback) override;