diff --git a/DEPS b/DEPS index e0d3183c7..92e4a88c 100644 --- a/DEPS +++ b/DEPS
@@ -295,11 +295,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': '502553f2f54b093686da6c516bcbef605bebedcd', + 'skia_revision': '3d4f57ab11323fa3e96885a488ec9a862ec6c2bc', # 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': '66900470cf2b7b974bd622dd42875f2a69ffaad0', + 'v8_revision': '172608cd0d063ebfe6ce341b599b833fb157aa0b', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ANGLE # and whatever else without interference from each other. @@ -366,7 +366,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling catapult # and whatever else without interference from each other. - 'catapult_revision': '07489847d9adb4d5fb5ab9348f1044acd96e523a', + 'catapult_revision': '4f0d7594338dae0097f3b45b88876d61613bff63', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libFuzzer # and whatever else without interference from each other. @@ -374,7 +374,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': 'fc4b4c505539d143bcc9e68cd53d5a51f15cb6f0', + 'devtools_frontend_revision': '779abc925b3cdc029a1aa543f1f90d564a4e247e', # 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. @@ -434,7 +434,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling nearby # and whatever else without interference from each other. - 'nearby_revision': '00b1a1570ef5290394b7e865a67392ae4199f4c4', + 'nearby_revision': '6871b9d5a6c5bf74bc1e8f893a4cc4ddef1b6491', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling securemessage # and whatever else without interference from each other. @@ -782,12 +782,12 @@ 'src/clank': { 'url': 'https://chrome-internal.googlesource.com/clank/internal/apps.git' + '@' + - 'e1ec096c608b85e3777f16dc7665c0e45a387466', + 'ba7c078599c9ec35cfcfd2e97fb2a0e749d4df4f', 'condition': 'checkout_android and checkout_src_internal', }, 'src/docs/website': { - 'url': Var('chromium_git') + '/website.git' + '@' + 'a951c376d10365faee64b904a050695506c4690a', + 'url': Var('chromium_git') + '/website.git' + '@' + 'a7af36d28ff2952a3a5a3d0886885c14fcd4a07e', }, 'src/ios/third_party/earl_grey2/src': { @@ -971,7 +971,7 @@ 'packages': [ { 'package': 'chromium/third_party/androidx', - 'version': 'ahejXuXdnledP6wfeAw85DLd_8GGUiV4NFHYL5sgrNIC', + 'version': 'DoMiLWGEPZ6MIrAeFkKaGQqFar0ez6bY0nwhdUVEIMMC', }, ], 'condition': 'checkout_android', @@ -1214,13 +1214,13 @@ }, 'src/third_party/depot_tools': - Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + 'd83509c0c3eaf76caed823a09b921871958d8237', + Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + '84edf22d0e5bf3f9ae60714ed9789fd62f86cf2a', 'src/third_party/devtools-frontend/src': Var('chromium_git') + '/devtools/devtools-frontend' + '@' + Var('devtools_frontend_revision'), 'src/third_party/devtools-frontend-internal': { - 'url': 'https://chrome-internal.googlesource.com/devtools/devtools-internal.git' + '@' + '86bfc22006060dbc8f9665688fa71b76842c503b', + 'url': 'https://chrome-internal.googlesource.com/devtools/devtools-internal.git' + '@' + 'e16742cf733ef2bce49cd8e15a30b0ee559d8712', 'condition': 'checkout_src_internal', }, @@ -1635,7 +1635,7 @@ }, 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + 'c2fa74a858edfb42ccfe4a024de1dabd6b5fbabe', + Var('android_git') + '/platform/external/perfetto.git' + '@' + '36fb00a3c36d9c367f50ba03c9bd9c4f5f45161b', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + '6f3e5028eb65d0b4c5fdd792106ac4c84eee1eb3', @@ -1780,7 +1780,7 @@ 'dep_type': 'cipd', }, - 'src/third_party/vulkan-deps': '{chromium_git}/vulkan-deps@8384d293b2e86ad6ecee26c5ecc109552ae685ee', + 'src/third_party/vulkan-deps': '{chromium_git}/vulkan-deps@a02977d267a4d2e0577cf1bc5378a2507b9e7948', 'src/third_party/vulkan_memory_allocator': Var('chromium_git') + '/external/github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator.git' + '@' + 'ebe84bec02c041d28f902da0214bf442743fc907', @@ -1820,7 +1820,7 @@ Var('chromium_git') + '/external/github.com/gpuweb/cts.git' + '@' + '57304e8905d4817346246ccc6aa3f2619d08ab7e', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + '569af3e80fcda6241f0e6d801c89f9ebbee310b3', + Var('webrtc_git') + '/src.git' + '@' + '370ca9c52cac61aceb836501ea935cc9519a4593', # Wuffs' canonical repository is at github.com/google/wuffs, but we use # Skia's mirror of Wuffs, the same as in upstream Skia's DEPS file. @@ -1942,7 +1942,7 @@ 'packages': [ { 'package': 'chromeos_internal/apps/projector_app/app', - 'version': '38UAyejemMk3TYydapl9yMeh3-AeOwFFpUX2F4xQ7_YC', + 'version': 'YuImAHR_I9ZvIdHRT02p_WRMvfyvPRIxdHlBH0Ok9mIC', }, ], 'condition': 'checkout_chromeos and checkout_src_internal',
diff --git a/ash/components/phonehub/fake_message_receiver.h b/ash/components/phonehub/fake_message_receiver.h index abda5a2..e9ca9b33 100644 --- a/ash/components/phonehub/fake_message_receiver.h +++ b/ash/components/phonehub/fake_message_receiver.h
@@ -16,6 +16,7 @@ FakeMessageReceiver() = default; ~FakeMessageReceiver() override = default; + using MessageReceiver::NotifyAppListUpdateReceived; using MessageReceiver::NotifyAppStreamUpdateReceived; using MessageReceiver::NotifyFeatureSetupResponseReceived; using MessageReceiver::NotifyFetchCameraRollItemDataResponseReceived;
diff --git a/ash/components/phonehub/phone_status_processor.cc b/ash/components/phonehub/phone_status_processor.cc index 8197f84..b0b9d244 100644 --- a/ash/components/phonehub/phone_status_processor.cc +++ b/ash/components/phonehub/phone_status_processor.cc
@@ -412,6 +412,16 @@ MaybeSetPhoneModelName(host_device_with_status.second); } +void PhoneStatusProcessor::OnAppListUpdateReceived( + const proto::AppListUpdate app_list_update) { + if (!app_list_update.has_all_apps()) + return; + + if (features::IsEcheSWAEnabled() && features::IsEcheLauncherEnabled()) { + GenerateAppListWithIcons(app_list_update.all_apps()); + } +} + void PhoneStatusProcessor::GenerateAppListWithIcons( const proto::StreamableApps& streamable_apps) { if (streamable_apps.apps_size() == 0) {
diff --git a/ash/components/phonehub/phone_status_processor.h b/ash/components/phonehub/phone_status_processor.h index 2b97dd98..965c69b 100644 --- a/ash/components/phonehub/phone_status_processor.h +++ b/ash/components/phonehub/phone_status_processor.h
@@ -69,6 +69,8 @@ proto::PhoneStatusUpdate phone_status_update) override; void OnAppStreamUpdateReceived( const proto::AppStreamUpdate app_stream_update) override; + void OnAppListUpdateReceived( + const proto::AppListUpdate app_list_update) override; // MultiDeviceSetupClient::Observer: void OnHostStatusChanged(
diff --git a/ash/components/phonehub/phone_status_processor_unittest.cc b/ash/components/phonehub/phone_status_processor_unittest.cc index b2d932f3..ff7f241 100644 --- a/ash/components/phonehub/phone_status_processor_unittest.cc +++ b/ash/components/phonehub/phone_status_processor_unittest.cc
@@ -39,8 +39,7 @@ #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/image/image.h" -namespace ash { -namespace phonehub { +namespace ash::phonehub { using multidevice_setup::mojom::Feature; using multidevice_setup::mojom::FeatureState; @@ -898,5 +897,101 @@ EXPECT_EQ("app1", app_stream_manager_observer_.last_app_stream_update_); } -} // namespace phonehub -} // namespace ash +TEST_F(PhoneStatusProcessorTest, OnAppListUpdateReceived) { + scoped_feature_list_.Reset(); + scoped_feature_list_.InitWithFeatures( + /*enabled_features=*/{features::kEcheSWA, features::kPhoneHubCameraRoll, + features::kEcheLauncher}, + /*disabled_features=*/{}); + + fake_multidevice_setup_client_->SetHostStatusWithDevice( + std::make_pair(HostStatus::kHostVerified, test_remote_device_)); + CreatePhoneStatusProcessor(); + + proto::AppListUpdate expected_update; + auto* streamable_apps = expected_update.mutable_all_apps(); + auto* app1 = streamable_apps->add_apps(); + app1->set_package_name("pkg1"); + app1->set_visible_name("first_app"); + app1->set_icon("icon1"); + + auto* app2 = streamable_apps->add_apps(); + app2->set_package_name("pkg2"); + app2->set_visible_name("second_app"); + app2->set_icon("icon2"); + + // Simulate feature set to enabled and connected. + fake_feature_status_provider_->SetStatus(FeatureStatus::kEnabledAndConnected); + fake_multidevice_setup_client_->SetFeatureState( + Feature::kPhoneHubNotifications, FeatureState::kEnabledByUser); + + // Simulate receiving a proto message. + fake_message_receiver_->NotifyAppListUpdateReceived(expected_update); + + EXPECT_EQ(2u, app_stream_launcher_data_model_->GetAppsList()->size()); + EXPECT_EQ( + u"first_app", + app_stream_launcher_data_model_->GetAppsList()->at(0).visible_app_name); + EXPECT_EQ( + u"second_app", + app_stream_launcher_data_model_->GetAppsList()->at(1).visible_app_name); +} + +TEST_F(PhoneStatusProcessorTest, OnAppListUpdateFeatureDisabled) { + scoped_feature_list_.Reset(); + scoped_feature_list_.InitWithFeatures( + /*enabled_features=*/{features::kEcheSWA, features::kPhoneHubCameraRoll}, + /*disabled_features=*/{features::kEcheLauncher}); + + fake_multidevice_setup_client_->SetHostStatusWithDevice( + std::make_pair(HostStatus::kHostVerified, test_remote_device_)); + CreatePhoneStatusProcessor(); + + proto::AppListUpdate expected_update; + auto* streamable_apps = expected_update.mutable_all_apps(); + auto* app1 = streamable_apps->add_apps(); + app1->set_package_name("pkg1"); + app1->set_visible_name("first_app"); + app1->set_icon("icon1"); + + auto* app2 = streamable_apps->add_apps(); + app2->set_package_name("pkg2"); + app2->set_visible_name("second_app"); + app2->set_icon("icon2"); + + // Simulate feature set to enabled and connected. + fake_feature_status_provider_->SetStatus(FeatureStatus::kEnabledAndConnected); + fake_multidevice_setup_client_->SetFeatureState( + Feature::kPhoneHubNotifications, FeatureState::kEnabledByUser); + + // Simulate receiving a proto message. + fake_message_receiver_->NotifyAppListUpdateReceived(expected_update); + + EXPECT_EQ(0u, app_stream_launcher_data_model_->GetAppsList()->size()); +} + +TEST_F(PhoneStatusProcessorTest, OnAppListUpdateNoApps) { + scoped_feature_list_.Reset(); + scoped_feature_list_.InitWithFeatures( + /*enabled_features=*/{features::kEcheSWA, features::kPhoneHubCameraRoll, + features::kEcheLauncher}, + /*disabled_features=*/{}); + + fake_multidevice_setup_client_->SetHostStatusWithDevice( + std::make_pair(HostStatus::kHostVerified, test_remote_device_)); + CreatePhoneStatusProcessor(); + + proto::AppListUpdate expected_update; + + // Simulate feature set to enabled and connected. + fake_feature_status_provider_->SetStatus(FeatureStatus::kEnabledAndConnected); + fake_multidevice_setup_client_->SetFeatureState( + Feature::kPhoneHubNotifications, FeatureState::kEnabledByUser); + + // Simulate receiving a proto message. + fake_message_receiver_->NotifyAppListUpdateReceived(expected_update); + + EXPECT_EQ(0u, app_stream_launcher_data_model_->GetAppsList()->size()); +} + +} // namespace ash::phonehub
diff --git a/ash/system/notification_center/notification_center_tray.cc b/ash/system/notification_center/notification_center_tray.cc index f5c41d4..74972fb 100644 --- a/ash/system/notification_center/notification_center_tray.cc +++ b/ash/system/notification_center/notification_center_tray.cc
@@ -54,6 +54,10 @@ UpdateVisibility(); } +bool NotificationCenterTray::IsBubbleShown() const { + return !!bubble_; +} + std::u16string NotificationCenterTray::GetAccessibleNameForTray() { return std::u16string(); } @@ -108,6 +112,22 @@ return bubble_ ? bubble_->GetBubbleWidget() : nullptr; } +void NotificationCenterTray::OnAnyBubbleVisibilityChanged( + views::Widget* bubble_widget, + bool visible) { + if (!IsBubbleShown()) + return; + + if (bubble_widget == GetBubbleWidget()) + return; + + if (visible) { + // Another bubble is becoming visible while this bubble is being shown, so + // hide this bubble. + CloseBubble(); + } +} + void NotificationCenterTray::OnNotificationAdded( const std::string& notification_id) { UpdateVisibility();
diff --git a/ash/system/notification_center/notification_center_tray.h b/ash/system/notification_center/notification_center_tray.h index 0700bfe..d5324ec 100644 --- a/ash/system/notification_center/notification_center_tray.h +++ b/ash/system/notification_center/notification_center_tray.h
@@ -43,6 +43,9 @@ // Called when UnifiedSystemTray's preferred visibility changes. void OnSystemTrayVisibilityChanged(bool system_tray_visible); + // True if the bubble is shown. + bool IsBubbleShown() const; + // TrayBackgroundView: std::u16string GetAccessibleNameForTray() override; void HandleLocaleChange() override; @@ -53,6 +56,8 @@ void UpdateAfterLoginStatusChange() override; TrayBubbleView* GetBubbleView() override; views::Widget* GetBubbleWidget() const override; + void OnAnyBubbleVisibilityChanged(views::Widget* bubble_widget, + bool visible) override; private: friend class NotificationCenterTestApi;
diff --git a/ash/system/notification_center/notification_center_tray_unittest.cc b/ash/system/notification_center/notification_center_tray_unittest.cc index 6b60671..4f0ea38 100644 --- a/ash/system/notification_center/notification_center_tray_unittest.cc +++ b/ash/system/notification_center/notification_center_tray_unittest.cc
@@ -10,6 +10,7 @@ #include "ash/system/notification_center/notification_center_test_api.h" #include "ash/system/status_area_widget.h" #include "ash/system/status_area_widget_test_helper.h" +#include "ash/system/unified/unified_system_tray.h" #include "ash/test/ash_test_base.h" #include "base/run_loop.h" #include "base/test/scoped_feature_list.h" @@ -169,6 +170,35 @@ EXPECT_FALSE(test_api()->IsBubbleShown()); } +// Tests that the bubble automatically hides if it is visible when another +// bubble becomes visible, and otherwise does not automatically show or hide. +TEST_F(NotificationCenterTrayTest, BubbleHideBehavior) { + // Basic verification test that the notification center tray bubble can + // show/hide itself when no other bubbles are visible. + EXPECT_FALSE(test_api()->IsBubbleShown()); + test_api()->AddNotification(); + test_api()->ToggleBubble(); + EXPECT_TRUE(test_api()->IsBubbleShown()); + test_api()->ToggleBubble(); + EXPECT_FALSE(test_api()->IsBubbleShown()); + + // Test that the notification center tray bubble automatically hides when it + // is currently visible while another bubble becomes visible. + test_api()->ToggleBubble(); + EXPECT_TRUE(test_api()->IsBubbleShown()); + GetPrimaryUnifiedSystemTray()->ShowBubble(); + EXPECT_FALSE(test_api()->IsBubbleShown()); + + // Hide all currently visible bubbles. + GetPrimaryUnifiedSystemTray()->CloseBubble(); + EXPECT_FALSE(test_api()->IsBubbleShown()); + + // Test that the notification center tray bubble stays hidden when showing + // another bubble. + GetPrimaryUnifiedSystemTray()->ShowBubble(); + EXPECT_FALSE(test_api()->IsBubbleShown()); +} + // TODO(b/252875025): // Add following test cases as we add relevant functionality: // - Focus Change dismissing bubble
diff --git a/ash/system/phonehub/app_stream_launcher_item.cc b/ash/system/phonehub/app_stream_launcher_item.cc index 66ef08c1..cfc86d8d 100644 --- a/ash/system/phonehub/app_stream_launcher_item.cc +++ b/ash/system/phonehub/app_stream_launcher_item.cc
@@ -50,6 +50,7 @@ label_ = AddChildView( std::make_unique<views::Label>(app_metadata.visible_app_name)); + label_->SetTooltipText(app_metadata.visible_app_name); ConfigureLabel(label_, kEcheAppNameLabelLineHeight, kEcheAppNameLabelFontSize); }
diff --git a/ash/system/phonehub/app_stream_launcher_item.h b/ash/system/phonehub/app_stream_launcher_item.h index e279f91..556aab5e 100644 --- a/ash/system/phonehub/app_stream_launcher_item.h +++ b/ash/system/phonehub/app_stream_launcher_item.h
@@ -32,6 +32,9 @@ void RequestFocus() override; const char* GetClassName() const override; + views::Label* get_label_for_test() { return label_; } + PhoneHubRecentAppButton* get_icon_for_test() { return recent_app_button_; } + private: // Owned by views hierarchy. // TODO(b/259426750) refactor PhoneHubRecentAppButton to a more generic name.
diff --git a/ash/system/phonehub/app_stream_launcher_view.cc b/ash/system/phonehub/app_stream_launcher_view.cc index d46dd11..a936670 100644 --- a/ash/system/phonehub/app_stream_launcher_view.cc +++ b/ash/system/phonehub/app_stream_launcher_view.cc
@@ -145,24 +145,12 @@ .SetCrossAxisAlignment(views::LayoutAlignment::kStretch) .SetInteriorMargin(gfx::Insets::VH(kVerticalPaddingBetweenSections, kHorizontalInteriorMargin)); - //.SetDefault(views::kMarginsKey, kVerticalPaddingBetweenSections); // All apps section. items_container_ = scroll_contents->AddChildView(std::make_unique<views::View>()); items_container_->SetPaintToLayer(); items_container_->layer()->SetFillsBoundsOpaquely(false); - auto* table_layout = items_container_->SetLayoutManager( - std::make_unique<views::TableLayout>()); - for (int i = 0; i < kColumns; i++) { - table_layout->AddColumn( - views::LayoutAlignment::kStretch, views::LayoutAlignment::kStretch, 1.0, - views::TableLayout::ColumnSize::kUsePreferred, 0, 0); - } - int n_apps = 107; - table_layout->AddRows(ceil((double)n_apps / kColumns), - views::TableLayout::kFixedSize, kRowHeight); - scroll_view->SetContents(std::move(scroll_contents)); return scroll_view; @@ -187,6 +175,16 @@ const std::vector<phonehub::Notification::AppMetadata>* apps_list = phone_hub_manager_->GetAppStreamLauncherDataModel() ->GetAppsListSortedByName(); + auto* table_layout = items_container_->SetLayoutManager( + std::make_unique<views::TableLayout>()); + for (int i = 0; i < kColumns; i++) { + table_layout->AddColumn( + views::LayoutAlignment::kStretch, views::LayoutAlignment::kStretch, 1.0, + views::TableLayout::ColumnSize::kUsePreferred, 0, 0); + } + table_layout->AddRows(ceil((double)apps_list->size() / kColumns), + views::TableLayout::kFixedSize, kRowHeight); + for (auto& app : *apps_list) { items_container_->AddChildView(CreateItemView(app)); }
diff --git a/ash/system/phonehub/app_stream_launcher_view.h b/ash/system/phonehub/app_stream_launcher_view.h index fd2f444..d692472 100644 --- a/ash/system/phonehub/app_stream_launcher_view.h +++ b/ash/system/phonehub/app_stream_launcher_view.h
@@ -46,9 +46,13 @@ // phonehub::AppStreamLauncherDataModel::Observer: void OnAppListChanged() override; + views::View* items_container_for_test() { return items_container_; } + private: friend class AppStreamLauncherViewTest; FRIEND_TEST_ALL_PREFIXES(AppStreamLauncherViewTest, OpenView); + FRIEND_TEST_ALL_PREFIXES(AppStreamLauncherViewTest, AddItems); + FRIEND_TEST_ALL_PREFIXES(AppStreamLauncherViewTest, ClickOnItem); std::unique_ptr<views::View> CreateAppListView(); std::unique_ptr<views::View> CreateItemView(
diff --git a/ash/system/phonehub/app_stream_launcher_view_unittest.cc b/ash/system/phonehub/app_stream_launcher_view_unittest.cc index 7fc36e0..a7d50d3 100644 --- a/ash/system/phonehub/app_stream_launcher_view_unittest.cc +++ b/ash/system/phonehub/app_stream_launcher_view_unittest.cc
@@ -3,25 +3,38 @@ // found in the LICENSE file. #include "ash/system/phonehub/app_stream_launcher_view.h" +#include "ash/components/phonehub/app_stream_launcher_data_model.h" #include "ash/components/phonehub/fake_phone_hub_manager.h" +#include "ash/components/phonehub/notification.h" #include "ash/components/phonehub/phone_hub_manager.h" #include "ash/constants/ash_features.h" +#include "ash/style/ash_color_provider.h" +#include "ash/system/phonehub/app_stream_launcher_item.h" #include "ash/system/phonehub/phone_hub_metrics.h" #include "ash/test/ash_test_base.h" #include "base/test/scoped_feature_list.h" +#include "ui/events/test/event_generator.h" +#include "ui/gfx/image/image.h" +#include "ui/gfx/image/image_unittest_util.h" +#include "ui/views/controls/label.h" +#include "ui/views/test/views_test_base.h" #include "ui/views/test/views_test_utils.h" #include "ui/views/view.h" +#include "ui/views/widget/widget_utils.h" namespace ash { -class AppStreamLauncherViewTest : public AshTestBase { +class AppStreamLauncherViewTest : public views::ViewsTestBase { public: AppStreamLauncherViewTest() = default; ~AppStreamLauncherViewTest() override = default; - // AshTestBase: + // ViewsTestBase: void SetUp() override { - AshTestBase::SetUp(); + views::ViewsTestBase::SetUp(); + CreateWidget(); + generator_ = + std::make_unique<ui::test::EventGenerator>(GetRootWindow(widget_)); feature_list_.InitWithFeatures( /*enabled_features=*/{features::kEcheLauncher, features::kEcheSWA}, @@ -29,30 +42,161 @@ app_stream_launcher_view_ = std::make_unique<AppStreamLauncherView>(&fake_phone_hub_manager_); + widget_->SetContentsView(app_stream_launcher_view_.get()); + widget_->Show(); + widget_->LayoutRootViewIfNecessary(); } // AshTestBase: void TearDown() override { app_stream_launcher_view_.reset(); - AshTestBase::TearDown(); + generator_.reset(); + views::ViewsTestBase::TearDown(); } protected: + views::Widget* widget() { return widget_; } + ui::test::EventGenerator* generator() { return generator_.get(); } AppStreamLauncherView* app_stream_launcher_view() { return app_stream_launcher_view_.get(); } + + AppStreamLauncherItem* GetItemView(int index) { + return static_cast<AppStreamLauncherItem*>( + app_stream_launcher_view()->items_container_for_test()->children().at( + index)); + } + + const gfx::Image CreateTestImage() { + SkBitmap bitmap; + bitmap.allocN32Pixels(60, 60); + gfx::ImageSkia image_skia = gfx::ImageSkia::CreateFrom1xBitmap(bitmap); + image_skia.MakeThreadSafe(); + return gfx::Image(image_skia); + } + + void CreateWidget() { + DCHECK(!widget_); + widget_ = new views::Widget; + views::Widget::InitParams params = + CreateParams(views::Widget::InitParams::TYPE_WINDOW_FRAMELESS); + params.bounds = gfx::Rect(0, 0, 600, 800); + widget_->Init(std::move(params)); + } + phonehub::FakePhoneHubManager* fake_phone_hub_manager() { return &fake_phone_hub_manager_; } private: + // This is required in order for the context to find color provider + AshColorProvider color_provider_; std::unique_ptr<AppStreamLauncherView> app_stream_launcher_view_; phonehub::FakePhoneHubManager fake_phone_hub_manager_; base::test::ScopedFeatureList feature_list_; + raw_ptr<views::Widget> widget_ = nullptr; + std::unique_ptr<ui::test::EventGenerator> generator_; }; TEST_F(AppStreamLauncherViewTest, OpenView) { EXPECT_TRUE(app_stream_launcher_view()->GetVisible()); } +TEST_F(AppStreamLauncherViewTest, AddItems) { + const int64_t user_id = 1; + const char16_t app_visible_name[] = u"Fake App"; + const char package_name[] = "com.fakeapp"; + + EXPECT_EQ(0U, app_stream_launcher_view() + ->items_container_for_test() + ->children() + .size()); + + auto app1 = phonehub::Notification::AppMetadata( + app_visible_name, package_name, CreateTestImage(), + /*icon_color=*/absl::nullopt, /*icon_is_monochrome=*/true, user_id); + std::vector<phonehub::Notification::AppMetadata> apps; + apps.push_back(app1); + + phonehub::AppStreamLauncherDataModel* data_model = + fake_phone_hub_manager()->fake_app_stream_launcher_data_model(); + data_model->SetAppList(apps); + + EXPECT_EQ(1U, app_stream_launcher_view() + ->items_container_for_test() + ->children() + .size()); + + EXPECT_EQ(u"Fake App", + GetItemView(0)->get_label_for_test()->GetTooltipText()); +} + +TEST_F(AppStreamLauncherViewTest, RemoveItem) { + const int64_t user_id = 1; + const char16_t app_visible_name[] = u"Fake App"; + const char package_name[] = "com.fakeapp"; + + auto app1 = phonehub::Notification::AppMetadata( + app_visible_name, package_name, CreateTestImage(), + /*icon_color=*/absl::nullopt, /*icon_is_monochrome=*/true, user_id); + std::vector<phonehub::Notification::AppMetadata> apps; + apps.push_back(app1); + + phonehub::AppStreamLauncherDataModel* data_model = + fake_phone_hub_manager()->fake_app_stream_launcher_data_model(); + data_model->SetAppList(apps); + + EXPECT_EQ(1U, app_stream_launcher_view() + ->items_container_for_test() + ->children() + .size()); + + EXPECT_EQ(u"Fake App", + GetItemView(0)->get_label_for_test()->GetTooltipText()); + + apps.clear(); + data_model->SetAppList(apps); + + EXPECT_EQ(0U, app_stream_launcher_view() + ->items_container_for_test() + ->children() + .size()); +} + +TEST_F(AppStreamLauncherViewTest, ClickOnItem) { + const int64_t user_id = 1; + const char16_t app_visible_name[] = u"Fake App"; + const char package_name[] = "com.fakeapp"; + + auto app1 = phonehub::Notification::AppMetadata( + app_visible_name, package_name, CreateTestImage(), + /*icon_color=*/absl::nullopt, /*icon_is_monochrome=*/true, user_id); + std::vector<phonehub::Notification::AppMetadata> apps; + apps.push_back(app1); + + phonehub::AppStreamLauncherDataModel* data_model = + fake_phone_hub_manager()->fake_app_stream_launcher_data_model(); + data_model->SetAppList(apps); + widget()->LayoutRootViewIfNecessary(); + + EXPECT_EQ(1U, app_stream_launcher_view() + ->items_container_for_test() + ->children() + .size()); + + ui::test::EventGenerator generator( + GetRootWindow(app_stream_launcher_view()->GetWidget())); + + EXPECT_TRUE(GetItemView(0)->GetVisible()); + + gfx::Point cursor_location = + GetItemView(0)->get_icon_for_test()->GetBoundsInScreen().CenterPoint(); + generator.MoveMouseTo(cursor_location); + generator.ClickLeftButton(); + + EXPECT_EQ(1U, fake_phone_hub_manager() + ->fake_recent_apps_interaction_handler() + ->HandledRecentAppsCount(package_name)); +} + } // namespace ash
diff --git a/ash/system/phonehub/phone_hub_tray_unittest.cc b/ash/system/phonehub/phone_hub_tray_unittest.cc index 533ba41..79c1c72b 100644 --- a/ash/system/phonehub/phone_hub_tray_unittest.cc +++ b/ash/system/phonehub/phone_hub_tray_unittest.cc
@@ -686,15 +686,14 @@ EXPECT_FALSE(content_view()); } -// Flaky. See https://crbug.com/1308967. -TEST_F(PhoneHubTrayTest, DISABLED_OnSessionChanged) { +TEST_F(PhoneHubTrayTest, OnSessionChanged) { ui::ScopedAnimationDurationScaleMode test_duration_mode( ui::ScopedAnimationDurationScaleMode::NORMAL_DURATION); // Disable the tray first. GetFeatureStatusProvider()->SetStatus( phonehub::FeatureStatus::kNotEligibleForFeature); - task_environment()->FastForwardBy(base::Seconds(3)); + FastForwardByConnectingViewGracePeriod(); EXPECT_FALSE(phone_hub_tray_->GetVisible()); // Enable it to let it visible. @@ -720,17 +719,15 @@ EXPECT_TRUE(phone_hub_tray_->GetVisible()); GetFeatureStatusProvider()->SetStatus( phonehub::FeatureStatus::kNotEligibleForFeature); - task_environment()->FastForwardBy(base::Seconds(1)); + FastForwardByConnectingViewGracePeriod(); EXPECT_FALSE(phone_hub_tray_->GetVisible()); GetFeatureStatusProvider()->SetStatus( phonehub::FeatureStatus::kEnabledAndConnected); + task_environment()->FastForwardBy(base::Seconds(3)); } EXPECT_FALSE(phone_hub_tray_->layer()->GetAnimator()->is_animating()); EXPECT_TRUE(phone_hub_tray_->GetVisible()); - // Animation is enabled after 5 seconds. We already fast forwarded 3 second in - // the above loop. So here we are forwarding 2 more seconds. - task_environment()->FastForwardBy(base::Seconds(2)); GetFeatureStatusProvider()->SetStatus( phonehub::FeatureStatus::kNotEligibleForFeature); GetFeatureStatusProvider()->SetStatus(
diff --git a/ash/system/unified/unified_system_tray.cc b/ash/system/unified/unified_system_tray.cc index 7a14849..4026dd5 100644 --- a/ash/system/unified/unified_system_tray.cc +++ b/ash/system/unified/unified_system_tray.cc
@@ -468,6 +468,25 @@ return absl::make_optional(TOGGLE_SYSTEM_TRAY_BUBBLE); } +void UnifiedSystemTray::OnAnyBubbleVisibilityChanged( + views::Widget* bubble_widget, + bool visible) { + if (!features::IsQsRevampEnabled()) + return; + + if (!IsBubbleShown()) + return; + + if (bubble_widget == GetBubbleWidget()) + return; + + if (visible) { + // Another bubble is becoming visible while this bubble is being shown, so + // hide this bubble. + CloseBubble(); + } +} + void UnifiedSystemTray::OnShelfConfigUpdated() { // Ensure the margin is updated correctly depending on whether dense shelf // is currently shown or not.
diff --git a/ash/system/unified/unified_system_tray.h b/ash/system/unified/unified_system_tray.h index 8ab2fb9..18ac4e6 100644 --- a/ash/system/unified/unified_system_tray.h +++ b/ash/system/unified/unified_system_tray.h
@@ -191,6 +191,8 @@ views::Widget* GetBubbleWidget() const override; const char* GetClassName() const override; absl::optional<AcceleratorAction> GetAcceleratorAction() const override; + void OnAnyBubbleVisibilityChanged(views::Widget* bubble_widget, + bool visible) override; // ShelfConfig::Observer: void OnShelfConfigUpdated() override;
diff --git a/ash/system/unified/unified_system_tray_unittest.cc b/ash/system/unified/unified_system_tray_unittest.cc index 0cad528..1f1a6d9 100644 --- a/ash/system/unified/unified_system_tray_unittest.cc +++ b/ash/system/unified/unified_system_tray_unittest.cc
@@ -8,11 +8,13 @@ #include "ash/constants/ash_features.h" #include "ash/ime/ime_controller_impl.h" #include "ash/public/cpp/test/shell_test_api.h" +#include "ash/root_window_controller.h" #include "ash/shelf/shelf.h" #include "ash/shelf/shelf_layout_manager.h" #include "ash/shell.h" #include "ash/strings/grit/ash_strings.h" #include "ash/system/message_center/unified_message_center_bubble.h" +#include "ash/system/notification_center/notification_center_tray.h" #include "ash/system/notification_center/notification_center_view.h" #include "ash/system/status_area_widget.h" #include "ash/system/status_area_widget_test_helper.h" @@ -80,6 +82,31 @@ MessageCenter::Get()->RemoveNotification(id, /*by_user=*/false); } + // Show the notification center bubble. This assumes that there is at least + // one notification in the notification list. This should only be called when + // QsRevamp is enabled. + void ShowNotificationBubble() { + DCHECK(IsQsRevampEnabled()); + Shell::Get() + ->GetPrimaryRootWindowController() + ->shelf() + ->GetStatusAreaWidget() + ->notification_center_tray() + ->ShowBubble(); + } + + // Hide the notification center bubble. This assumes that it is already shown. + // This should only be called when QsRevamp is enabled. + void HideNotificationBubble() { + DCHECK(IsQsRevampEnabled()); + Shell::Get() + ->GetPrimaryRootWindowController() + ->shelf() + ->GetStatusAreaWidget() + ->notification_center_tray() + ->CloseBubble(); + } + bool IsBubbleShown() { return GetPrimaryUnifiedSystemTray()->IsBubbleShown(); } @@ -674,4 +701,38 @@ message_center->SetQuietMode(true); EXPECT_TRUE(quiet_mode_view()->GetVisible()); } + +// Tests that the bubble automatically hides if it is visible when another +// bubble becomes visible, and otherwise does not automatically show or hide. +TEST_P(UnifiedSystemTrayTest, BubbleHideBehavior) { + // This hiding behavior only applies when QsRevamp is enabled. + if (!IsQsRevampEnabled()) + return; + + // Basic verification test that the unified system tray bubble can show/hide + // itself when no other bubbles are visible. + auto* tray = GetPrimaryUnifiedSystemTray(); + EXPECT_FALSE(IsBubbleShown()); + tray->ShowBubble(); + EXPECT_TRUE(IsBubbleShown()); + tray->CloseBubble(); + EXPECT_FALSE(IsBubbleShown()); + + // Test that the unified system tray bubble automatically hides when it is + // currently visible while another bubble becomes visible. + AddNotification(); + tray->ShowBubble(); + EXPECT_TRUE(IsBubbleShown()); + ShowNotificationBubble(); + EXPECT_FALSE(IsBubbleShown()); + + // Hide all currently visible bubbles. + HideNotificationBubble(); + EXPECT_FALSE(IsBubbleShown()); + + // Test that the unified system tray bubble stays hidden when showing another + // bubble. + ShowNotificationBubble(); + EXPECT_FALSE(IsBubbleShown()); +} } // namespace ash
diff --git a/ash/webui/firmware_update_ui/BUILD.gn b/ash/webui/firmware_update_ui/BUILD.gn index 5dd853dc..8da672c 100644 --- a/ash/webui/firmware_update_ui/BUILD.gn +++ b/ash/webui/firmware_update_ui/BUILD.gn
@@ -16,6 +16,7 @@ deps = [ "//ash/components/fwupd:fwupd", + "//ash/constants:constants", "//ash/webui/firmware_update_ui/mojom", "//ash/webui/resources:firmware_update_app_resources", "//chromeos/strings/",
diff --git a/ash/webui/firmware_update_ui/firmware_update_app_ui.cc b/ash/webui/firmware_update_ui/firmware_update_app_ui.cc index 78b22478..a120f66 100644 --- a/ash/webui/firmware_update_ui/firmware_update_app_ui.cc +++ b/ash/webui/firmware_update_ui/firmware_update_app_ui.cc
@@ -8,6 +8,7 @@ #include <utility> #include "ash/components/fwupd/firmware_update_manager.h" +#include "ash/constants/ash_features.h" #include "ash/webui/firmware_update_ui/mojom/firmware_update.mojom.h" #include "ash/webui/firmware_update_ui/url_constants.h" #include "ash/webui/grit/ash_firmware_update_app_resources.h" @@ -69,6 +70,11 @@ } // namespace +bool FirmwareUpdateAppUIConfig::IsWebUIEnabled( + content::BrowserContext* browser_context) { + return ash::features::IsFirmwareUpdaterAppEnabled(); +} + FirmwareUpdateAppUI::FirmwareUpdateAppUI(content::WebUI* web_ui) : ui::MojoWebDialogUI(web_ui) { content::WebUIDataSource* source = content::WebUIDataSource::CreateAndAdd(
diff --git a/ash/webui/firmware_update_ui/firmware_update_app_ui.h b/ash/webui/firmware_update_ui/firmware_update_app_ui.h index a29554ca..9b49f9c 100644 --- a/ash/webui/firmware_update_ui/firmware_update_app_ui.h +++ b/ash/webui/firmware_update_ui/firmware_update_app_ui.h
@@ -6,6 +6,9 @@ #define ASH_WEBUI_FIRMWARE_UPDATE_UI_FIRMWARE_UPDATE_APP_UI_H_ #include "ash/webui/firmware_update_ui/mojom/firmware_update.mojom-forward.h" +#include "ash/webui/firmware_update_ui/url_constants.h" +#include "content/public/browser/webui_config.h" +#include "content/public/common/url_constants.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "ui/web_dialogs/web_dialog_ui.h" @@ -15,6 +18,19 @@ namespace ash { +class FirmwareUpdateAppUI; + +// WebUIConfig for chrome://accessory-update +class FirmwareUpdateAppUIConfig + : public content::DefaultWebUIConfig<FirmwareUpdateAppUI> { + public: + FirmwareUpdateAppUIConfig() + : DefaultWebUIConfig(content::kChromeUIScheme, + ash::kChromeUIFirmwareUpdateAppHost) {} + + bool IsWebUIEnabled(content::BrowserContext* browser_context) override; +}; + class FirmwareUpdateAppUI : public ui::MojoWebDialogUI { public: explicit FirmwareUpdateAppUI(content::WebUI* web_ui);
diff --git a/ash/webui/personalization_app/resources/js/ambient/albums_subpage_element.ts b/ash/webui/personalization_app/resources/js/ambient/albums_subpage_element.ts index d7fae19..e8ac16b 100644 --- a/ash/webui/personalization_app/resources/js/ambient/albums_subpage_element.ts +++ b/ash/webui/personalization_app/resources/js/ambient/albums_subpage_element.ts
@@ -14,7 +14,7 @@ import './art_album_dialog_element.js'; import '../../css/common.css.js'; -import {assert} from 'chrome://resources/js/assert.js'; +import {assert} from 'chrome://resources/js/assert_ts.js'; import {AmbientModeAlbum, TopicSource} from '../personalization_app.mojom-webui.js'; import {PersonalizationRouter} from '../personalization_router_element.js';
diff --git a/ash/webui/personalization_app/resources/js/personalization_test_api.ts b/ash/webui/personalization_app/resources/js/personalization_test_api.ts index 206cd93..2db67781 100644 --- a/ash/webui/personalization_app/resources/js/personalization_test_api.ts +++ b/ash/webui/personalization_app/resources/js/personalization_test_api.ts
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import {assert} from 'chrome://resources/js/assert.js'; +import {assert} from 'chrome://resources/js/assert_ts.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {PersonalizationStore} from './personalization_store.js';
diff --git a/ash/webui/personalization_app/resources/js/user/user_controller.ts b/ash/webui/personalization_app/resources/js/user/user_controller.ts index 4a82655..d01eb78 100644 --- a/ash/webui/personalization_app/resources/js/user/user_controller.ts +++ b/ash/webui/personalization_app/resources/js/user/user_controller.ts
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import {assert} from 'chrome://resources/js/assert.js'; +import {assert} from 'chrome://resources/js/assert_ts.js'; import {BigBuffer, BigBufferSharedMemoryRegion} from 'chrome://resources/mojo/mojo/public/mojom/base/big_buffer.mojom-webui.js'; import {UserProviderInterface} from '../personalization_app.mojom-webui.js';
diff --git a/ash/webui/personalization_app/resources/js/wallpaper/google_photos_metrics_logger.ts b/ash/webui/personalization_app/resources/js/wallpaper/google_photos_metrics_logger.ts index 1451043..c3c4b82 100644 --- a/ash/webui/personalization_app/resources/js/wallpaper/google_photos_metrics_logger.ts +++ b/ash/webui/personalization_app/resources/js/wallpaper/google_photos_metrics_logger.ts
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import {assert} from 'chrome://resources/js/assert.js'; +import {assert} from 'chrome://resources/js/assert_ts.js'; /** * This enum is tied directly to a UMA enum defined in
diff --git a/ash/webui/personalization_app/resources/js/wallpaper/local_images_element.ts b/ash/webui/personalization_app/resources/js/wallpaper/local_images_element.ts index 5a344212..2a9cb1eb 100644 --- a/ash/webui/personalization_app/resources/js/wallpaper/local_images_element.ts +++ b/ash/webui/personalization_app/resources/js/wallpaper/local_images_element.ts
@@ -15,7 +15,7 @@ import '../../common/icons.html.js'; import '../../css/common.css.js'; -import {assert} from 'chrome://resources/js/assert.js'; +import {assert} from 'chrome://resources/js/assert_ts.js'; import {FilePath} from 'chrome://resources/mojo/mojo/public/mojom/base/file_path.mojom-webui.js'; import {Url} from 'chrome://resources/mojo/url/mojom/url.mojom-webui.js'; import {afterNextRender} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
diff --git a/ash/webui/print_management/resources/print_job_entry.ts b/ash/webui/print_management/resources/print_job_entry.ts index e725121e..b1bf660 100644 --- a/ash/webui/print_management/resources/print_job_entry.ts +++ b/ash/webui/print_management/resources/print_job_entry.ts
@@ -14,7 +14,7 @@ import './strings.m.js'; import {I18nMixin} from 'chrome://resources/cr_elements/i18n_mixin.js'; -import {assert, assertNotReached} from 'chrome://resources/js/assert.js'; +import {assert, assertNotReached} from 'chrome://resources/js/assert_ts.js'; import {FocusRowMixin} from 'chrome://resources/js/focus_row_mixin.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {String16} from 'chrome://resources/mojo/mojo/public/mojom/base/string16.mojom-webui.js'; @@ -380,7 +380,6 @@ return loadTimeData.getString('completionStatusPrinted'); default: assertNotReached(); - return loadTimeData.getString('unknownPrinterError'); } } @@ -500,7 +499,6 @@ return loadTimeData.getString('clientUnauthorized'); default: assertNotReached(); - return loadTimeData.getString('unknownPrinterError'); } } @@ -536,10 +534,8 @@ return loadTimeData.getString('clientUnauthorized'); case PrinterErrorCode.kPrinterUnreachable: assertNotReached(); - return loadTimeData.getString('unknownPrinterErrorStopped'); default: assertNotReached(); - return loadTimeData.getString('unknownPrinterErrorStopped'); } } }
diff --git a/ash/webui/print_management/resources/print_management.ts b/ash/webui/print_management/resources/print_management.ts index fd72c9f1..0dd3258 100644 --- a/ash/webui/print_management/resources/print_management.ts +++ b/ash/webui/print_management/resources/print_management.ts
@@ -17,7 +17,7 @@ import {IronIconElement} from '//resources/polymer/v3_0/iron-icon/iron-icon.js'; import {I18nMixin} from 'chrome://resources/cr_elements/i18n_mixin.js'; -import {assert} from 'chrome://resources/js/assert.js'; +import {assert} from 'chrome://resources/js/assert_ts.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {PolymerElementProperties} from 'chrome://resources/polymer/v3_0/polymer/interfaces.js'; import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
diff --git a/ash/wm_mode/wm_mode_button_tray.cc b/ash/wm_mode/wm_mode_button_tray.cc index 1fe9883..c903f9c 100644 --- a/ash/wm_mode/wm_mode_button_tray.cc +++ b/ash/wm_mode/wm_mode_button_tray.cc
@@ -33,6 +33,9 @@ : TrayBackgroundView(shelf, TrayBackgroundViewCatalogName::kWmMode), image_view_(tray_container()->AddChildView( std::make_unique<views::ImageView>())) { + SetPressedCallback(base::BindRepeating( + [](const ui::Event& event) { WmModeController::Get()->Toggle(); })); + image_view_->SetTooltipText(GetAccessibleNameForTray()); image_view_->SetHorizontalAlignment(views::ImageView::Alignment::kCenter); image_view_->SetVerticalAlignment(views::ImageView::Alignment::kCenter); @@ -66,16 +69,6 @@ return u"WM Mode"; } -bool WmModeButtonTray::PerformAction(const ui::Event& event) { - DCHECK(event.type() == ui::ET_MOUSE_RELEASED || - event.type() == ui::ET_GESTURE_TAP || - event.type() == ui::ET_KEY_PRESSED); - - WmModeController::Get()->Toggle(); - - return true; -} - void WmModeButtonTray::OnSessionStateChanged( session_manager::SessionState state) { UpdateButtonVisibility();
diff --git a/ash/wm_mode/wm_mode_button_tray.h b/ash/wm_mode/wm_mode_button_tray.h index d7e5afae..f7d71cb 100644 --- a/ash/wm_mode/wm_mode_button_tray.h +++ b/ash/wm_mode/wm_mode_button_tray.h
@@ -8,10 +8,6 @@ #include "ash/public/cpp/session/session_observer.h" #include "ash/system/tray/tray_background_view.h" -namespace ui { -class Event; -} - namespace views { class ImageView; } @@ -40,7 +36,6 @@ void HandleLocaleChange() override {} void HideBubbleWithView(const TrayBubbleView* bubble_view) override {} void ClickedOutsideBubble() override {} - bool PerformAction(const ui::Event& event) override; // SessionObserver: void OnSessionStateChanged(session_manager::SessionState state) override;
diff --git a/base/BUILD.gn b/base/BUILD.gn index 0f68d70..66e670a 100644 --- a/base/BUILD.gn +++ b/base/BUILD.gn
@@ -1745,6 +1745,8 @@ sources += [ "profiler/chrome_unwind_info_android.cc", "profiler/chrome_unwind_info_android.h", + "profiler/chrome_unwinder_android.cc", + "profiler/chrome_unwinder_android.h", "profiler/chrome_unwinder_android_v2.cc", "profiler/chrome_unwinder_android_v2.h", ] @@ -2646,6 +2648,7 @@ flags = [ "ENABLE_ARM_CFI_TABLE=$enable_arm_cfi_table", "IOS_STACK_PROFILER_ENABLED=$ios_stack_profiler_enabled", + "USE_ANDROID_UNWINDER_V2=$use_android_unwinder_v2", ] } @@ -3641,6 +3644,7 @@ if (current_cpu == "arm") { sources += [ "profiler/chrome_unwind_info_android_unittest.cc", + "profiler/chrome_unwinder_android_unittest.cc", "profiler/chrome_unwinder_android_v2_unittest.cc", ] }
diff --git a/base/profiler/chrome_unwinder_android.cc b/base/profiler/chrome_unwinder_android.cc new file mode 100644 index 0000000..3322b92 --- /dev/null +++ b/base/profiler/chrome_unwinder_android.cc
@@ -0,0 +1,104 @@ +// Copyright 2019 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/profiler/chrome_unwinder_android.h" + +#include "base/numerics/checked_math.h" +#include "base/profiler/module_cache.h" +#include "build/build_config.h" + +namespace base { + +ChromeUnwinderAndroid::ChromeUnwinderAndroid( + const ArmCFITable* cfi_table, + uintptr_t chrome_module_base_address) + : cfi_table_(cfi_table), + chrome_module_base_address_(chrome_module_base_address) { + DCHECK(cfi_table_); +} + +ChromeUnwinderAndroid::~ChromeUnwinderAndroid() = default; + +bool ChromeUnwinderAndroid::CanUnwindFrom(const Frame& current_frame) const { + return current_frame.module && + current_frame.module->GetBaseAddress() == chrome_module_base_address_; +} + +UnwindResult ChromeUnwinderAndroid::TryUnwind(RegisterContext* thread_context, + uintptr_t stack_top, + std::vector<Frame>* stack) { + DCHECK(CanUnwindFrom(stack->back())); + do { + const ModuleCache::Module* module = stack->back().module; + uintptr_t pc = RegisterContextInstructionPointer(thread_context); + DCHECK_GE(pc, module->GetBaseAddress()); + uintptr_t func_addr = pc - module->GetBaseAddress(); + + auto entry = cfi_table_->FindEntryForAddress(func_addr); + if (entry) { + if (!Step(thread_context, stack_top, *entry)) + return UnwindResult::kAborted; + } else if (stack->size() == 1) { + // Try unwinding by sourcing the return address from the lr register. + if (!StepUsingLrRegister(thread_context, stack_top)) + return UnwindResult::kAborted; + } else { + return UnwindResult::kAborted; + } + stack->emplace_back(RegisterContextInstructionPointer(thread_context), + module_cache()->GetModuleForAddress( + RegisterContextInstructionPointer(thread_context))); + } while (CanUnwindFrom(stack->back())); + return UnwindResult::kUnrecognizedFrame; +} + +// static +bool ChromeUnwinderAndroid::Step(RegisterContext* thread_context, + uintptr_t stack_top, + const ArmCFITable::FrameEntry& entry) { + CHECK_NE(RegisterContextStackPointer(thread_context), 0U); + CHECK_LE(RegisterContextStackPointer(thread_context), stack_top); + if (entry.cfa_offset == 0) + return StepUsingLrRegister(thread_context, stack_top); + + // The rules for unwinding using the CFI information are: + // SP_prev = SP_cur + cfa_offset and + // PC_prev = * (SP_prev - ra_offset). + auto new_sp = + CheckedNumeric<uintptr_t>(RegisterContextStackPointer(thread_context)) + + CheckedNumeric<uint16_t>(entry.cfa_offset); + if (!new_sp.AssignIfValid(&RegisterContextStackPointer(thread_context)) || + RegisterContextStackPointer(thread_context) >= stack_top) { + return false; + } + + if (entry.ra_offset > entry.cfa_offset) + return false; + + // Underflow is prevented because |ra_offset| <= |cfa_offset|. + uintptr_t ip_address = (new_sp - CheckedNumeric<uint16_t>(entry.ra_offset)) + .ValueOrDie<uintptr_t>(); + RegisterContextInstructionPointer(thread_context) = + *reinterpret_cast<uintptr_t*>(ip_address); + return true; +} + +// static +bool ChromeUnwinderAndroid::StepUsingLrRegister(RegisterContext* thread_context, + uintptr_t stack_top) { + CHECK_NE(RegisterContextStackPointer(thread_context), 0U); + CHECK_LE(RegisterContextStackPointer(thread_context), stack_top); + + uintptr_t pc = RegisterContextInstructionPointer(thread_context); + uintptr_t return_address = static_cast<uintptr_t>(thread_context->arm_lr); + + // The step failed if the pc doesn't change. + if (pc == return_address) + return false; + + RegisterContextInstructionPointer(thread_context) = return_address; + return true; +} + +} // namespace base
diff --git a/base/profiler/chrome_unwinder_android.h b/base/profiler/chrome_unwinder_android.h new file mode 100644 index 0000000..46728d3d --- /dev/null +++ b/base/profiler/chrome_unwinder_android.h
@@ -0,0 +1,55 @@ +// Copyright 2019 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef BASE_PROFILER_CHROME_UNWINDER_ANDROID_H_ +#define BASE_PROFILER_CHROME_UNWINDER_ANDROID_H_ + +#include <vector> + +#include "base/memory/raw_ptr.h" +#include "base/profiler/unwinder.h" + +#include "base/base_export.h" +#include "base/profiler/arm_cfi_table.h" +#include "base/profiler/module_cache.h" +#include "base/profiler/register_context.h" + +namespace base { + +// Chrome unwinder implementation for Android, using ArmCfiTable. +class BASE_EXPORT ChromeUnwinderAndroid : public Unwinder { + public: + ChromeUnwinderAndroid(const ArmCFITable* cfi_table, + uintptr_t chrome_module_base_address); + ~ChromeUnwinderAndroid() override; + ChromeUnwinderAndroid(const ChromeUnwinderAndroid&) = delete; + ChromeUnwinderAndroid& operator=(const ChromeUnwinderAndroid&) = delete; + + // Unwinder: + bool CanUnwindFrom(const Frame& current_frame) const override; + UnwindResult TryUnwind(RegisterContext* thread_context, + uintptr_t stack_top, + std::vector<Frame>* stack) override; + + static bool StepForTesting(RegisterContext* thread_context, + uintptr_t stack_top, + const ArmCFITable::FrameEntry& entry) { + return Step(thread_context, stack_top, entry); + } + + private: + static bool Step(RegisterContext* thread_context, + uintptr_t stack_top, + const ArmCFITable::FrameEntry& entry); + // Fallback setp that attempts to use lr as return address. + static bool StepUsingLrRegister(RegisterContext* thread_context, + uintptr_t stack_top); + + raw_ptr<const ArmCFITable> cfi_table_; + const uintptr_t chrome_module_base_address_; +}; + +} // namespace base + +#endif // BASE_PROFILER_CHROME_UNWINDER_ANDROID_H_
diff --git a/base/profiler/chrome_unwinder_android_unittest.cc b/base/profiler/chrome_unwinder_android_unittest.cc new file mode 100644 index 0000000..10ae0ea --- /dev/null +++ b/base/profiler/chrome_unwinder_android_unittest.cc
@@ -0,0 +1,309 @@ +// Copyright 2019 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/profiler/chrome_unwinder_android.h" + +#include "base/android/library_loader/anchor_functions.h" +#include "base/files/file_util.h" +#include "base/profiler/profile_builder.h" +#include "base/profiler/stack_buffer.h" +#include "base/profiler/stack_copier_signal.h" +#include "base/profiler/stack_sampling_profiler_test_util.h" +#include "base/profiler/thread_delegate_posix.h" +#include "base/test/gtest_util.h" +#include "build/build_config.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace base { + +namespace { + +// Input is generated from the CFI file: +// STACK CFI INIT 100 100 +// STACK CFI 1010 .cfa: sp 8 + .ra: .cfa -4 + ^ +const uint16_t cfi_data[] = { + // UNW_INDEX size + 0x02, + 0x0, + // UNW_INDEX function_addresses (4 byte rows). + 0x100, + 0x0, + 0x200, + 0x0, + // UNW_INDEX entry_data_indices (2 byte rows). + 0x0, + 0xffff, + // UNW_DATA table. + 0x1, + 0x10, + 0x9, +}; + +// Utility function to add a single native module during test setup. Returns +// a pointer to the provided module. +const ModuleCache::Module* AddNativeModule( + ModuleCache* cache, + std::unique_ptr<const ModuleCache::Module> module) { + const ModuleCache::Module* module_ptr = module.get(); + cache->AddCustomNativeModule(std::move(module)); + return module_ptr; +} + +ArmCFITable::FrameEntry MakeFrameEntry(uint16_t cfa_offset, + uint16_t ra_offset) { + return ArmCFITable::FrameEntry{ + static_cast<uint16_t>(cfa_offset * sizeof(uintptr_t)), + static_cast<uint16_t>(ra_offset * sizeof(uintptr_t))}; +} + +} // namespace + +// Tests unwind step under normal operation. +TEST(ChromeUnwinderAndroidTest, Step) { + const std::vector<uintptr_t> stack_buffer = { + 0xFFFF, 0xFFFF, 0xFFFF, 0x1111, 0xFFFF, 0x2222, + }; + const uintptr_t stack_top = + reinterpret_cast<uintptr_t>(stack_buffer.data() + stack_buffer.size()); + RegisterContext context; + RegisterContextInstructionPointer(&context) = 0xBEEF; + RegisterContextStackPointer(&context) = + reinterpret_cast<uintptr_t>(stack_buffer.data()); + + EXPECT_TRUE(ChromeUnwinderAndroid::StepForTesting(&context, stack_top, + MakeFrameEntry(4, 1))); + EXPECT_EQ(RegisterContextInstructionPointer(&context), 0x1111U); + EXPECT_EQ(RegisterContextStackPointer(&context), + reinterpret_cast<uintptr_t>(stack_buffer.data() + 4)); + + EXPECT_TRUE(ChromeUnwinderAndroid::StepForTesting(&context, stack_top, + MakeFrameEntry(1, 0))); + EXPECT_EQ(RegisterContextInstructionPointer(&context), 0x2222U); + EXPECT_EQ(RegisterContextStackPointer(&context), + reinterpret_cast<uintptr_t>(stack_buffer.data() + 5)); +} + +// Tests unwind step using immediate return address. +TEST(ChromeUnwinderAndroidTest, StepImmediate) { + const std::vector<uintptr_t> stack_buffer = {0xFFFF, 0xFFFF}; + const uintptr_t stack_top = + reinterpret_cast<uintptr_t>(stack_buffer.data() + stack_buffer.size()); + RegisterContext context; + RegisterContextInstructionPointer(&context) = 0xBEEF; + RegisterContextStackPointer(&context) = + reinterpret_cast<uintptr_t>(stack_buffer.data()); + context.arm_lr = 0x4444; + + EXPECT_TRUE(ChromeUnwinderAndroid::StepForTesting(&context, stack_top, + MakeFrameEntry(0, 0))); + EXPECT_EQ(RegisterContextInstructionPointer(&context), 0x4444U); + EXPECT_EQ(RegisterContextStackPointer(&context), + reinterpret_cast<uintptr_t>(stack_buffer.data())); +} + +// Tests that unwinding fails if immediate return address is the current +// instruction. +TEST(ChromeUnwinderAndroidTest, StepImmediateFail) { + const std::vector<uintptr_t> stack_buffer = {0xFFFF, 0xFFFF}; + const uintptr_t stack_top = + reinterpret_cast<uintptr_t>(stack_buffer.data() + stack_buffer.size()); + + RegisterContext context; + RegisterContextInstructionPointer(&context) = 0x1111; + RegisterContextStackPointer(&context) = + reinterpret_cast<uintptr_t>(stack_buffer.data()); + context.arm_lr = 0x1111; + + EXPECT_FALSE(ChromeUnwinderAndroid::StepForTesting(&context, stack_top, + MakeFrameEntry(0, 0))); +} + +// Tests that unwinding fails if stack is invalid. +TEST(ChromeUnwinderAndroidTest, StepInvalidStack) { + const std::vector<uintptr_t> stack_buffer = {0xFFFF}; + + const uintptr_t stack_top = + reinterpret_cast<uintptr_t>(stack_buffer.data() + stack_buffer.size()); + + RegisterContext context; + EXPECT_CHECK_DEATH({ + RegisterContextStackPointer(&context) = 0; + + ChromeUnwinderAndroid::StepForTesting(&context, stack_top, + MakeFrameEntry(1, 0)); + }); + + EXPECT_CHECK_DEATH({ + RegisterContextStackPointer(&context) = reinterpret_cast<uintptr_t>( + stack_buffer.data() + stack_buffer.size() + 1); + + ChromeUnwinderAndroid::StepForTesting(&context, stack_top, + MakeFrameEntry(1, 0)); + }); +} + +// Tests that unwinding fails if the frame entry is out of bounds. +TEST(ChromeUnwinderAndroidTest, StepOutOfBounds) { + RegisterContext context; + RegisterContextInstructionPointer(&context) = 0xBEEF; + constexpr uintptr_t kOverflowOffset = 8; + constexpr size_t kStackSize = 4; + // It's fine to use a fake stack pointer since the stack won't be + // dereferenced. Purposely underflow so that sp + |kOverflowOffset| overflows. + RegisterContextStackPointer(&context) = 0 - kOverflowOffset; + const uintptr_t stack_top = + RegisterContextStackPointer(&context) + kStackSize; + + // ra_offset exceeds cfa_offset. + EXPECT_FALSE(ChromeUnwinderAndroid::StepForTesting(&context, stack_top, + MakeFrameEntry(1, 2))); + EXPECT_FALSE(ChromeUnwinderAndroid::StepForTesting( + &context, stack_top, MakeFrameEntry(1, kOverflowOffset))); + + // cfa_offset exceeds |stack_top|. + EXPECT_FALSE(ChromeUnwinderAndroid::StepForTesting( + &context, stack_top, MakeFrameEntry(kStackSize, 0))); + + // sp + cfa_offset overflows. + EXPECT_FALSE(ChromeUnwinderAndroid::StepForTesting( + &context, stack_top, MakeFrameEntry(kOverflowOffset, 0))); +} + +TEST(ChromeUnwinderAndroidTest, StepUnderflows) { + RegisterContext context; + RegisterContextInstructionPointer(&context) = 0xBEEF; + // It's fine to use a fake stack pointer since the stack won't be + // dereferenced. + RegisterContextStackPointer(&context) = 2; + const uintptr_t stack_top = RegisterContextStackPointer(&context) + 4; + + // sp + cfa_offset - ra_offset underflows. + EXPECT_FALSE(ChromeUnwinderAndroid::StepForTesting(&context, stack_top, + MakeFrameEntry(1, 4))); +} + +TEST(ChromeUnwinderAndroidTest, CanUnwindFrom) { + auto cfi_table = ArmCFITable::Parse( + {reinterpret_cast<const uint8_t*>(cfi_data), sizeof(cfi_data)}); + + auto chrome_module = std::make_unique<TestModule>(0x1000, 0x500); + auto non_chrome_module = std::make_unique<TestModule>(0x2000, 0x500); + + ModuleCache module_cache; + ChromeUnwinderAndroid unwinder(cfi_table.get(), + chrome_module->GetBaseAddress()); + unwinder.Initialize(&module_cache); + + EXPECT_TRUE(unwinder.CanUnwindFrom({0x1100, chrome_module.get()})); + EXPECT_FALSE(unwinder.CanUnwindFrom({0x2100, non_chrome_module.get()})); +} + +TEST(ChromeUnwinderAndroidTest, TryUnwind) { + auto cfi_table = ArmCFITable::Parse( + {reinterpret_cast<const uint8_t*>(cfi_data), sizeof(cfi_data)}); + + ModuleCache module_cache; + const ModuleCache::Module* chrome_module = AddNativeModule( + &module_cache, std::make_unique<TestModule>(0x1000, 0x500)); + + ChromeUnwinderAndroid unwinder(cfi_table.get(), + chrome_module->GetBaseAddress()); + unwinder.Initialize(&module_cache); + + std::vector<uintptr_t> stack_buffer = { + 0xFFFF, + // .cfa: sp 8 + .ra: .cfa -4 + ^ + 0x2000, + 0xFFFF, + }; + uintptr_t stack_top = + reinterpret_cast<uintptr_t>(stack_buffer.data() + stack_buffer.size()); + + std::vector<Frame> stack; + stack.emplace_back(0x1100, chrome_module); + + RegisterContext context; + RegisterContextInstructionPointer(&context) = 0x1100; + RegisterContextStackPointer(&context) = + reinterpret_cast<uintptr_t>(stack_buffer.data()); + context.arm_lr = 0x11AA; + + EXPECT_EQ(UnwindResult::kUnrecognizedFrame, + unwinder.TryUnwind(&context, stack_top, &stack)); + EXPECT_EQ(std::vector<Frame>({{0x1100, chrome_module}, + {0x11AA, chrome_module}, + {0x2000, nullptr}}), + stack); +} + +TEST(ChromeUnwinderAndroidTest, TryUnwindAbort) { + auto cfi_table = ArmCFITable::Parse( + {reinterpret_cast<const uint8_t*>(cfi_data), sizeof(cfi_data)}); + ASSERT_TRUE(cfi_table); + + ModuleCache module_cache; + const ModuleCache::Module* chrome_module = AddNativeModule( + &module_cache, std::make_unique<TestModule>(0x1000, 0x500)); + + ChromeUnwinderAndroid unwinder(cfi_table.get(), + chrome_module->GetBaseAddress()); + unwinder.Initialize(&module_cache); + + std::vector<uintptr_t> stack_buffer = { + 0xFFFF, + }; + uintptr_t stack_top = + reinterpret_cast<uintptr_t>(stack_buffer.data() + stack_buffer.size()); + + std::vector<Frame> stack; + stack.emplace_back(0x1100, chrome_module); + + RegisterContext context; + RegisterContextInstructionPointer(&context) = 0x1100; + RegisterContextStackPointer(&context) = + reinterpret_cast<uintptr_t>(stack_buffer.data()); + context.arm_lr = 0x1100; + + // Aborted because ra == pc. + EXPECT_EQ(UnwindResult::kAborted, + unwinder.TryUnwind(&context, stack_top, &stack)); + EXPECT_EQ(std::vector<Frame>({{0x1100, chrome_module}}), stack); +} + +TEST(ChromeUnwinderAndroidTest, TryUnwindNoData) { + auto cfi_table = ArmCFITable::Parse( + {reinterpret_cast<const uint8_t*>(cfi_data), sizeof(cfi_data)}); + + ModuleCache module_cache; + const ModuleCache::Module* chrome_module = AddNativeModule( + &module_cache, std::make_unique<TestModule>(0x1000, 0x500)); + + ChromeUnwinderAndroid unwinder(cfi_table.get(), + chrome_module->GetBaseAddress()); + unwinder.Initialize(&module_cache); + + std::vector<uintptr_t> stack_buffer = {0xFFFF}; + + uintptr_t stack_top = + reinterpret_cast<uintptr_t>(stack_buffer.data() + stack_buffer.size()); + + std::vector<Frame> stack; + stack.emplace_back(0x1200, chrome_module); + + RegisterContext context; + RegisterContextInstructionPointer(&context) = 0xBEEF; + RegisterContextStackPointer(&context) = + reinterpret_cast<uintptr_t>(stack_buffer.data()); + context.arm_lr = 0x12AA; + + // Unwinding will first use arm_lr as fallback because there's no unwind info + // for the instruction pointer, and then abort. + EXPECT_EQ(UnwindResult::kAborted, + unwinder.TryUnwind(&context, stack_top, &stack)); + EXPECT_EQ( + std::vector<Frame>({{0x1200, chrome_module}, {0x12AA, chrome_module}}), + stack); +} + +} // namespace base
diff --git a/base/profiler/module_cache_unittest.cc b/base/profiler/module_cache_unittest.cc index 2244151..54280a5 100644 --- a/base/profiler/module_cache_unittest.cc +++ b/base/profiler/module_cache_unittest.cc
@@ -96,7 +96,7 @@ } #if (BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_IOS) && !defined(ARCH_CPU_ARM64)) || \ - BUILDFLAG(IS_WIN) + BUILDFLAG(IS_FUCHSIA) || BUILDFLAG(IS_WIN) #define MAYBE_TEST(TestSuite, TestName) TEST(TestSuite, TestName) #else #define MAYBE_TEST(TestSuite, TestName) TEST(TestSuite, DISABLED_##TestName)
diff --git a/base/profiler/stack_sampling_profiler.cc b/base/profiler/stack_sampling_profiler.cc index 8cef744..052bfa2 100644 --- a/base/profiler/stack_sampling_profiler.cc +++ b/base/profiler/stack_sampling_profiler.cc
@@ -760,13 +760,12 @@ } // static -// The profiler is currently supported for Windows x64, macOS, iOS 64-bit, -// Android ARM32, and Android ARM64. +// The profiler is currently supported for Windows x64, macOS, iOS 64-bit, and +// Android ARM32. bool StackSamplingProfiler::IsSupportedForCurrentPlatform() { -#if (BUILDFLAG(IS_WIN) && defined(ARCH_CPU_X86_64)) || BUILDFLAG(IS_MAC) || \ - (BUILDFLAG(IS_IOS) && defined(ARCH_CPU_64_BITS)) || \ - (BUILDFLAG(IS_ANDROID) && \ - (BUILDFLAG(ENABLE_ARM_CFI_TABLE) || defined(ARCH_CPU_ARM64))) +#if (BUILDFLAG(IS_WIN) && defined(ARCH_CPU_X86_64)) || BUILDFLAG(IS_MAC) || \ + (BUILDFLAG(IS_IOS) && defined(ARCH_CPU_64_BITS)) || \ + (BUILDFLAG(IS_ANDROID) && BUILDFLAG(ENABLE_ARM_CFI_TABLE)) #if BUILDFLAG(IS_WIN) // Do not start the profiler when Application Verifier is in use; running them // simultaneously can cause crashes and has no known use case.
diff --git a/base/profiler/stack_sampling_profiler_test_util.cc b/base/profiler/stack_sampling_profiler_test_util.cc index d703d97c..2c70d585 100644 --- a/base/profiler/stack_sampling_profiler_test_util.cc +++ b/base/profiler/stack_sampling_profiler_test_util.cc
@@ -22,10 +22,16 @@ #if BUILDFLAG(IS_ANDROID) && BUILDFLAG(ENABLE_ARM_CFI_TABLE) #include "base/android/apk_assets.h" -#include "base/android/library_loader/anchor_functions.h" #include "base/files/memory_mapped_file.h" -#include "base/profiler/chrome_unwinder_android_v2.h" #include "base/profiler/native_unwinder_android.h" + +#if BUILDFLAG(USE_ANDROID_UNWINDER_V2) +#include "base/android/library_loader/anchor_functions.h" +#include "base/profiler/chrome_unwinder_android_v2.h" +#else +#include "base/profiler/chrome_unwinder_android.h" +#endif + #endif #if BUILDFLAG(IS_WIN) @@ -121,6 +127,7 @@ std::move(maps), std::move(memory), exclude_module_with_base_address); } +#if BUILDFLAG(USE_ANDROID_UNWINDER_V2) std::unique_ptr<Unwinder> CreateChromeUnwinderAndroidForTesting( uintptr_t chrome_module_base_address) { static constexpr char kCfiFileName[] = "assets/unwind_cfi_32_v2"; @@ -156,6 +163,41 @@ chrome_module_base_address, /* text_section_start_address= */ base::android::kStartOfText); } +#else +std::unique_ptr<Unwinder> CreateChromeUnwinderAndroidForTesting( + uintptr_t chrome_module_base_address) { + static constexpr char kCfiFileName[] = "assets/unwind_cfi_32"; + + // The wrapper class ensures that `MemoryMappedFile` has the same lifetime + // as the unwinder. + class ChromeUnwinderAndroidForTesting : public ChromeUnwinderAndroid { + public: + ChromeUnwinderAndroidForTesting(std::unique_ptr<MemoryMappedFile> cfi_file, + std::unique_ptr<ArmCFITable> cfi_table, + uintptr_t chrome_module_base_address) + : ChromeUnwinderAndroid(cfi_table.get(), chrome_module_base_address), + cfi_file_(std::move(cfi_file)), + cfi_table_(std::move(cfi_table)) {} + ~ChromeUnwinderAndroidForTesting() override = default; + + private: + std::unique_ptr<MemoryMappedFile> cfi_file_; + std::unique_ptr<ArmCFITable> cfi_table_; + }; + + MemoryMappedFile::Region cfi_region; + int fd = base::android::OpenApkAsset(kCfiFileName, &cfi_region); + DCHECK_GT(fd, 0); + auto cfi_file = std::make_unique<MemoryMappedFile>(); + bool ok = cfi_file->Initialize(base::File(fd), cfi_region); + DCHECK(ok); + std::unique_ptr<ArmCFITable> cfi_table = + ArmCFITable::Parse({cfi_file->data(), cfi_file->length()}); + DCHECK(cfi_table); + return std::make_unique<ChromeUnwinderAndroidForTesting>( + std::move(cfi_file), std::move(cfi_table), chrome_module_base_address); +} +#endif // #if BUILDFLAG(USE_ANDROID_UNWINDER_V2) #endif // #if BUILDFLAG(IS_ANDROID) && BUILDFLAG(ENABLE_ARM_CFI_TABLE) } // namespace
diff --git a/base/time/time.h b/base/time/time.h index 50fccd59..7f7b07b 100644 --- a/base/time/time.h +++ b/base/time/time.h
@@ -67,6 +67,7 @@ #include <iosfwd> #include <limits> +#include <ostream> #include "base/base_export.h" #include "base/check.h"
diff --git a/base/time/time_win.cc b/base/time/time_win.cc index 452e688..9da2419 100644 --- a/base/time/time_win.cc +++ b/base/time/time_win.cc
@@ -40,6 +40,7 @@ #include <stdint.h> #include <atomic> +#include <ostream> #include "base/bit_cast.h" #include "base/check_op.h"
diff --git a/base/win/scoped_hstring.cc b/base/win/scoped_hstring.cc index f0c15ba..6a8b7ef 100644 --- a/base/win/scoped_hstring.cc +++ b/base/win/scoped_hstring.cc
@@ -6,6 +6,7 @@ #include <winstring.h> +#include <ostream> #include <string> #include "base/check.h"
diff --git a/chrome/android/features/autofill_assistant/BUILD.gn b/chrome/android/features/autofill_assistant/BUILD.gn index e44c239..382e875 100644 --- a/chrome/android/features/autofill_assistant/BUILD.gn +++ b/chrome/android/features/autofill_assistant/BUILD.gn
@@ -175,6 +175,7 @@ "//third_party/hamcrest:hamcrest_java", "//third_party/junit", "//third_party/mockito:mockito_java", + "//ui/accessibility:ax_base_java", "//ui/android:ui_full_java", "//ui/android:ui_java_test_support", "//url:gurl_java",
diff --git a/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantTtsIntegrationTest.java b/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantTtsIntegrationTest.java index a23f2b2f..fc16735c 100644 --- a/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantTtsIntegrationTest.java +++ b/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantTtsIntegrationTest.java
@@ -54,8 +54,8 @@ import org.chromium.chrome.test.ChromeJUnit4ClassRunner; import org.chromium.components.autofill_assistant.AssistantTagsForTesting; import org.chromium.components.autofill_assistant.R; -import org.chromium.content.browser.accessibility.BrowserAccessibilityState; import org.chromium.content_public.browser.test.util.TestThreadUtils; +import org.chromium.ui.accessibility.AccessibilityState; import java.util.ArrayList; import java.util.Collections; @@ -87,7 +87,7 @@ @After public void tearDown() { // Reset accessibility state. - BrowserAccessibilityState.setHasSpokenFeedbackServicePresent(false); + AccessibilityState.setHasSpokenFeedbackServicePresent(false); } private void startAutofillAssistantWithTts(AutofillAssistantTestScript script, @@ -203,7 +203,7 @@ list); // Mock enabling an accessibility service with spoken feedback. - BrowserAccessibilityState.setHasSpokenFeedbackServicePresent(true); + AccessibilityState.setHasSpokenFeedbackServicePresent(true); AutofillAssistantTestTtsController testTtsController = new AutofillAssistantTestTtsController(
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/content/RealtimeEngagementSignalObserver.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/content/RealtimeEngagementSignalObserver.java index 6751d2d..8ceb62ed 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/content/RealtimeEngagementSignalObserver.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/content/RealtimeEngagementSignalObserver.java
@@ -43,11 +43,11 @@ @ActivityScope class RealtimeEngagementSignalObserver extends CustomTabTabObserver { private static final int SCROLL_STATE_MAX_PERCENTAGE_NOT_INCREASING = -1; - // Limit the granularity of data the embedder receives. + // Limit the granularity of data the embedder receives. private static final int SCROLL_PERCENTAGE_GRANULARITY = 5; private final CustomTabsConnection mConnection; - private final TabObserverRegistrar mTabObserverRegisterar; + private final TabObserverRegistrar mTabObserverRegistrar; @Nullable private final CustomTabsSessionToken mSession; @@ -75,10 +75,10 @@ CustomTabsConnection connection, @Nullable CustomTabsSessionToken session) { mConnection = connection; mSession = session; - mTabObserverRegisterar = tabObserverRegistrar; + mTabObserverRegistrar = tabObserverRegistrar; // Do not register observer via tab#addObserver, so it can change tabs when necessary. - mTabObserverRegisterar.registerActivityTabObserver(this); + mTabObserverRegistrar.registerActivityTabObserver(this); } // extends CustomTabTabObserver @@ -93,6 +93,11 @@ maybeStartSendingRealTimeEngagementSignals(tab); } + @Override + protected void onAllTabsClosed() { + removeWebContentsDependencies(mWebContents); + } + // extends TabObserver @Override public void onContentChanged(Tab tab) {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/content/TabObserverRegistrar.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/content/TabObserverRegistrar.java index 4313aa0a..b245da6 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/content/TabObserverRegistrar.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/content/TabObserverRegistrar.java
@@ -69,6 +69,9 @@ @Override public void onAllTabsClosed() { onTabProviderTabUpdated(); + for (CustomTabTabObserver observer : mActivityTabObservers) { + observer.onAllTabsClosed(); + } } }; @@ -215,5 +218,13 @@ * @param tab The tab that the observer is now observing. */ protected void onObservingDifferentTab(@NonNull Tab tab) {} + + /** + * A notification that the observer has been removed from the tab, as all the tabs are + * closing and there's no active tabs left. This is useful when observers need to release + * related dependencies when observers are removed from the tab while the tab is still kept + * alive (e.g. during tab reparenting). + */ + protected void onAllTabsClosed() {} } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabGestureStateListener.java b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabGestureStateListener.java index 4af67db..c4621cf 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabGestureStateListener.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabGestureStateListener.java
@@ -43,8 +43,6 @@ public void initWebContents(WebContents webContents) { GestureListenerManager manager = GestureListenerManager.fromWebContents(webContents); mGestureListener = new GestureStateListener() { - private int mLastScrollOffsetY; - @Override public void onFlingStartGesture( int scrollOffsetY, int scrollExtentY, boolean isDirectionUp) { @@ -60,17 +58,11 @@ public void onScrollStarted( int scrollOffsetY, int scrollExtentY, boolean isDirectionUp) { onScrollingStateChanged(); - mLastScrollOffsetY = scrollOffsetY; } @Override public void onScrollEnded(int scrollOffsetY, int scrollExtentY) { onScrollingStateChanged(); - RewindableIterator<TabObserver> observers = ((TabImpl) mTab).getTabObservers(); - while (observers.hasNext()) { - observers.next().onContentViewScrollingEnded( - mLastScrollOffsetY - scrollOffsetY); - } } private void onScrollingStateChanged() {
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/bookmarks/PowerBookmarkTagChipListRenderTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/bookmarks/PowerBookmarkTagChipListRenderTest.java index c586de1..c4b26bd 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/bookmarks/PowerBookmarkTagChipListRenderTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/bookmarks/PowerBookmarkTagChipListRenderTest.java
@@ -26,6 +26,7 @@ import org.junit.Test; import org.junit.runner.RunWith; +import org.chromium.base.test.util.DisabledTest; import org.chromium.base.test.util.Feature; import org.chromium.base.test.util.Restriction; import org.chromium.chrome.R; @@ -74,6 +75,7 @@ @Test @MediumTest @Feature({"RenderTest"}) + @DisabledTest(message = "https://crbug.com/1394244") public void testTagList() throws IOException { PowerBookmarkMeta.Builder meta = PowerBookmarkMeta.newBuilder(); PowerBookmarkMeta.Tag.Builder tag = PowerBookmarkMeta.Tag.newBuilder();
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index b9fc83b4..72b66450 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -3310,6 +3310,22 @@ {" with minimized state", kPasswordStrengthIndicatorMinimizedVariation, std::size(kPasswordStrengthIndicatorMinimizedVariation), nullptr}}; +#if !BUILDFLAG(IS_ANDROID) +const FeatureEntry::FeatureParam kOsIntegrationSubManagersWriteConfig[] = { + {"stage", "write_config"}}; +const FeatureEntry::FeatureParam + kOsIntegrationSubManagersExecuteAndWriteConfig[] = { + {"stage", "execute_and_write_config"}}; + +const FeatureEntry::FeatureVariation + kOsIntegrationSubManagersConfigVariations[] = { + {"Write Config only", kOsIntegrationSubManagersWriteConfig, + std::size(kOsIntegrationSubManagersWriteConfig), nullptr}, + {"Execute and Write Config", + kOsIntegrationSubManagersExecuteAndWriteConfig, + std::size(kOsIntegrationSubManagersExecuteAndWriteConfig), nullptr}}; +#endif // !BUILDFLAG(IS_ANDROID) + // RECORDING USER METRICS FOR FLAGS: // ----------------------------------------------------------------------------- // The first line of the entry is the internal name. @@ -4439,6 +4455,13 @@ flag_descriptions::kCastStreamingVp9Description, kOsDesktop, FEATURE_VALUE_TYPE(media::kCastStreamingVp9)}, + {"enable-os-integration-sub-managers", + flag_descriptions::kEnableOsIntegrationSubManagersName, + flag_descriptions::kEnableOsIntegrationSubManagersDescription, kOsDesktop, + FEATURE_WITH_PARAMS_VALUE_TYPE(features::kOsIntegrationSubManagers, + kOsIntegrationSubManagersConfigVariations, + "OsIntegrationSubManagers")}, + #endif // !BUILDFLAG(IS_ANDROID) #if BUILDFLAG(IS_ANDROID) @@ -5150,6 +5173,9 @@ {"eche-swa", flag_descriptions::kEcheSWAName, flag_descriptions::kEcheSWADescription, kOsCrOS, FEATURE_VALUE_TYPE(chromeos::features::kEcheSWA)}, + {"eche-launcher", flag_descriptions::kEcheLauncherName, + flag_descriptions::kEcheLauncherDescription, kOsCrOS, + FEATURE_VALUE_TYPE(chromeos::features::kEcheLauncher)}, {"eche-swa-debug-mode", flag_descriptions::kEcheSWADebugModeName, flag_descriptions::kEcheSWADebugModeDescription, kOsCrOS, FEATURE_VALUE_TYPE(chromeos::features::kEcheSWADebugMode)}, @@ -8871,11 +8897,6 @@ flag_descriptions::kEnableVariableRefreshRateDescription, kOsCrOS, FEATURE_VALUE_TYPE(features::kEnableVariableRefreshRate)}, - {"enable-app-provisioning-static-server", - flag_descriptions::kAppProvisioningStaticName, - flag_descriptions::kAppProvisioningStaticDescription, kOsCrOS, - FEATURE_VALUE_TYPE(features::kAppProvisioningStatic)}, - {"enable-projector", flag_descriptions::kProjectorName, flag_descriptions::kProjectorDescription, kOsCrOS, FEATURE_VALUE_TYPE(ash::features::kProjector)}, @@ -9505,6 +9526,11 @@ FEATURE_VALUE_TYPE(::features::kUIEnableSharedImageCacheForGpu)}, #endif +#if !BUILDFLAG(IS_ANDROID) + {"devtools-tab-target", flag_descriptions::kDevToolsTabTargetLiteralName, + flag_descriptions::kDevToolsTabTargetLiteralDescription, kOsDesktop, + FEATURE_VALUE_TYPE(::features::kDevToolsTabTarget)}, +#endif // NOTE: Adding a new flag requires adding a corresponding entry to enum // "LoginCustomFlags" in tools/metrics/histograms/enums.xml. See "Flag // Histograms" in tools/metrics/histograms/README.md (run the
diff --git a/chrome/browser/ash/arc/app_shortcuts/arc_app_shortcuts_menu_builder.cc b/chrome/browser/ash/arc/app_shortcuts/arc_app_shortcuts_menu_builder.cc index cd8eb7b..83507dc 100644 --- a/chrome/browser/ash/arc/app_shortcuts/arc_app_shortcuts_menu_builder.cc +++ b/chrome/browser/ash/arc/app_shortcuts/arc_app_shortcuts_menu_builder.cc
@@ -15,7 +15,6 @@ #include "chrome/browser/ui/app_list/app_list_client_impl.h" #include "chrome/browser/ui/app_list/arc/arc_app_utils.h" #include "chrome/browser/ui/app_list/search/ranking/launch_data.h" -#include "chrome/browser/ui/app_list/search/ranking/ranking_item_util.h" #include "chrome/browser/ui/app_list/search/search_controller.h" #include "ui/base/models/image_model.h" #include "ui/base/models/simple_menu_model.h" @@ -82,7 +81,6 @@ launch_data.id = ConstructArcAppShortcutUrl( app_id_, app_shortcut_items_->at(index).shortcut_id), launch_data.result_type = ash::AppListSearchResultType::kArcAppShortcut; - launch_data.ranking_item_type = app_list::RankingItemType::kArcAppShortcut; app_list_client_impl->search_controller()->Train(std::move(launch_data)); }
diff --git a/chrome/browser/ash/arc/input_overlay/arc_input_overlay_manager.cc b/chrome/browser/ash/arc/input_overlay/arc_input_overlay_manager.cc index ccdecfdf..47a9c31 100644 --- a/chrome/browser/ash/arc/input_overlay/arc_input_overlay_manager.cc +++ b/chrome/browser/ash/arc/input_overlay/arc_input_overlay_manager.cc
@@ -65,6 +65,12 @@ return shell_surface_base && shell_surface_base->HasOverlay(); } +void CheckWriteResult(std::string package_name, bool result) { + if (result) + return; + LOG(ERROR) << "Failed to write proto for " << package_name; +} + } // namespace class ArcInputOverlayManager::InputMethodObserver @@ -133,6 +139,7 @@ ArcInputOverlayManager::~ArcInputOverlayManager() = default; +// static std::unique_ptr<TouchInjector> ArcInputOverlayManager::ReadDefaultData( std::unique_ptr<TouchInjector> touch_injector) { DCHECK(touch_injector); @@ -194,10 +201,15 @@ base::BindOnce(&ArcInputOverlayManager::OnReceiveAppCategory, Unretained(this), std::move(touch_injector))); } else { + if (!data_controller_) { + OnProtoDataAvailable(std::move(touch_injector), /*proto=*/nullptr); + return; + } task_runner_->PostTaskAndReplyWithResult( FROM_HERE, - base::BindOnce(&ArcInputOverlayManager::GetProto, Unretained(this), - package_name), + base::BindOnce( + &DataController::ReadProtoFromFile, + data_controller_->GetFilePathFromPackageName(package_name)), base::BindOnce(&ArcInputOverlayManager::OnProtoDataAvailable, weak_ptr_factory_.GetWeakPtr(), std::move(touch_injector))); @@ -223,18 +235,10 @@ RegisterFocusedWindow(); } -std::unique_ptr<AppDataProto> ArcInputOverlayManager::GetProto( - std::string package_name) { - // |data_controller_| is null for test. - return data_controller_ ? data_controller_->ReadProtoFromFile(package_name) - : nullptr; -} - void ArcInputOverlayManager::OnProtoDataAvailable( std::unique_ptr<TouchInjector> touch_injector, std::unique_ptr<AppDataProto> proto) { DCHECK(touch_injector); - if (proto) { touch_injector->OnProtoDataAvailable(*proto); } else { @@ -260,16 +264,14 @@ void ArcInputOverlayManager::OnSaveProtoFile( std::unique_ptr<AppDataProto> proto, std::string package_name) { - task_runner_->PostTask( + if (!data_controller_) + return; + task_runner_->PostTaskAndReplyWithResult( FROM_HERE, - base::BindOnce(&ArcInputOverlayManager::SaveFile, base::Unretained(this), - std::move(proto), package_name)); -} - -void ArcInputOverlayManager::SaveFile(std::unique_ptr<AppDataProto> proto, - std::string package_name) { - if (data_controller_) - data_controller_->WriteProtoToFile(std::move(proto), package_name); + base::BindOnce( + &DataController::WriteProtoToFile, std::move(proto), + data_controller_->GetFilePathFromPackageName(package_name)), + base::BindOnce(&CheckWriteResult, package_name)); } void ArcInputOverlayManager::NotifyTextInputState() { @@ -407,13 +409,12 @@ base::BindRepeating(&ArcInputOverlayManager::OnSaveProtoFile, weak_ptr_factory_.GetWeakPtr())); loading_data_windows_.insert(top_level_window); - task_runner_->PostTaskAndReplyWithResult( FROM_HERE, - base::BindOnce(&ArcInputOverlayManager::ReadDefaultData, Unretained(this), + base::BindOnce(&ArcInputOverlayManager::ReadDefaultData, std::move(touch_injector)), base::BindOnce(&ArcInputOverlayManager::OnFinishReadDefaultData, - Unretained(this))); + weak_ptr_factory_.GetWeakPtr())); } void ArcInputOverlayManager::OnWindowDestroying(aura::Window* window) {
diff --git a/chrome/browser/ash/arc/input_overlay/arc_input_overlay_manager.h b/chrome/browser/ash/arc/input_overlay/arc_input_overlay_manager.h index 6cb20ce3..82b46b0 100644 --- a/chrome/browser/ash/arc/input_overlay/arc_input_overlay_manager.h +++ b/chrome/browser/ash/arc/input_overlay/arc_input_overlay_manager.h
@@ -93,7 +93,7 @@ class InputMethodObserver; // Read default data. - std::unique_ptr<TouchInjector> ReadDefaultData( + static std::unique_ptr<TouchInjector> ReadDefaultData( std::unique_ptr<TouchInjector> touch_injector); // Called when finishing reading default data. void OnFinishReadDefaultData(std::unique_ptr<TouchInjector> touch_injector); @@ -104,16 +104,12 @@ // there is any. void ReadCustomizedData(const std::string& package_name, std::unique_ptr<TouchInjector> touch_injector); - // Get the Proto object from customized data. - std::unique_ptr<AppDataProto> GetProto(std::string package_name); // Apply the customized proto data. void OnProtoDataAvailable(std::unique_ptr<TouchInjector> touch_injector, std::unique_ptr<AppDataProto> proto); // Callback function triggered by Save button. void OnSaveProtoFile(std::unique_ptr<AppDataProto> proto, std::string package_name); - // Pass |package_name| by value because it runs on task runner. - void SaveFile(std::unique_ptr<AppDataProto> proto, std::string package_name); void NotifyTextInputState(); void AddObserverToInputMethod(); void RemoveObserverFromInputMethod();
diff --git a/chrome/browser/ash/arc/input_overlay/db/data_controller.cc b/chrome/browser/ash/arc/input_overlay/db/data_controller.cc index 232f1c2e9..8a820a4e 100644 --- a/chrome/browser/ash/arc/input_overlay/db/data_controller.cc +++ b/chrome/browser/ash/arc/input_overlay/db/data_controller.cc
@@ -20,6 +20,31 @@ // Base directory for saving customized data in the user profile. constexpr char kPath[] = "google_gio"; +absl::optional<base::FilePath> CreateOrGetDirectory( + const base::FilePath& storage_dir) { + if (base::PathExists(storage_dir)) + return storage_dir; + if (base::CreateDirectory(storage_dir)) + return storage_dir; + + LOG(ERROR) << "Failed to create the base storage directory: " + << storage_dir.value(); + return absl::nullopt; +} + +bool ProtoFileExists(const base::FilePath& file_path) { + return base::PathExists(file_path); +} + +void CreateEmptyFile(const base::FilePath& file_path) { + FILE* file = base::OpenFile(file_path, "wb+"); + if (file == nullptr) { + LOG(ERROR) << "Failed to create file: " << file_path.value(); + return; + } + base::CloseFile(file); +} + } // namespace DataController::DataController( @@ -40,12 +65,10 @@ } std::unique_ptr<AppDataProto> DataController::ReadProtoFromFile( - const std::string& package_name) { - DCHECK(task_runner_->RunsTasksInCurrentSequence()); - auto base_path = CreateOrGetDirectory(); + base::FilePath file_path) { + auto base_path = CreateOrGetDirectory(file_path.DirName()); if (!base_path) return nullptr; - auto file_path = GetFilePathFromPackageName(package_name); if (!ProtoFileExists(file_path)) { CreateEmptyFile(file_path); @@ -62,40 +85,11 @@ } bool DataController::WriteProtoToFile(std::unique_ptr<AppDataProto> proto, - const std::string& package_name) { - DCHECK(task_runner_->RunsTasksInCurrentSequence()); + base::FilePath file_path) { std::string proto_str; if (!proto->SerializeToString(&proto_str)) return false; - return base::WriteFile(GetFilePathFromPackageName(package_name), - proto_str.data(), proto_str.size()) > 0; -} - -absl::optional<base::FilePath> DataController::CreateOrGetDirectory() { - DCHECK(task_runner_->RunsTasksInCurrentSequence()); - if (base::PathExists(storage_dir_)) - return storage_dir_; - if (base::CreateDirectory(storage_dir_)) - return storage_dir_; - - LOG(ERROR) << "Failed to create the base storage directory: " - << storage_dir_.value(); - return absl::nullopt; -} - -bool DataController::ProtoFileExists(base::FilePath file_path) { - DCHECK(task_runner_->RunsTasksInCurrentSequence()); - return base::PathExists(file_path); -} - -void DataController::CreateEmptyFile(base::FilePath file_path) { - DCHECK(task_runner_->RunsTasksInCurrentSequence()); - FILE* file = base::OpenFile(file_path, "wb+"); - if (file == nullptr) { - LOG(ERROR) << "Failed to create file: " << file_path.value(); - return; - } - base::CloseFile(file); + return base::WriteFile(file_path, proto_str.data(), proto_str.size()) > 0; } } // namespace arc::input_overlay
diff --git a/chrome/browser/ash/arc/input_overlay/db/data_controller.h b/chrome/browser/ash/arc/input_overlay/db/data_controller.h index c1cdcfe9..b1fa8af 100644 --- a/chrome/browser/ash/arc/input_overlay/db/data_controller.h +++ b/chrome/browser/ash/arc/input_overlay/db/data_controller.h
@@ -19,23 +19,16 @@ ~DataController(); // Read Proto object from file and return the Proto object for app - // |package_name|. - std::unique_ptr<AppDataProto> ReadProtoFromFile( - const std::string& package_name); - // Write the Proto object |proto| to file for app |package_name|. - bool WriteProtoToFile(std::unique_ptr<AppDataProto> proto, - const std::string& package_name); + // |file_path|. + static std::unique_ptr<AppDataProto> ReadProtoFromFile( + base::FilePath file_path); + // Write the Proto object |proto| to file for app |file_path|. + static bool WriteProtoToFile(std::unique_ptr<AppDataProto> proto, + base::FilePath file_path); + + base::FilePath GetFilePathFromPackageName(const std::string& package_name); private: - // Create the base directory as |storage_dir_| if it doesn't exist. If it - // returns null, the base directory didn't create successfully. - absl::optional<base::FilePath> CreateOrGetDirectory(); - base::FilePath GetFilePathFromPackageName(const std::string& package_name); - // Check if file |file_path| exists. - bool ProtoFileExists(base::FilePath file_path); - // Create empty file if file |file_path| doesn't exists. - void CreateEmptyFile(base::FilePath file_path); - // Base directory for GIO in the user profile. base::FilePath storage_dir_; // Task runner for the I/O functions.
diff --git a/chrome/browser/ash/crosapi/browser_manager.cc b/chrome/browser/ash/crosapi/browser_manager.cc index dee1a3de..f3d8abf4a 100644 --- a/chrome/browser/ash/crosapi/browser_manager.cc +++ b/chrome/browser/ash/crosapi/browser_manager.cc
@@ -47,6 +47,7 @@ #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "base/threading/thread_restrictions.h" +#include "build/build_config.h" #include "chrome/browser/apps/app_service/app_service_proxy_factory.h" #include "chrome/browser/ash/crosapi/browser_action.h" #include "chrome/browser/ash/crosapi/browser_data_migrator.h" @@ -192,6 +193,72 @@ return false; } +void PreloadFile(base::FilePath file_path) { + DLOG(WARNING) << "Preloading " << file_path; + + base::File file(file_path, base::File::FLAG_OPEN | base::File::FLAG_READ); + DPCHECK(file.IsValid()); + if (!file.IsValid()) { + PLOG(WARNING) << "Failed opening " << file_path << " while preloading"; + return; + } + + int64_t file_size = file.GetLength(); + if (file_size < 0) { + PLOG(WARNING) << "Failed getting size of " << file_path + << "while preloading"; + return; + } + + if (readahead(file.GetPlatformFile(), 0, file_size) < 0) { + PLOG(WARNING) << "Failed preloading " << file_path; + return; + } + + DLOG(WARNING) << "Preloaded " << file_path; +} + +void PreloadLacrosFiles(const base::FilePath& lacros_dir) { + // These files are the Lacros equivalent of Ash's files preloaded at boot by + // ureadahead. + static constexpr const char* kPreloadFiles[] = { + "WidevineCdm/manifest.json", + "chrome", + "chrome_100_percent.pak", + "chrome_200_percent.pak", + "chrome_crashpad_handler", + "icudtl.dat", + "icudtl.dat.hash", + "nacl_helper", + "resources.pak", + "snapshot_blob.bin", + }; + + // Preload common files. + for (const char* file_name : kPreloadFiles) { + base::FilePath file_path = lacros_dir.Append(base::FilePath(file_name)); + PreloadFile(file_path); + } + + // Preload localization pack. + std::string locale = g_browser_process->GetApplicationLocale(); + base::FilePath locale_path = + lacros_dir.Append(base::StringPrintf("locales/%s.pak", locale.c_str())); + PreloadFile(locale_path); + base::FilePath locale_info_path = locale_path.AddExtension(".info"); + PreloadFile(locale_info_path); + + // Preload Widevine for the right architecture. +#if defined(ARCH_CPU_ARM_FAMILY) + base::FilePath libwidevine_path = lacros_dir.Append( + "WidevineCdm/_platform_specific/cros_arm/libwidevinecdm.so"); +#else + base::FilePath libwidevine_path = lacros_dir.Append( + "WidevineCdm/_platform_specific/cros_x64/libwidevinecdm.so"); +#endif + PreloadFile(libwidevine_path); +} + ResourcesFileSharingMode ClearOrMoveSharedResourceFileInternal( bool clear_shared_resource_file, base::FilePath shared_resource_path) { @@ -256,7 +323,8 @@ // The returns struct is used by the main thread as parameters to launch Lacros. LaunchParamsFromBackground DoLacrosBackgroundWorkPreLaunch( base::FilePath lacros_dir, - bool clear_shared_resource_file) { + bool clear_shared_resource_file, + bool launching_at_login_screen) { LaunchParamsFromBackground params; if (!RotateLacrosLogs()) { @@ -314,6 +382,13 @@ } } + // When launching at login screen, we can take advantage of the time before + // the user inputs the password and logs in to preload Lacros-related files. + // This speeds up the perceived startup time, as they will be loaded anyway + // in the later stages of Lacros's lifetime. + if (launching_at_login_screen) + PreloadLacrosFiles(lacros_dir); + return params; } @@ -867,7 +942,8 @@ base::ThreadPool::PostTaskAndReplyWithResult( FROM_HERE, {base::MayBlock()}, base::BindOnce(&DoLacrosBackgroundWorkPreLaunch, lacros_path_, - is_initial_lacros_launch_after_reboot_), + is_initial_lacros_launch_after_reboot_, + launching_at_login_screen), base::BindOnce(&BrowserManager::StartWithLogFile, weak_factory_.GetWeakPtr()));
diff --git a/chrome/browser/ash/file_manager/file_manager_jstest.cc b/chrome/browser/ash/file_manager/file_manager_jstest.cc index 63425df..7070cdab 100644 --- a/chrome/browser/ash/file_manager/file_manager_jstest.cc +++ b/chrome/browser/ash/file_manager/file_manager_jstest.cc
@@ -322,6 +322,10 @@ RunTestURL("state/reducers/current_directory_unittest.js"); } +IN_PROC_BROWSER_TEST_F(FileManagerJsTest, ReducerSearch) { + RunTestURL("state/reducers/search_unittest.js"); +} + IN_PROC_BROWSER_TEST_F(FileManagerJsTest, XfConflictDialog) { RunTestURL("widgets/xf_conflict_dialog_unittest.js"); }
diff --git a/chrome/browser/component_updater/app_provisioning_component_installer.cc b/chrome/browser/component_updater/app_provisioning_component_installer.cc index e4c3ee08..a00d2ad 100644 --- a/chrome/browser/component_updater/app_provisioning_component_installer.cc +++ b/chrome/browser/component_updater/app_provisioning_component_installer.cc
@@ -167,10 +167,7 @@ } void RegisterAppProvisioningComponent(component_updater::ComponentUpdateService* cus) { - // If either of these flags are enabled, register the component. Otherwise, - // don't. - if (base::FeatureList::IsEnabled(features::kAppProvisioningStatic) || - chromeos::features::IsCloudGamingDeviceEnabled()) { + if (chromeos::features::IsCloudGamingDeviceEnabled()) { VLOG(1) << "Registering App Provisioning component."; auto installer = base::MakeRefCounted<ComponentInstaller>( std::make_unique<AppProvisioningComponentInstallerPolicy>());
diff --git a/chrome/browser/dips/dips_features.cc b/chrome/browser/dips/dips_features.cc index fb0cbe5..0fecc9b7 100644 --- a/chrome/browser/dips/dips_features.cc +++ b/chrome/browser/dips/dips_features.cc
@@ -26,4 +26,16 @@ const base::FeatureParam<base::TimeDelta> kTimerDelay{&kFeature, "timer_delay", base::Hours(24)}; +// Sets the actions which will trigger DIPS clearing for a site. The default is +// to set to kBounce, but can be overridden by Finch experiment groups or by +// command-line flags. +constexpr base::FeatureParam<DIPSTriggeringAction>::Option + kTriggeringActionOptions[] = { + {DIPSTriggeringAction::kStorage, "storage"}, + {DIPSTriggeringAction::kBounce, "bounce"}, + {DIPSTriggeringAction::kStatefulBounce, "stateful_bounce"}}; +const base::FeatureParam<DIPSTriggeringAction> kTriggeringAction{ + &kFeature, "triggering_action", DIPSTriggeringAction::kBounce, + &kTriggeringActionOptions}; + } // namespace dips
diff --git a/chrome/browser/dips/dips_features.h b/chrome/browser/dips/dips_features.h index 5299717..951ef8c 100644 --- a/chrome/browser/dips/dips_features.h +++ b/chrome/browser/dips/dips_features.h
@@ -8,6 +8,7 @@ #include "base/feature_list.h" #include "base/metrics/field_trial_params.h" #include "base/time/time.h" +#include "chrome/browser/dips/dips_utils.h" namespace dips { @@ -15,6 +16,7 @@ extern const base::FeatureParam<bool> kPersistedDatabaseEnabled; extern const base::FeatureParam<base::TimeDelta> kGracePeriod; extern const base::FeatureParam<base::TimeDelta> kTimerDelay; +extern const base::FeatureParam<DIPSTriggeringAction> kTriggeringAction; } // namespace dips
diff --git a/chrome/browser/dips/dips_utils.h b/chrome/browser/dips/dips_utils.h index ae534c2..6774d9e 100644 --- a/chrome/browser/dips/dips_utils.h +++ b/chrome/browser/dips/dips_utils.h
@@ -123,6 +123,8 @@ rhs.stateful_bounce_times, rhs.stateless_bounce_times); } +enum class DIPSTriggeringAction { kStorage, kBounce, kStatefulBounce }; + // Return the number of seconds in `td`, clamped to [0, 10]. // i.e. 11 linearly-sized buckets. int64_t BucketizeBounceDelay(base::TimeDelta delta);
diff --git a/chrome/browser/extensions/extension_service.cc b/chrome/browser/extensions/extension_service.cc index 8826dd1..38dfe9f 100644 --- a/chrome/browser/extensions/extension_service.cc +++ b/chrome/browser/extensions/extension_service.cc
@@ -432,10 +432,6 @@ SetCurrentDeveloperMode( util::GetBrowserContextId(profile), profile->GetPrefs()->GetBoolean(prefs::kExtensionsUIDeveloperMode)); - - // How long is the path to the Extensions directory? - UMA_HISTOGRAM_CUSTOM_COUNTS("Extensions.ExtensionRootPathLength", - install_directory_.value().length(), 1, 500, 100); } PendingExtensionManager* ExtensionService::pending_extension_manager() { @@ -561,10 +557,6 @@ } } MaybeFinishDelayedInstallations(); - std::unique_ptr<ExtensionPrefs::ExtensionsInfo> delayed_info2( - extension_prefs_->GetAllDelayedInstallInfo()); - UMA_HISTOGRAM_COUNTS_100("Extensions.UpdateOnLoad", - delayed_info2->size() - delayed_info->size()); } scoped_refptr<CrxInstaller> ExtensionService::CreateUpdateInstaller( @@ -1299,7 +1291,6 @@ CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); TRACE_EVENT0("browser,startup", "ExtensionService::CheckForExternalUpdates"); - SCOPED_UMA_HISTOGRAM_TIMER("Extensions.CheckForExternalUpdatesTime"); // Note that this installation is intentionally silent (since it didn't // go through the front-end). Extensions that are registered in this @@ -1705,10 +1696,6 @@ UMA_HISTOGRAM_ENUMERATION("Extensions.InstallSource", extension->location()); RecordPermissionMessagesHistogram(extension, "Install"); - } else { - UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateType", extension->GetType(), - 100); - UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateSource", extension->location()); } const Extension::State initial_state =
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index 69d9d50..c3904b2f 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -1302,6 +1302,11 @@ "expiry_milestone": 112 }, { + "name": "devtools-tab-target", + "owners": [ "dsv", "caseq" ], + "expiry_milestone": 112 + }, + { "name": "diagnostics-app-navigation", "owners": [ "//ash/webui/diagnostics_ui/OWNERS" ], "expiry_milestone": 112 @@ -1552,29 +1557,34 @@ "expiry_milestone": 112 }, { + "name": "eche-launcher", + "owners": [ "jonmann" ], + "expiry_milestone": 115 + }, + { "name": "eche-swa", "owners": [ "dhnishi" ], - "expiry_milestone": 110 + "expiry_milestone": 115 }, { "name": "eche-swa-debug-mode", "owners": [ "dhnishi" ], - "expiry_milestone": 110 + "expiry_milestone": 115 }, { "name": "eche-swa-disable-stun-server", "owners": [ "dhnishi", "mavishsu@google.com", "ftsui@google.com" ], - "expiry_milestone": 110 + "expiry_milestone": 115 }, { "name": "eche-swa-measure-latency", "owners": [ "paulzchen@google.com", "guanrulee@google.com" ], - "expiry_milestone": 110 + "expiry_milestone": 115 }, { "name": "eche-swa-send-start-signaling", "owners": [ "dhnishi", "mavishsu@google.com" ], - "expiry_milestone": 110 + "expiry_milestone": 115 }, { "name": "edit-context", @@ -1637,11 +1647,6 @@ "expiry_milestone": 110 }, { - "name": "enable-app-provisioning-static-server", - "owners": ["melzhang", "mxcai", "chromeos-apps-foundation-team"], - "expiry_milestone": 110 - }, - { "name": "enable-app-service-in-kiosk", "owners": ["yixie", "chromeos-kiosk-eng@google.com"], "expiry_milestone": 130 @@ -2713,6 +2718,11 @@ "expiry_milestone": 116 }, { + "name": "enable-os-integration-sub-managers", + "owners": [ "dibyapal@chromium.org", "desktop-pwas-team@google.com" ], + "expiry_milestone": 120 + }, + { "name": "enable-palm-max-touch-major", "owners": [ "robsc", "napper", "adlr" ], // Added feature to possibly disable/enable this functionality, combined
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index b072420..955655ff 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -1539,6 +1539,13 @@ const char kContextualPageActionsReaderModeDescription[] = "Enables reader mode as a contextual page action."; +const char kEnableOsIntegrationSubManagersName[] = + "OS Integration sub managers"; +const char kEnableOsIntegrationSubManagersDescription[] = + "Enable OS integration sub managers to either just write new OS " + "integration states to DB or execute on the OS integration states before " + "writing to the DB"; + const char kHandwritingGestureEditingName[] = "Handwriting Gestures Editing"; const char kHandwritingGestureEditingDescription[] = "Enables editing with handwriting gestures within the virtual keyboard."; @@ -4399,6 +4406,10 @@ "attestation statement from a security key when creating a Web " "Authentication credential."; +const char kDevToolsTabTargetLiteralName[] = "DevTools using Tab Target"; +const char kDevToolsTabTargetLiteralDescription[] = + "Makes DevTools use an experimental CDP Tab target."; + #endif // BUILDFLAG(IS_ANDROID) // Windows --------------------------------------------------------------------- @@ -4669,12 +4680,6 @@ const char kAppDiscoveryForOobeDescription[] = "Use the App Discovery Service to request recommended apps for OOBE."; -const char kAppProvisioningStaticName[] = - "App Provisioning with static server setup."; -const char kAppProvisioningStaticDescription[] = - "Enables pulling apps from a static server setup to enable new app serving " - "possibilities. "; - const char kArcCustomTabsExperimentName[] = "Enable Custom Tabs experiment for ARC"; const char kArcCustomTabsExperimentDescription[] = @@ -5328,6 +5333,10 @@ const char kEcheSWAName[] = "Enable Eche feature"; const char kEcheSWADescription[] = "This is the main flag for enabling Eche."; +const char kEcheLauncherName[] = "Enable the Eche launcher"; +const char kEcheLauncherDescription[] = + "Enables the launcher for all apps for Eche."; + const char kEcheSWADebugModeName[] = "Enable Eche Debug Mode"; const char kEcheSWADebugModeDescription[] = "Save console logs of Eche in the system log";
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index efbafe6..dcc235ce 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -861,6 +861,9 @@ extern const char kContextualPageActionsReaderModeName[]; extern const char kContextualPageActionsReaderModeDescription[]; +extern const char kEnableOsIntegrationSubManagersName[]; +extern const char kEnableOsIntegrationSubManagersDescription[]; + extern const char kGpuRasterizationName[]; extern const char kGpuRasterizationDescription[]; @@ -2526,6 +2529,9 @@ extern const char kWebAuthenticationPermitEnterpriseAttestationName[]; extern const char kWebAuthenticationPermitEnterpriseAttestationDescription[]; +extern const char kDevToolsTabTargetLiteralName[]; +extern const char kDevToolsTabTargetLiteralDescription[]; + #endif // BUILDFLAG(IS_ANDROID) // Windows -------------------------------------------------------------------- @@ -2687,9 +2693,6 @@ extern const char kAppDiscoveryForOobeName[]; extern const char kAppDiscoveryForOobeDescription[]; -extern const char kAppProvisioningStaticName[]; -extern const char kAppProvisioningStaticDescription[]; - extern const char kArcCustomTabsExperimentName[]; extern const char kArcCustomTabsExperimentDescription[]; @@ -3049,6 +3052,9 @@ extern const char kEcheSWAName[]; extern const char kEcheSWADescription[]; +extern const char kEcheLauncherName[]; +extern const char kEcheLauncherDescription[]; + extern const char kEcheSWADebugModeName[]; extern const char kEcheSWADebugModeDescription[];
diff --git a/chrome/browser/lens/region_search/BUILD.gn b/chrome/browser/lens/region_search/BUILD.gn index 29f5f176..166208262 100644 --- a/chrome/browser/lens/region_search/BUILD.gn +++ b/chrome/browser/lens/region_search/BUILD.gn
@@ -10,6 +10,8 @@ "../metrics/lens_metrics.h", "lens_region_search_controller.cc", "lens_region_search_controller.h", + "lens_region_search_helper.cc", + "lens_region_search_helper.h", ] # TODO(crbug/1383280): Remove allow_circular_includes_from when dependencies for controller are fixed.
diff --git a/chrome/browser/lens/region_search/lens_region_search_controller.cc b/chrome/browser/lens/region_search/lens_region_search_controller.cc index 94b8c80d..6005ca01 100644 --- a/chrome/browser/lens/region_search/lens_region_search_controller.cc +++ b/chrome/browser/lens/region_search/lens_region_search_controller.cc
@@ -26,6 +26,9 @@ namespace lens { +LensRegionSearchControllerData::LensRegionSearchControllerData() = default; +LensRegionSearchControllerData::~LensRegionSearchControllerData() = default; + RegionSearchCapturedData::RegionSearchCapturedData() = default; RegionSearchCapturedData::~RegionSearchCapturedData() = default;
diff --git a/chrome/browser/lens/region_search/lens_region_search_controller.h b/chrome/browser/lens/region_search/lens_region_search_controller.h index d496bca..2fb1a121 100644 --- a/chrome/browser/lens/region_search/lens_region_search_controller.h +++ b/chrome/browser/lens/region_search/lens_region_search_controller.h
@@ -107,8 +107,23 @@ base::WeakPtrFactory<LensRegionSearchController> weak_factory_{this}; }; -// Class to associate region search data with Profile across navigation. Used to -// support region search on a static WebUI page. +// Class to associate region search controller data with Profile across +// navigation. Used to support region search via keyboard shortcut. +class LensRegionSearchControllerData : public base::SupportsUserData::Data { + public: + LensRegionSearchControllerData(); + ~LensRegionSearchControllerData() override; + LensRegionSearchControllerData(const LensRegionSearchControllerData&) = + delete; + LensRegionSearchControllerData& operator=( + const LensRegionSearchControllerData&) = delete; + + static constexpr char kDataKey[] = "lens_region_search_controller_data"; + std::unique_ptr<LensRegionSearchController> lens_region_search_controller; +}; + +// Class to associate region search captured data with Profile across +// navigation. Used to support region search on a static WebUI page. class RegionSearchCapturedData : public base::SupportsUserData::Data { public: RegionSearchCapturedData();
diff --git a/chrome/browser/lens/region_search/lens_region_search_helper.cc b/chrome/browser/lens/region_search/lens_region_search_helper.cc new file mode 100644 index 0000000..6272898 --- /dev/null +++ b/chrome/browser/lens/region_search/lens_region_search_helper.cc
@@ -0,0 +1,59 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/lens/region_search/lens_region_search_helper.h" + +#include "base/feature_list.h" +#include "build/branding_buildflags.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/search_engines/template_url_service_factory.h" +#include "chrome/browser/ui/browser.h" +#include "chrome/common/pref_names.h" +#include "components/lens/lens_features.h" +#include "components/prefs/pref_service.h" +#include "components/search_engines/template_url.h" +#include "components/search_engines/template_url_service.h" +#include "content/public/browser/navigation_entry.h" +#include "content/public/browser/web_contents.h" +#include "content/public/common/url_constants.h" +#include "url/gurl.h" + +namespace lens { + +bool IsRegionSearchEnabled(Browser* browser, + Profile* profile, + const GURL& url) { +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) + if (!browser) + return false; + + TemplateURLService* service = + TemplateURLServiceFactory::GetForProfile(profile); + if (!service) + return false; + +// Region selection is broken in PWAs on Mac b/250074889 +#if BUILDFLAG(IS_MAC) + if (IsInProgressiveWebApp(browser)) + return false; +#endif // BUILDFLAG(IS_MAC) + + const TemplateURL* provider = service->GetDefaultSearchProvider(); + const bool provider_supports_image_search = + provider && !provider->image_url().empty() && + provider->image_url_ref().IsValid(service->search_terms_data()); + return base::FeatureList::IsEnabled(lens::features::kLensStandalone) && + provider_supports_image_search && + !url.SchemeIs(content::kChromeUIScheme) && + profile->GetPrefs()->GetBoolean(prefs::kLensRegionSearchEnabled); +#else + return false; +#endif // BUILDFLAG(GOOGLE_CHROME_BRANDING) +} + +bool IsInProgressiveWebApp(Browser* browser) { + return browser && (browser->is_type_app() || browser->is_type_app_popup()); +} + +} // namespace lens
diff --git a/chrome/browser/lens/region_search/lens_region_search_helper.h b/chrome/browser/lens/region_search/lens_region_search_helper.h new file mode 100644 index 0000000..adca097 --- /dev/null +++ b/chrome/browser/lens/region_search/lens_region_search_helper.h
@@ -0,0 +1,20 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_LENS_REGION_SEARCH_LENS_REGION_SEARCH_HELPER_H_ +#define CHROME_BROWSER_LENS_REGION_SEARCH_LENS_REGION_SEARCH_HELPER_H_ + +class Browser; +class Profile; +class GURL; + +namespace lens { + +bool IsRegionSearchEnabled(Browser* browser, Profile* profile, const GURL& url); + +bool IsInProgressiveWebApp(Browser* browser); + +} // namespace lens + +#endif // CHROME_BROWSER_LENS_REGION_SEARCH_LENS_REGION_SEARCH_HELPER_H_
diff --git a/chrome/browser/renderer_context_menu/render_view_context_menu.cc b/chrome/browser/renderer_context_menu/render_view_context_menu.cc index b308b85..7ff50782 100644 --- a/chrome/browser/renderer_context_menu/render_view_context_menu.cc +++ b/chrome/browser/renderer_context_menu/render_view_context_menu.cc
@@ -3273,6 +3273,8 @@ bool RenderViewContextMenu::IsRegionSearchEnabled() const { #if BUILDFLAG(GOOGLE_CHROME_BRANDING) + // TODO(nguyenbryan): Refactor to use lens_region_search_helper.cc after PDF + // support is cleaned up. if (!GetBrowser()) return false;
diff --git a/chrome/browser/resources/.eslintignore b/chrome/browser/resources/.eslintignore index 4c4f085e7..0e84e12 100644 --- a/chrome/browser/resources/.eslintignore +++ b/chrome/browser/resources/.eslintignore
@@ -1,2 +1,4 @@ # Ignore because eslint doesn't understand // <if expr> gaia_auth_host/authenticator.js +gaia_auth_host/password_change_authenticator.js +gaia_auth_host/saml_username_autofill.js
diff --git a/chrome/browser/resources/about_sys/about_sys.js b/chrome/browser/resources/about_sys/about_sys.js index 625989ae..01dfd272 100644 --- a/chrome/browser/resources/about_sys/about_sys.js +++ b/chrome/browser/resources/about_sys/about_sys.js
@@ -4,9 +4,9 @@ import './strings.m.js'; -import {sendWithPromise} from 'chrome://resources/js/cr.m.js'; +import {sendWithPromise} from 'chrome://resources/js/cr.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; -import {$} from 'chrome://resources/js/util.js'; +import {$} from 'chrome://resources/js/util_ts.js'; // Contents of lines that act as delimiters for multi-line values. const DELIM_START = '---------- START ----------';
diff --git a/chrome/browser/resources/apc_internals/apc_internals.js b/chrome/browser/resources/apc_internals/apc_internals.js index 5fb5ea2..9d06d81d 100644 --- a/chrome/browser/resources/apc_internals/apc_internals.js +++ b/chrome/browser/resources/apc_internals/apc_internals.js
@@ -3,7 +3,7 @@ // found in the LICENSE file. import {addWebUiListener} from 'chrome://resources/js/cr.js'; -import {$} from 'chrome://resources/js/util.js'; +import {$} from 'chrome://resources/js/util_ts.js'; function createButton(text, onClickClosure) { const button = document.createElement('button');
diff --git a/chrome/browser/resources/bluetooth_internals/adapter_page.js b/chrome/browser/resources/bluetooth_internals/adapter_page.js index 3d41a6ce..62986e4 100644 --- a/chrome/browser/resources/bluetooth_internals/adapter_page.js +++ b/chrome/browser/resources/bluetooth_internals/adapter_page.js
@@ -8,7 +8,7 @@ import './object_fieldset.js'; -import {$} from 'chrome://resources/js/util.js'; +import {$} from 'chrome://resources/js/util_ts.js'; import {AdapterInfo} from './adapter.mojom-webui.js'; import {Page} from './page.js';
diff --git a/chrome/browser/resources/bluetooth_internals/bluetooth_internals.js b/chrome/browser/resources/bluetooth_internals/bluetooth_internals.js index e251d4d..5904e8c 100644 --- a/chrome/browser/resources/bluetooth_internals/bluetooth_internals.js +++ b/chrome/browser/resources/bluetooth_internals/bluetooth_internals.js
@@ -8,7 +8,7 @@ */ import {assert} from 'chrome://resources/js/assert.js'; -import {$} from 'chrome://resources/js/util.js'; +import {$} from 'chrome://resources/js/util_ts.js'; import {DiscoverySessionRemote} from './adapter.mojom-webui.js'; import {AdapterBroker, AdapterProperty, getAdapterBroker} from './adapter_broker.js'; @@ -288,7 +288,10 @@ window.addEventListener('hashchange', function() { // If a user navigates and the page doesn't exist, do nothing. const pageName = window.location.hash.substr(1); - if ($(pageName)) { + // Device page names are invalid selectors for querySelector(), as they + // contain "/" and ":". + // eslint-disable-next-line no-restricted-properties + if (document.getElementById(pageName)) { pageManager.showPageByName(pageName); } });
diff --git a/chrome/browser/resources/bluetooth_internals/debug_log_page.js b/chrome/browser/resources/bluetooth_internals/debug_log_page.js index 1129141..3d1301e 100644 --- a/chrome/browser/resources/bluetooth_internals/debug_log_page.js +++ b/chrome/browser/resources/bluetooth_internals/debug_log_page.js
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import {$} from 'chrome://resources/js/util.js'; +import {$} from 'chrome://resources/js/util_ts.js'; import {BluetoothInternalsHandlerRemote, DebugLogsChangeHandlerRemote} from './bluetooth_internals.mojom-webui.js'; import {Page} from './page.js';
diff --git a/chrome/browser/resources/bluetooth_internals/device_details_page.js b/chrome/browser/resources/bluetooth_internals/device_details_page.js index abb8834..d12d06fd 100644 --- a/chrome/browser/resources/bluetooth_internals/device_details_page.js +++ b/chrome/browser/resources/bluetooth_internals/device_details_page.js
@@ -11,7 +11,7 @@ import './service_list.js'; import './object_fieldset.js'; -import {$} from 'chrome://resources/js/util.js'; +import {$} from 'chrome://resources/js/util_ts.js'; import {DeviceInfo, DeviceRemote, ServiceInfo} from './device.mojom-webui.js'; import {connectToDevice} from './device_broker.js';
diff --git a/chrome/browser/resources/bluetooth_internals/page.js b/chrome/browser/resources/bluetooth_internals/page.js index 1bc1add..8cd562a 100644 --- a/chrome/browser/resources/bluetooth_internals/page.js +++ b/chrome/browser/resources/bluetooth_internals/page.js
@@ -2,7 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import {getRequiredElement} from 'chrome://resources/js/util.js'; +import {assert} from 'chrome://resources/js/assert_ts.js'; + +function getRequiredElement(id) { + // Disable getElementById restriction here, because this UI uses non valid + // selectors that don't work with querySelector(). + // eslint-disable-next-line no-restricted-properties + const el = document.getElementById(id); + assert(el instanceof HTMLElement); + return el; +} /** * Finds a good place to set initial focus. Generally called when UI is shown.
diff --git a/chrome/browser/resources/bluetooth_internals/snackbar.js b/chrome/browser/resources/bluetooth_internals/snackbar.js index 6ec1a3a2..17fb61a 100644 --- a/chrome/browser/resources/bluetooth_internals/snackbar.js +++ b/chrome/browser/resources/bluetooth_internals/snackbar.js
@@ -4,7 +4,7 @@ import {assert} from 'chrome://resources/js/assert.js'; import {CustomElement} from 'chrome://resources/js/custom_element.js'; -import {ensureTransitionEndEvent, listenOnce} from 'chrome://resources/js/util.js'; +import {listenOnce} from 'chrome://resources/js/util_ts.js'; import {getTemplate} from './snackbar.html.js'; @@ -118,6 +118,25 @@ this.dispatchEvent( new CustomEvent('showed', {bubbles: true, composed: true})); } + /** + * transitionend does not always fire (e.g. when animation is aborted + * or when no paint happens during the animation). This function sets up + * a timer and emulate the event if it is not fired when the timer expires. + * @private + */ + ensureTransitionEndEvent_() { + let fired = false; + this.addEventListener('transitionend', function f(e) { + this.removeEventListener('transitionend', f); + fired = true; + }.bind(this)); + window.setTimeout(() => { + if (!fired) { + this.dispatchEvent(new CustomEvent('transitionend', + {bubbles: true, composed: true})); + } + }, TRANSITION_DURATION); + } /** * Dismisses the Snackbar. Once the Snackbar is completely hidden, the @@ -138,7 +157,7 @@ resolve(); }.bind(this)); - ensureTransitionEndEvent(this, TRANSITION_DURATION); + this.ensureTransitionEndEvent_(); this.classList.remove('open'); document.removeEventListener('contentfocus', this.boundStartTimeout_);
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/BUILD.gn b/chrome/browser/resources/chromeos/accessibility/chromevox/BUILD.gn index 280115d..cd1bb475 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/BUILD.gn +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/BUILD.gn
@@ -42,6 +42,7 @@ "../common/rect_util.js", "../common/string_util.js", "../common/tree_walker.js", + "background/abstract_tts.js", "background/automation_object_constructor_installer.js", "background/auto_scroll_handler.js", "background/background.js", @@ -115,7 +116,6 @@ "background/tts_background.js", "background/user_action_monitor.js", "common/abstract_earcons.js", - "common/abstract_tts.js", "common/background_bridge.js", "common/braille/braille_command_data.js", "common/braille/braille_key_types.js",
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/common/abstract_tts.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/abstract_tts.js similarity index 98% rename from chrome/browser/resources/chromeos/accessibility/chromevox/common/abstract_tts.js rename to chrome/browser/resources/chromeos/accessibility/chromevox/background/abstract_tts.js index 8e3fb438..90d1264 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/common/abstract_tts.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/abstract_tts.js
@@ -7,9 +7,9 @@ * text to speech. */ -import {Msgs} from './msgs.js'; -import {TtsInterface} from './tts_interface.js'; -import * as ttsTypes from './tts_types.js'; +import {Msgs} from '../common/msgs.js'; +import {TtsInterface} from '../common/tts_interface.js'; +import * as ttsTypes from '../common/tts_types.js'; /** * @typedef {{
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/download_handler.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/download_handler.js index d4cac0b4..7722caa 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/download_handler.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/download_handler.js
@@ -11,147 +11,101 @@ import {Output} from './output/output.js'; -export class DownloadHandler {} +// TODO: determine why Delta types are not in the externs for chrome.downloads. +// Pulled from +// https://developer.chrome.com/docs/extensions/reference/downloads/#type-DownloadDelta +/** @typedef {{current: (boolean|undefined), previous: (boolean|undefined)}} */ +let BoolDelta; +/** @typedef {{current: (string|undefined), previous: (string|undefined)}} */ +let StringDelta; +/** @typedef {{current: (number|undefined), previous: (number|undefined)}} */ +let DoubleDelta; /** - * Maps download item ID to an object containing its file name and progress - * update function. - * @private {Object<number, {fileName: string, - * notifyProgressId: number, - * time: number, - * percentComplete: number}>} + * @typedef {{ + * canResume: (BoolDelta|undefined), + * danger: (StringDelta|undefined), + * endTime: (StringDelta|undefined), + * error: (StringDelta|undefined), + * exists: (BoolDelta|undefined), + * fileSize: (DoubleDelta|undefined), + * filename: (StringDelta|undefined), + * finalUrl: (StringDelta|undefined), + * id: number, + * mime: (StringDelta|undefined), + * paused: (BoolDelta|undefined), + * startTime: (StringDelta|undefined), + * state: (StringDelta|undefined), + * totalBytes: (DoubleDelta|undefined), + * url: (StringDelta|undefined) + * }} */ -DownloadHandler.downloadItemData_ = {}; +let DownloadDelta; +const DownloadItem = chrome.downloads.DownloadItem; +const DownloadState = chrome.downloads.State; -/** - * Threshold value used when determining whether to report an update to user. - * @const {number} - * @private - */ -DownloadHandler.UPDATE_THRESHOLD_ = 100; +export class DownloadHandler { + /** @private */ + constructor() { + /** + * Maps download item ID to an object containing its file name and progress + * update function. + * @private {!Object<number, {fileName: string, + * notifyProgressId: number, + * time: number, + * percentComplete: number}>} + */ + this.downloadItemData_ = {}; + } -/** - * The limit for the number of results we receive when querying for downloads. - * @const {number} - * @private - */ -DownloadHandler.FILE_LIMIT_ = 20; + /** + * Performs initialization. Populates downloadItemData_ object and registers + * event listener for chrome.downloads.onChanged events. + */ + static init() { + DownloadHandler.instance_ = new DownloadHandler(); -/** - * The time interval, in milliseconds, for calling - * DownloadHandler.notifyProgress. - * @const {number} - * @private - */ -DownloadHandler.INTERVAL_TIME_MILLISECONDS_ = 10000; + // Populate downloadItemData_. + // Retrieve 20 most recent downloads sorted by most recent start time. + chrome.downloads.search( + {orderBy: ['-startTime'], limit: DownloadHandler.FILE_LIMIT_}, + results => + DownloadHandler.instance_.populateDownloadItemData_(results)); -/** - * Performs initialization. Populates downloadItemData_ object and registers - * event listener for chrome.downloads.onChanged events. - */ -DownloadHandler.init = function() { - // Populate downloadItemData_. - // Retrieve 20 most recent downloads sorted by most recent start time. - chrome.downloads.search( - {orderBy: ['-startTime'], limit: DownloadHandler.FILE_LIMIT_}, - function(results) { - if (!results || results.length === 0) { - return; - } + // Note: No event listener for chrome.downloads.onCreated because + // onCreated does not actually correspond to when the download starts; + // it corresponds to when the user clicks the download button, which + // sometimes leads to a screen where the user can decide where to save the + // download. - for (let i = 0; i < results.length; ++i) { - const item = results[i]; - const state = item.state; - if (!state) { - continue; - } - // If download is in progress, start tracking it. - if (state === chrome.downloads.State.IN_PROGRESS) { - DownloadHandler.startTrackingDownload(item); - } - } - }); + // Fired when any of a DownloadItem's properties, except bytesReceived and + // estimatedEndTime, change. Only contains properties that changed. + chrome.downloads.onChanged.addListener( + item => DownloadHandler.instance_.onChanged_( + /** @type {DownloadDelta} */ (item))); + } - // Note: No event listener for chrome.downloads.onCreated because - // onCreated does not actually correspond to when the download starts; - // it corresponds to when the user clicks the download button, which sometimes - // leads to a screen where the user can decide where to save the download. + /** + * Notifies user of download progress for file. + * @param {number} id The ID of the file we are providing an update for. + * @private + */ + notifyProgress_(id) { + chrome.downloads.search( + {id}, results => this.notifyProgressResults_(results)); + } - // Fired when any of a DownloadItem's properties, except bytesReceived and - // estimatedEndTime, change. Only contains properties that changed. - chrome.downloads.onChanged.addListener(function(item) { - // The type of notification ChromeVox reports can be inferred based on the - // available properties, as they have been observed to be mutually - // exclusive. - const name = item.filename; - const state = item.state; - const paused = item.paused; - // The item ID is always set no matter what. - const id = item.id; - - const storedItem = DownloadHandler.downloadItemData_[id]; - - // New download if we're not tracking the item and if the filename was - // previously empty. - if (!storedItem && name && (name.previous === '')) { - DownloadHandler.startTrackingDownload( - /** @type {!chrome.downloads.DownloadItem} */ (item)); - - // Speech and braille output. - const optSubs = [DownloadHandler.downloadItemData_[id].fileName]; - DownloadHandler.speechAndBrailleOutput( - 'download_started', QueueMode.FLUSH, optSubs); - } else if (state) { - const currentState = state.current; - let msgId = ''; - // Only give notification for COMPLETE and INTERRUPTED. - // IN_PROGRESS notifications are given by notifyProgress function. - if (currentState === chrome.downloads.State.COMPLETE) { - msgId = 'download_completed'; - } else if (currentState === chrome.downloads.State.INTERRUPTED) { - msgId = 'download_stopped'; - } else { - return; - } - - const optSubs = [storedItem.fileName]; - clearInterval(storedItem.notifyProgressId); - delete DownloadHandler.downloadItemData_[id]; - // Speech and braille output. - DownloadHandler.speechAndBrailleOutput(msgId, QueueMode.FLUSH, optSubs); - } else if (paused) { - // Will be either resumed or paused. - let msgId = 'download_resumed'; - const optSubs = [storedItem.fileName]; - if (paused.current === true) { - // Download paused. - msgId = 'download_paused'; - clearInterval(storedItem.notifyProgressId); - } else { - // Download resumed. - storedItem.notifyProgressId = setInterval( - DownloadHandler.notifyProgress.bind(DownloadHandler, item.id), - 10000); - storedItem.time = Date.now(); - } - // Speech and braille output. - DownloadHandler.speechAndBrailleOutput(msgId, QueueMode.FLUSH, optSubs); - } - }); -}; - -/** - * Notifies user of download progress for file. - * @param {number} id The ID of the file we are providing an update for. - */ -DownloadHandler.notifyProgress = function(id) { - chrome.downloads.search({id}, function(results) { + /** + * @param {!Array<!DownloadItem>} results + * @private + */ + notifyProgressResults_(results) { if (!results || (results.length !== 1)) { return; } // Results should have only one item because IDs are unique. const updatedItem = results[0]; - const storedItem = DownloadHandler.downloadItemData_[updatedItem.id]; + const storedItem = this.downloadItemData_[updatedItem.id]; const percentComplete = Math.round((updatedItem.bytesReceived / updatedItem.totalBytes) * 100); @@ -207,47 +161,159 @@ timeRemaining, timeUnit, ]; - DownloadHandler.speechAndBrailleOutput( + this.speechAndBrailleOutput_( 'download_progress', QueueMode.FLUSH, optSubs); } - }); -}; + } + + /** + * @param {!DownloadDelta} delta + * @private + */ + onChanged_(delta) { + // The type of notification ChromeVox reports can be inferred based on the + // available properties, as they have been observed to be mutually + // exclusive. + const name = delta.filename; + const state = delta.state; + const paused = delta.paused; + // The ID is always set no matter what. + const id = delta.id; + + const storedItem = this.downloadItemData_[id]; + + // New download if we're not tracking the item and if the filename was + // previously empty. + if (!storedItem && name && (name.previous === '')) { + this.startTrackingDownload_(delta); + + // Speech and braille output. + const optSub = this.downloadItemData_[id].fileName; + this.speechAndBrailleOutput_( + 'download_started', QueueMode.FLUSH, [optSub]); + } else if (state) { + const currentState = state.current; + let msgId = ''; + // Only give notification for COMPLETE and INTERRUPTED. + // IN_PROGRESS notifications are given by notifyProgress function. + if (currentState === DownloadState.COMPLETE) { + msgId = 'download_completed'; + } else if (currentState === DownloadState.INTERRUPTED) { + msgId = 'download_stopped'; + } else { + return; + } + + const optSubs = [storedItem.fileName]; + clearInterval(storedItem.notifyProgressId); + delete this.downloadItemData_[id]; + // Speech and braille output. + this.speechAndBrailleOutput_(msgId, QueueMode.FLUSH, optSubs); + } else if (paused) { + // Will be either resumed or paused. + let msgId = 'download_resumed'; + const optSubs = [storedItem.fileName]; + if (paused.current === true) { + // Download paused. + msgId = 'download_paused'; + clearInterval(storedItem.notifyProgressId); + } else { + // Download resumed. + storedItem.notifyProgressId = setInterval( + () => this.notifyProgress_(id), + DownloadHandler.INTERVAL_TIME_MILLISECONDS_); + storedItem.time = Date.now(); + } + // Speech and braille output. + this.speechAndBrailleOutput_(msgId, QueueMode.FLUSH, optSubs); + } + } + + /** + * @param {!Array<!DownloadItem>} results + * @private + */ + populateDownloadItemData_(results) { + if (!results || results.length === 0) { + return; + } + + for (let i = 0; i < results.length; ++i) { + const item = results[i]; + const state = item.state; + if (!state) { + continue; + } + // If download is in progress, start tracking it. + if (state === DownloadState.IN_PROGRESS) { + this.startTrackingDownload_(item); + } + } + } + + /** + * Output download notification as speech and braille. + * @param{string} msgId The msgId for Output. + * @param{QueueMode} queueMode The queue mode. + * @param{Array<string>} optSubs Substitution strings. + * @private + */ + speechAndBrailleOutput_(msgId, queueMode, optSubs) { + if (localStorage['announceDownloadNotifications'] === 'true') { + const msg = Msgs.getMsg(msgId, optSubs); + new Output().withString(msg).withQueueMode(queueMode).go(); + } + } + + + /** + * Store item data. + * @param {!DownloadItem|!DownloadDelta} item The download item to track. + * @private + */ + startTrackingDownload_(item) { + const id = item.id; + // Don't add if we are already tracking file. + if (this.downloadItemData_[id]) { + return; + } + + const fullPath = (item.filename.current || item.filename); + const fileName = fullPath.substring(fullPath.lastIndexOf('/') + 1); + const notifyProgressId = setInterval( + () => this.notifyProgress_(id), + DownloadHandler.INTERVAL_TIME_MILLISECONDS_); + let percentComplete = 0; + if (item.bytesReceived && item.totalBytes) { + percentComplete = + Math.round((item.bytesReceived / item.totalBytes) * 100); + } + + this.downloadItemData_[id] = + {fileName, notifyProgressId, time: Date.now(), percentComplete}; + } +} /** - * Store item data. - * @param{!chrome.downloads.DownloadItem} item The download item we want to - * track. + * Threshold value used when determining whether to report an update to user. + * @const {number} + * @private */ -DownloadHandler.startTrackingDownload = function(item) { - const id = item.id; - // Don't add if we are already tracking file. - if (DownloadHandler.downloadItemData_[id]) { - return; - } - - const fullPath = (item.filename.current || item.filename); - const fileName = fullPath.substring(fullPath.lastIndexOf('/') + 1); - const notifyProgressId = setInterval( - DownloadHandler.notifyProgress.bind(DownloadHandler, id), - DownloadHandler.INTERVAL_TIME_MILLISECONDS_); - let percentComplete = 0; - if (item.bytesReceived && item.totalBytes) { - percentComplete = Math.round((item.bytesReceived / item.totalBytes) * 100); - } - - DownloadHandler.downloadItemData_[id] = - {fileName, notifyProgressId, time: Date.now(), percentComplete}; -}; +DownloadHandler.UPDATE_THRESHOLD_ = 100; /** - * Output download notification as speech and braille. - * @param{string} msgId The msgId for Output. - * @param{QueueMode} queueMode The queue mode. - * @param{Array<string>} optSubs Substitution strings. + * The limit for the number of results we receive when querying for downloads. + * @const {number} + * @private */ -DownloadHandler.speechAndBrailleOutput = function(msgId, queueMode, optSubs) { - if (localStorage['announceDownloadNotifications'] === 'true') { - const msg = Msgs.getMsg(msgId, optSubs); - new Output().withString(msg).withQueueMode(queueMode).go(); - } -}; +DownloadHandler.FILE_LIMIT_ = 20; + +/** + * The time interval, in milliseconds, for calling notifyProgress. + * @const {number} + * @private + */ +DownloadHandler.INTERVAL_TIME_MILLISECONDS_ = 10000; + +/** @private {DownloadHandler} */ +DownloadHandler.instance_;
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/output/output.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/output/output.js index 9e4f037..c1d0ac3 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/output/output.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/output/output.js
@@ -11,6 +11,7 @@ import {Cursor, CURSOR_NODE_INDEX} from '../../../common/cursors/cursor.js'; import {CursorRange} from '../../../common/cursors/range.js'; import {AutomationTreeWalker} from '../../../common/tree_walker.js'; +import {Earcon} from '../../common/abstract_earcons.js'; import {NavBraille} from '../../common/braille/nav_braille.js'; import {EventSourceType} from '../../common/event_source_type.js'; import {LocaleOutputHelper} from '../../common/locale_output_helper.js'; @@ -670,25 +671,6 @@ } /** @override */ - formatJoinedDescendants_(data, token, options) { - const buff = data.outputBuffer; - const node = data.node; - const formatLog = data.outputFormatLogger; - - const unjoined = []; - formatLog.write('joinedDescendants {'); - this.format_({ - node, - outputFormat: '$descendants', - outputBuffer: unjoined, - outputFormatLogger: formatLog, - }); - this.append_(buff, unjoined.join(' '), options); - formatLog.write( - '}: ' + (unjoined.length ? unjoined.join(' ') : 'EMPTY') + '\n'); - } - - /** @override */ formatRole_(data, token, options) { const buff = data.outputBuffer; const node = data.node; @@ -903,9 +885,9 @@ if (!resolvedInfo) { return; } - if (this.formatOptions_.speech && resolvedInfo.earconId) { + if (this.formatOptions_.speech && resolvedInfo.earcon) { options.annotation.push( - new outputTypes.OutputEarconAction(resolvedInfo.earconId), + new outputTypes.OutputEarconAction(resolvedInfo.earcon), node.location || undefined); } const msgId = this.formatOptions_.braille ? resolvedInfo.msgId + '_brl' : @@ -1015,7 +997,7 @@ } options.annotation.push(new outputTypes.OutputEarconAction( - tree.firstChild.value, node.location || undefined)); + Earcon[tree.firstChild.value], node.location || undefined)); this.append_(buff, '', options); formatLog.writeTokenWithValue(token, tree.firstChild.value); } @@ -1958,9 +1940,9 @@ while (earconFinder = ancestors.pop()) { const info = OutputRoleInfo[earconFinder.role]; - if (info && info.earconId) { + if (info && info.earcon) { return new outputTypes.OutputEarconAction( - info.earconId, node.location || undefined); + info.earcon, node.location || undefined); break; } earconFinder = earconFinder.parent;
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/output/output_formatter.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/output/output_formatter.js index 4bfe306..d3daa0c 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/output/output_formatter.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/output/output_formatter.js
@@ -78,7 +78,7 @@ } else if (token === 'descendants') { this.formatDescendants_(this.params_, token); } else if (token === 'joinedDescendants') { - this.output_.formatJoinedDescendants_(this.params_, token, options); + this.formatJoinedDescendants_(this.params_, token, options); } else if (token === 'role') { if (localStorage['useVerboseMode'] === String(false)) { return true; @@ -340,6 +340,30 @@ * @param {!outputTypes.OutputFormattingData} data * @param {string} token * @param {!{annotation: Array<*>, isUnique: (boolean|undefined)}} options + * @private + */ + formatJoinedDescendants_(data, token, options) { + const buff = data.outputBuffer; + const node = data.node; + const formatLog = data.outputFormatLogger; + + const unjoined = []; + formatLog.write('joinedDescendants {'); + this.output_.format_({ + node, + outputFormat: '$descendants', + outputBuffer: unjoined, + outputFormatLogger: formatLog, + }); + this.output_.append_(buff, unjoined.join(' '), options); + formatLog.write( + '}: ' + (unjoined.length ? unjoined.join(' ') : 'EMPTY') + '\n'); + } + + /** + * @param {!outputTypes.OutputFormattingData} data + * @param {string} token + * @param {!{annotation: Array<*>, isUnique: (boolean|undefined)}} options */ formatName_(data, token, options) { const buff = data.outputBuffer;
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/output/output_interface.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/output/output_interface.js index c3db5ab..6b0b92f3 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/output/output_interface.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/output/output_interface.js
@@ -86,13 +86,6 @@ /** * @param {!outputTypes.OutputFormattingData} data - * @param {string} token - * @param {!{annotation: Array<*>, isUnique: (boolean|undefined)}} options - */ - formatJoinedDescendants_(data, token, options) {} - - /** - * @param {!outputTypes.OutputFormattingData} data */ formatListNestedLevel_(data) {}
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/output/output_role_info.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/output/output_role_info.js index 90b95a6b..a42024ccf 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/output/output_role_info.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/output/output_role_info.js
@@ -6,6 +6,7 @@ * @fileoverview Roel information for the Output module. */ +import {Earcon} from '../../common/abstract_earcons.js'; import {AbstractRole, ChromeVoxRole} from '../../common/role_type.js'; import {OutputContextOrder} from './output_types.js'; @@ -15,14 +16,14 @@ /** * Metadata about supported automation roles. * @const {Object<{msgId: string, - * earconId: (string|undefined), + * earcon: (!Earcon|undefined), * inherits: (ChromeVoxRole|undefined), * verboseAncestry: (boolean|undefined), * contextOrder: (OutputContextOrder|undefined), * ignoreAncestry: (boolean|undefined)}>} * msgId: the message id of the role. Each role used requires a speech entry in * chromevox_strings.grd + an optional Braille entry (with _BRL suffix). - * earconId: an optional earcon to play when encountering the role. + * earcon: an optional earcon to play when encountering the role. * inherits: inherits rules from this role. * contextOrder: where to place the context output. * ignoreAncestry: ignores ancestry (context) output for this role. @@ -38,16 +39,16 @@ application: {msgId: 'role_application', inherits: AbstractRole.CONTAINER}, audio: {msgId: 'tag_audio', inherits: AbstractRole.FORM_FIELD_CONTAINER}, banner: {msgId: 'role_banner', inherits: AbstractRole.CONTAINER}, - button: {msgId: 'role_button', earconId: 'BUTTON'}, - buttonDropDown: {msgId: 'role_button', earconId: 'BUTTON'}, + button: {msgId: 'role_button', earcon: Earcon.BUTTON}, + buttonDropDown: {msgId: 'role_button', earcon: Earcon.BUTTON}, checkBox: {msgId: 'role_checkbox'}, columnHeader: {msgId: 'role_columnheader', inherits: RoleType.CELL}, - comboBoxMenuButton: {msgId: 'role_combobox', earconId: 'LISTBOX'}, + comboBoxMenuButton: {msgId: 'role_combobox', earcon: Earcon.LISTBOX}, comboBoxGrouping: {msgId: 'role_combobox', inherits: AbstractRole.FORM_FIELD_CONTAINER}, comboBoxSelect: { msgId: 'role_button', - earconId: 'POP_UP_BUTTON', + earcon: Earcon.POP_UP_BUTTON, inherits: RoleType.COMBO_BOX_MENU_BUTTON, }, complementary: @@ -88,17 +89,23 @@ {msgId: 'role_doc_acknowledgments', inherits: AbstractRole.SPAN}, docAfterword: {msgId: 'role_doc_afterword', inherits: AbstractRole.CONTAINER}, docAppendix: {msgId: 'role_doc_appendix', inherits: AbstractRole.SPAN}, - docBackLink: - {msgId: 'role_doc_back_link', earconId: 'LINK', inherits: RoleType.LINK}, + docBackLink: { + msgId: 'role_doc_back_link', + earcon: Earcon.LINK, + inherits: RoleType.LINK, + }, docBiblioEntry: { msgId: 'role_doc_biblio_entry', - earconId: 'LIST_ITEM', + earcon: Earcon.LIST_ITEM, inherits: AbstractRole.ITEM, }, docBibliography: {msgId: 'role_doc_bibliography', inherits: AbstractRole.SPAN}, - docBiblioRef: - {msgId: 'role_doc_biblio_ref', earconId: 'LINK', inherits: RoleType.LINK}, + docBiblioRef: { + msgId: 'role_doc_biblio_ref', + earcon: Earcon.LINK, + inherits: RoleType.LINK, + }, docChapter: {msgId: 'role_doc_chapter', inherits: AbstractRole.SPAN}, docColophon: {msgId: 'role_doc_colophon', inherits: AbstractRole.SPAN}, docConclusion: {msgId: 'role_doc_conclusion', inherits: AbstractRole.SPAN}, @@ -108,12 +115,12 @@ docDedication: {msgId: 'role_doc_dedication', inherits: AbstractRole.SPAN}, docEndnote: { msgId: 'role_doc_endnote', - earconId: 'LIST_ITEM', + earcon: Earcon.LIST_ITEM, inherits: AbstractRole.ITEM, }, docEndnotes: { msgId: 'role_doc_endnotes', - earconId: 'LISTBOX', + earcon: Earcon.LISTBOX, inherits: RoleType.LIST, }, docEpigraph: {msgId: 'role_doc_epigraph', inherits: AbstractRole.SPAN}, @@ -122,18 +129,24 @@ docExample: {msgId: 'role_doc_example', inherits: AbstractRole.SPAN}, docFootnote: { msgId: 'role_doc_footnote', - earconId: 'LIST_ITEM', + earcon: Earcon.LIST_ITEM, inherits: AbstractRole.ITEM, }, docForeword: {msgId: 'role_doc_foreword', inherits: AbstractRole.SPAN}, docGlossary: {msgId: 'role_doc_glossary', inherits: AbstractRole.SPAN}, - docGlossRef: - {msgId: 'role_doc_gloss_ref', earconId: 'LINK', inherits: RoleType.LINK}, + docGlossRef: { + msgId: 'role_doc_gloss_ref', + earcon: Earcon.LINK, + inherits: RoleType.LINK, + }, docIndex: {msgId: 'role_doc_index', inherits: AbstractRole.SPAN}, docIntroduction: {msgId: 'role_doc_introduction', inherits: AbstractRole.SPAN}, - docNoteRef: - {msgId: 'role_doc_note_ref', earconId: 'LINK', inherits: RoleType.LINK}, + docNoteRef: { + msgId: 'role_doc_note_ref', + earcon: Earcon.LINK, + inherits: RoleType.LINK, + }, docNotice: {msgId: 'role_doc_notice', inherits: AbstractRole.SPAN}, docPageBreak: {msgId: 'role_doc_page_break', inherits: AbstractRole.SPAN}, docPageFooter: {msgId: 'role_doc_page_footer', inherits: AbstractRole.SPAN}, @@ -165,14 +178,14 @@ imeCandidate: {msgId: 'ime_candidate', ignoreAncestry: true}, inputTime: {msgId: 'input_type_time', inherits: AbstractRole.FORM_FIELD_CONTAINER}, - link: {msgId: 'role_link', earconId: 'LINK'}, + link: {msgId: 'role_link', earcon: Earcon.LINK}, list: {msgId: 'role_list', inherits: AbstractRole.LIST}, - listBox: {msgId: 'role_listbox', earconId: 'LISTBOX'}, - listBoxOption: {msgId: 'role_listitem', earconId: 'LIST_ITEM'}, + listBox: {msgId: 'role_listbox', earcon: Earcon.LISTBOX}, + listBoxOption: {msgId: 'role_listitem', earcon: Earcon.LIST_ITEM}, listGrid: {msgId: 'role_list_grid', inherits: RoleType.TABLE}, listItem: { msgId: 'role_listitem', - earconId: 'LIST_ITEM', + earcon: Earcon.LIST_ITEM, inherits: AbstractRole.ITEM, }, log: {msgId: 'role_log', inherits: AbstractRole.NAME_FROM_CONTENTS}, @@ -205,7 +218,7 @@ {msgId: 'role_progress_indicator', inherits: AbstractRole.RANGE}, popUpButton: { msgId: 'role_button', - earconId: 'POP_UP_BUTTON', + earcon: Earcon.POP_UP_BUTTON, inherits: RoleType.COMBO_BOX_MENU_BUTTON, }, radioButton: {msgId: 'role_radio'}, @@ -218,12 +231,15 @@ section: {msgId: 'role_region', inherits: AbstractRole.CONTAINER}, search: {msgId: 'role_search', inherits: AbstractRole.CONTAINER}, separator: {msgId: 'role_separator', inherits: AbstractRole.CONTAINER}, - slider: - {msgId: 'role_slider', inherits: AbstractRole.RANGE, earconId: 'SLIDER'}, + slider: { + msgId: 'role_slider', + inherits: AbstractRole.RANGE, + earcon: Earcon.SLIDER, + }, spinButton: { msgId: 'role_spinbutton', inherits: AbstractRole.RANGE, - earconId: 'LISTBOX', + earcon: Earcon.LISTBOX, }, splitter: {msgId: 'role_separator', inherits: AbstractRole.SPAN}, status: {msgId: 'role_status', inherits: AbstractRole.NAME_FROM_CONTENTS}, @@ -238,9 +254,9 @@ tab: {msgId: 'role_tab', inherits: AbstractRole.CONTAINER}, tabList: {msgId: 'role_tablist', inherits: AbstractRole.FORM_FIELD_CONTAINER}, tabPanel: {msgId: 'role_tabpanel', inherits: AbstractRole.CONTAINER}, - searchBox: {msgId: 'role_search', earconId: 'EDITABLE_TEXT'}, - textField: {msgId: 'input_type_text', earconId: 'EDITABLE_TEXT'}, - textFieldWithComboBox: {msgId: 'role_combobox', earconId: 'EDITABLE_TEXT'}, + searchBox: {msgId: 'role_search', earcon: Earcon.EDITABLE_TEXT}, + textField: {msgId: 'input_type_text', earcon: Earcon.EDITABLE_TEXT}, + textFieldWithComboBox: {msgId: 'role_combobox', earcon: Earcon.EDITABLE_TEXT}, time: {msgId: 'tag_time', inherits: AbstractRole.FORM_FIELD_CONTAINER}, timer: {msgId: 'role_timer', inherits: AbstractRole.NAME_FROM_CONTENTS}, toolbar: {msgId: 'role_toolbar', ignoreAncestry: true},
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/output/output_rules.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/output/output_rules.js index 2c95a508..cfd3f9de 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/output/output_rules.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/output/output_rules.js
@@ -243,7 +243,7 @@ $value $state $role $description`, }, [RoleType.IME_CANDIDATE]: - {speak: '$name $phoneticReading @describe_index($posInSet, $setSize)'}, + {speak: `$name $phoneticReading @describe_index($posInSet, $setSize)`}, [RoleType.INLINE_TEXT_BOX]: {speak: `$precedingBullet $name=`}, [RoleType.INPUT_TIME]: {enter: `$nameFromNode $role $state $restriction $description`},
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/output/output_test.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/output/output_test.js index 4e4a0f3..34a0ad2 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/output/output_test.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/output/output_test.js
@@ -111,6 +111,7 @@ await importModule( ['OutputEarconAction', 'OutputNodeSpan', 'OutputSelectionSpan'], '/chromevox/background/output/output_types.js'); + await importModule('Earcon', '/chromevox/common/abstract_earcons.js'); await importModule( 'EventSourceType', '/chromevox/common/event_source_type.js'); await importModule('Msgs', '/chromevox/common/msgs.js'); @@ -140,7 +141,7 @@ {value: 'name', start: 0, end: 10}, // Link earcon (based on the name). - {value: {earconId: 'LINK'}, start: 0, end: 10}, + {value: {earcon: Earcon.LINK}, start: 0, end: 10}, {value: {'delay': true}, start: 25, end: 55}, ], @@ -159,7 +160,7 @@ checkSpeechOutput( '|Check box|Not checked|Press Search+Space to toggle', [ - {value: new OutputEarconAction('CHECK_OFF'), start: 0, end: 0}, + {value: new OutputEarconAction(Earcon.CHECK_OFF), start: 0, end: 0}, {value: 'role', start: 1, end: 10}, {value: {'delay': true}, start: 23, end: 51}, ], @@ -236,7 +237,7 @@ string_: 'b|Link|Heading 1', 'spans_': [ {value: 'name', start: 0, end: 1}, - {value: new OutputEarconAction('LINK'), start: 0, end: 1}, + {value: new OutputEarconAction(Earcon.LINK), start: 0, end: 1}, {value: 'role', start: 2, end: 6}, ], }, @@ -263,7 +264,7 @@ checkSpeechOutput( 'play|Disabled|Button|audio|Tool bar', [ - {value: new OutputEarconAction('BUTTON'), start: 0, end: 4}, + {value: new OutputEarconAction(Earcon.BUTTON), start: 0, end: 4}, {value: 'name', start: 21, end: 26}, {value: 'role', start: 27, end: 35}, ], @@ -287,7 +288,7 @@ '|audio time scrubber|Slider|0:00|Min 0|Max 0', [ {value: 'name', start: 0, end: 0}, - {value: new OutputEarconAction('SLIDER'), start: 0, end: 0}, + {value: new OutputEarconAction(Earcon.SLIDER), start: 0, end: 0}, {value: 'description', start: 1, end: 20}, {value: 'role', start: 21, end: 27}, {value: 'value', start: 28, end: 32}, @@ -312,14 +313,14 @@ '<input type="invalidType"</input>'); const expectedSpansNonSearchBox = [ {value: 'name', start: 0, end: 0}, - {value: new OutputEarconAction('EDITABLE_TEXT'), start: 0, end: 0}, + {value: new OutputEarconAction(Earcon.EDITABLE_TEXT), start: 0, end: 0}, {value: new OutputSelectionSpan(0, 0, 0), start: 1, end: 1}, {value: 'value', start: 1, end: 1}, {value: 'inputType', start: 2}, ]; const expectedSpansForSearchBox = [ {value: 'name', start: 0, end: 0}, - {value: new OutputEarconAction('EDITABLE_TEXT'), start: 0, end: 0}, + {value: new OutputEarconAction(Earcon.EDITABLE_TEXT), start: 0, end: 0}, {value: new OutputSelectionSpan(0, 0, 0), start: 1, end: 1}, {value: 'value', start: 1, end: 1}, {value: 'role', start: 2, end: 8}, @@ -334,7 +335,7 @@ '|Spin button', [ {value: 'name', start: 0, end: 0}, - {value: new OutputEarconAction('LISTBOX'), start: 0, end: 0}, + {value: new OutputEarconAction(Earcon.LISTBOX), start: 0, end: 0}, {value: 'role', start: 1, end: 12}, ], ], @@ -344,7 +345,7 @@ 'No file chosen, Choose File|Button', [ {value: 'name', start: 0, end: 27}, - {value: new OutputEarconAction('BUTTON'), start: 0, end: 27}, + {value: new OutputEarconAction(Earcon.BUTTON), start: 0, end: 27}, {value: 'role', start: 28, end: 34}, ], ], @@ -426,7 +427,7 @@ checkSpeechOutput( 'a|List item|first|List|with 3 items', [ - {value: {earconId: 'LIST_ITEM'}, start: 0, end: 1}, + {value: {earcon: Earcon.LIST_ITEM}, start: 0, end: 1}, {value: 'name', start: 12, end: 17}, {value: 'role', start: 18, end: 22}, ], @@ -574,7 +575,7 @@ '1|List item| 1 of 2 |Not selected|List box|with 2 items', [ {value: 'name', start: 0, end: 1}, - {value: new OutputEarconAction('LIST_ITEM'), start: 0, end: 1}, + {value: new OutputEarconAction(Earcon.LIST_ITEM), start: 0, end: 1}, {value: 'role', start: 34, end: 42}, ], o); @@ -647,9 +648,6 @@ } assertFalse(/[A-Z]+/.test(value.msgId)); } - if (value.earconId) { - assertNotNullNorUndefined(Earcon[value.earconId]); - } } for (const key in Output.STATE_INFO_) { const value = Output.STATE_INFO_[key]; @@ -662,9 +660,6 @@ Msgs.getMsg(innerValue.msgId); Msgs.getMsg(innerValue.msgId + '_brl'); assertFalse(/[A-Z]+/.test(innerValue.msgId)); - if (innerValue.earconId) { - assertNotNullNorUndefined(Earcon[innerValue.earconId]); - } } } for (const key in Output.INPUT_TYPE_MESSAGE_IDS_) { @@ -770,7 +765,7 @@ string_: '|Subscribe|Toggle Button|Pressed|Press Search+Space to toggle', spans_: [ - {value: {earconId: 'CHECK_ON'}, start: 0, end: 0}, + {value: {earcon: Earcon.CHECK_ON}, start: 0, end: 0}, {value: 'name', start: 1, end: 10}, {value: 'role', start: 11, end: 24}, {value: {'delay': true}, start: 33, end: 61}, @@ -891,7 +886,7 @@ 'volume|Slider|2|Min 1|Max 10', [ {value: 'name', start: 0, end: 6}, - {value: new OutputEarconAction('SLIDER'), start: 0, end: 6}, + {value: new OutputEarconAction(Earcon.SLIDER), start: 0, end: 6}, {value: 'role', start: 7, end: 13}, {value: 'value', start: 14, end: 15}, ], @@ -925,7 +920,7 @@ 'volume|Spin button|2|Min 1|Max 10', [ {value: 'name', start: 0, end: 6}, - {value: new OutputEarconAction('LISTBOX'), start: 0, end: 6}, + {value: new OutputEarconAction(Earcon.LISTBOX), start: 0, end: 6}, {value: 'role', start: 7, end: 18}, {value: 'value', start: 19, end: 20}, ], @@ -942,7 +937,7 @@ 'hi|foo', [ {value: 'name', start: 0, end: 2}, - {value: new OutputEarconAction('BUTTON'), start: 0, end: 2}, + {value: new OutputEarconAction(Earcon.BUTTON), start: 0, end: 2}, {value: 'role', start: 3, end: 6}, ], o); @@ -1513,7 +1508,7 @@ checkSpeechOutput( '|Check box|checked state description', [ - {value: new OutputEarconAction('CHECK_OFF'), start: 0, end: 0}, + {value: new OutputEarconAction(Earcon.CHECK_OFF), start: 0, end: 0}, {value: 'role', start: 1, end: 10}, {value: 'checkedStateDescription', start: 11, end: 36}, ],
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/output/output_types.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/output/output_types.js index 2d474a70..0ab4957 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/output/output_types.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/output/output_types.js
@@ -73,26 +73,26 @@ */ export class OutputEarconAction extends OutputAction { /** - * @param {string} earconId + * @param {!Earcon} earcon * @param {chrome.automation.Rect=} opt_location */ - constructor(earconId, opt_location) { + constructor(earcon, opt_location) { super(); - /** @type {string} */ - this.earconId = earconId; + /** @type {!Earcon} */ + this.earcon = earcon; /** @type {chrome.automation.Rect|undefined} */ this.location = opt_location; } /** @override */ run() { - ChromeVox.earcons.playEarcon(Earcon[this.earconId], this.location); + ChromeVox.earcons.playEarcon(this.earcon, this.location); } /** @override */ toJSON() { - return {earconId: this.earconId}; + return {earcon: this.earcon}; } } @@ -169,8 +169,8 @@ /** * Metadata about supported automation states. - * @const {!Object<string, {on: {msgId: string, earconId: string}, - * off: {msgId: string, earconId: string}, + * @const {!Object<string, {on: {msgId: string, earcon: !Earcon}, + * off: {msgId: string, earcon: !Earcon}, * isRoleSpecific: (boolean|undefined)}>} * on: info used to describe a state that is set to true. * off: info used to describe a state that is set to undefined.
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/tts_background.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/tts_background.js index 78bb406..fe8c92e1 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/tts_background.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/tts_background.js
@@ -8,7 +8,6 @@ */ import {constants} from '../../common/constants.js'; -import {AbstractTts} from '../common/abstract_tts.js'; import {BridgeConstants} from '../common/bridge_constants.js'; import {BridgeHelper} from '../common/bridge_helper.js'; import {CompositeTts} from '../common/composite_tts.js'; @@ -17,6 +16,7 @@ import {TtsCapturingEventListener, TtsInterface} from '../common/tts_interface.js'; import * as ttsTypes from '../common/tts_types.js'; +import {AbstractTts} from './abstract_tts.js'; import {ChromeVox} from './chromevox.js'; import {ConsoleTts} from './console_tts.js'; import {PhoneticData} from './phonetic_data.js';
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/panel/panel.js b/chrome/browser/resources/chromeos/accessibility/chromevox/panel/panel.js index 40e09c86..9dae1f2 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/panel/panel.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/panel/panel.js
@@ -1166,10 +1166,12 @@ BackgroundBridge.CommandHandler.onCommand(Command.FULLY_DESCRIBE); }); $('chromevox-tutorial').addEventListener('requestearcon', evt => { + evt = /** @type {{detail: {earconId: string}}} */ (evt); const earconId = evt.detail.earconId; backgroundPage['ChromeVox']['earcons']['playEarcon'](earconId); }); $('chromevox-tutorial').addEventListener('cancelearcon', evt => { + evt = /** @type {{detail: {earconId: string}}} */ (evt); const earconId = evt.detail.earconId; backgroundPage['ChromeVox']['earcons']['cancelEarcon'](earconId); });
diff --git a/chrome/browser/resources/device_log_ui/device_log_ui.js b/chrome/browser/resources/device_log_ui/device_log_ui.js index 8335e5f..2f1055d 100644 --- a/chrome/browser/resources/device_log_ui/device_log_ui.js +++ b/chrome/browser/resources/device_log_ui/device_log_ui.js
@@ -6,7 +6,7 @@ import {sendWithPromise} from 'chrome://resources/js/cr.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; -import {$} from 'chrome://resources/js/util.js'; +import {$} from 'chrome://resources/js/util_ts.js'; // List of log levels in priority order. const logLevels = ['Debug', 'Event', 'User', 'Error'];
diff --git a/chrome/browser/resources/family_link_user_internals/family_link_user_internals.js b/chrome/browser/resources/family_link_user_internals/family_link_user_internals.js index 864bfd2..10079b3 100644 --- a/chrome/browser/resources/family_link_user_internals/family_link_user_internals.js +++ b/chrome/browser/resources/family_link_user_internals/family_link_user_internals.js
@@ -5,7 +5,7 @@ import 'chrome://resources/js/jstemplate_compiled.js'; import {addWebUiListener, sendWithPromise} from 'chrome://resources/js/cr.js'; -import {$} from 'chrome://resources/js/util.js'; +import {$} from 'chrome://resources/js/util_ts.js'; function initialize() { function submitURL(event) {
diff --git a/chrome/browser/resources/gaia_auth_host/authenticator.js b/chrome/browser/resources/gaia_auth_host/authenticator.js index 78e03ad..fbd3438 100644 --- a/chrome/browser/resources/gaia_auth_host/authenticator.js +++ b/chrome/browser/resources/gaia_auth_host/authenticator.js
@@ -5,13 +5,14 @@ import {assert} from 'chrome://resources/js/assert.js'; // <if expr="not chromeos_ash"> import {sendWithPromise} from 'chrome://resources/js/cr.js'; +import {$, appendParam} from 'chrome://resources/js/util_ts.js'; // </if> // <if expr="chromeos_ash"> import {sendWithPromise} from 'chrome://resources/js/cr.m.js'; import {NativeEventTarget as EventTarget} from 'chrome://resources/js/cr/event_target.js'; +import {$, appendParam} from 'chrome://resources/js/util.js'; // </if> -import {$, appendParam} from 'chrome://resources/js/util.js'; import {OnHeadersReceivedDetails, SamlHandler} from './saml_handler.js'; import {PasswordAttributes} from './saml_password_attributes.js';
diff --git a/chrome/browser/resources/gaia_auth_host/password_change_authenticator.js b/chrome/browser/resources/gaia_auth_host/password_change_authenticator.js index 6722e6e..221607e 100644 --- a/chrome/browser/resources/gaia_auth_host/password_change_authenticator.js +++ b/chrome/browser/resources/gaia_auth_host/password_change_authenticator.js
@@ -9,8 +9,11 @@ import {assert} from 'chrome://resources/js/assert.js'; // <if expr="chromeos_ash"> import {NativeEventTarget as EventTarget} from 'chrome://resources/js/cr/event_target.js'; -// </if> import {$, appendParam} from 'chrome://resources/js/util.js'; +// </if> +// <if expr="not chromeos_ash"> +import {$, appendParam} from 'chrome://resources/js/util_ts.js'; +// </if> import {SamlHandler} from './saml_handler.js'; import {WebviewEventManager} from './webview_event_manager.js';
diff --git a/chrome/browser/resources/gaia_auth_host/saml_username_autofill.js b/chrome/browser/resources/gaia_auth_host/saml_username_autofill.js index 78dece5..a6b142b6 100644 --- a/chrome/browser/resources/gaia_auth_host/saml_username_autofill.js +++ b/chrome/browser/resources/gaia_auth_host/saml_username_autofill.js
@@ -2,7 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// <if expr="chromeos_ash"> import {appendParam} from 'chrome://resources/js/util.js'; +// </if> +// <if expr="not chromeos_ash"> +import {appendParam} from 'chrome://resources/js/util_ts.js'; +// </if> /** * Try to autofill email on login page for supported identity providers
diff --git a/chrome/browser/resources/inspect/inspect.js b/chrome/browser/resources/inspect/inspect.js index 3ffcbb0..20dad82 100644 --- a/chrome/browser/resources/inspect/inspect.js +++ b/chrome/browser/resources/inspect/inspect.js
@@ -2,7 +2,19 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import {$} from 'chrome://resources/js/util.js'; +import {assert} from 'chrome://resources/js/assert_ts.js'; + +function $(id) { + // Disable getElementById restriction here, because this UI uses non valid + // selectors that don't work with querySelector(). + // eslint-disable-next-line no-restricted-properties + const el = document.getElementById(id); + if (!el) { + return null; + } + assert(el instanceof HTMLElement); + return el; +} const MIN_VERSION_TAB_CLOSE = 25; const MIN_VERSION_TARGET_ID = 26;
diff --git a/chrome/browser/resources/invalidations/about_invalidations.js b/chrome/browser/resources/invalidations/about_invalidations.js index 21781f3..6b5549f 100644 --- a/chrome/browser/resources/invalidations/about_invalidations.js +++ b/chrome/browser/resources/invalidations/about_invalidations.js
@@ -4,7 +4,7 @@ import 'chrome://resources/js/jstemplate_compiled.js'; import {addWebUiListener} from 'chrome://resources/js/cr.js'; -import {$} from 'chrome://resources/js/util.js'; +import {$} from 'chrome://resources/js/util_ts.js'; import {loadTestModule} from './test_loader_util.js'; /**
diff --git a/chrome/browser/resources/net_internals/dns_view.js b/chrome/browser/resources/net_internals/dns_view.js index b3ebb6c7..ab9ebb3 100644 --- a/chrome/browser/resources/net_internals/dns_view.js +++ b/chrome/browser/resources/net_internals/dns_view.js
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import {$} from 'chrome://resources/js/util.js'; +import {$} from 'chrome://resources/js/util_ts.js'; import {BrowserBridge} from './browser_bridge.js'; import {addNode} from './util.js';
diff --git a/chrome/browser/resources/net_internals/domain_security_policy_view.js b/chrome/browser/resources/net_internals/domain_security_policy_view.js index 688b11b..ec5a619 100644 --- a/chrome/browser/resources/net_internals/domain_security_policy_view.js +++ b/chrome/browser/resources/net_internals/domain_security_policy_view.js
@@ -3,7 +3,7 @@ // found in the LICENSE file. import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; -import {$} from 'chrome://resources/js/util.js'; +import {$} from 'chrome://resources/js/util_ts.js'; import './strings.js'; import {BrowserBridge} from './browser_bridge.js';
diff --git a/chrome/browser/resources/net_internals/events_view.js b/chrome/browser/resources/net_internals/events_view.js index ea186f7e..5fb2dad 100644 --- a/chrome/browser/resources/net_internals/events_view.js +++ b/chrome/browser/resources/net_internals/events_view.js
@@ -7,7 +7,7 @@ * help users migrate to using net-export and the catapult netlog_viewer. */ -import {$} from 'chrome://resources/js/util.js'; +import {$} from 'chrome://resources/js/util_ts.js'; import {DivView} from './view.js';
diff --git a/chrome/browser/resources/net_internals/proxy_view.js b/chrome/browser/resources/net_internals/proxy_view.js index beea9fc57..f9f3429 100644 --- a/chrome/browser/resources/net_internals/proxy_view.js +++ b/chrome/browser/resources/net_internals/proxy_view.js
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import {$} from 'chrome://resources/js/util.js'; +import {$} from 'chrome://resources/js/util_ts.js'; import {BrowserBridge} from './browser_bridge.js'; import {DivView} from './view.js';
diff --git a/chrome/browser/resources/net_internals/sockets_view.js b/chrome/browser/resources/net_internals/sockets_view.js index 4b32c4d..8680019a 100644 --- a/chrome/browser/resources/net_internals/sockets_view.js +++ b/chrome/browser/resources/net_internals/sockets_view.js
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import {$} from 'chrome://resources/js/util.js'; +import {$} from 'chrome://resources/js/util_ts.js'; import {BrowserBridge} from './browser_bridge.js'; import {DivView} from './view.js';
diff --git a/chrome/browser/resources/net_internals/tab_switcher_view.js b/chrome/browser/resources/net_internals/tab_switcher_view.js index 47fc7211..3d3fb93 100644 --- a/chrome/browser/resources/net_internals/tab_switcher_view.js +++ b/chrome/browser/resources/net_internals/tab_switcher_view.js
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import {$} from 'chrome://resources/js/util.js'; +import {$} from 'chrome://resources/js/util_ts.js'; import {addNode, addNodeWithText, setNodeDisplay, setNodePosition} from './util.js'; import {View} from './view.js';
diff --git a/chrome/browser/resources/net_internals/view.js b/chrome/browser/resources/net_internals/view.js index cead5d2..a968141 100644 --- a/chrome/browser/resources/net_internals/view.js +++ b/chrome/browser/resources/net_internals/view.js
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import {$} from 'chrome://resources/js/util.js'; +import {$} from 'chrome://resources/js/util_ts.js'; import {setNodeDisplay, setNodePosition} from './util.js'; /**
diff --git a/chrome/browser/resources/ntp4/apps_page.js b/chrome/browser/resources/ntp4/apps_page.js index 908d61b..750858a 100644 --- a/chrome/browser/resources/ntp4/apps_page.js +++ b/chrome/browser/resources/ntp4/apps_page.js
@@ -4,7 +4,7 @@ import {assert} from 'chrome://resources/js/assert.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; -import {$, appendParam} from 'chrome://resources/js/util.js'; +import {$, appendParam} from 'chrome://resources/js/util_ts.js'; import {AppInfo} from './app_info.js'; import {contextMenuHandler} from './context_menu_handler.js';
diff --git a/chrome/browser/resources/ntp4/card_slider.js b/chrome/browser/resources/ntp4/card_slider.js index 8d4cde3..573d2459c 100644 --- a/chrome/browser/resources/ntp4/card_slider.js +++ b/chrome/browser/resources/ntp4/card_slider.js
@@ -3,7 +3,7 @@ // found in the LICENSE file. import {assert, assertInstanceof} from 'chrome://resources/js/assert.js'; -import {isRTL} from 'chrome://resources/js/util.js'; +import {isRTL} from 'chrome://resources/js/util_ts.js'; import {dispatchSimpleEvent} from './cr_deprecated.js'; import {TouchHandler} from './touch_handler.js';
diff --git a/chrome/browser/resources/ntp4/dot_list.js b/chrome/browser/resources/ntp4/dot_list.js index 9ee89fff..b2146f4 100644 --- a/chrome/browser/resources/ntp4/dot_list.js +++ b/chrome/browser/resources/ntp4/dot_list.js
@@ -3,7 +3,7 @@ // found in the LICENSE file. import {define as crUiDefine} from './ui.js'; -import {hasKeyModifiers} from 'chrome://resources/js/util.js'; +import {hasKeyModifiers} from 'chrome://resources/js/util_ts.js'; /** * @fileoverview DotList implementation
diff --git a/chrome/browser/resources/ntp4/incognito_tab.js b/chrome/browser/resources/ntp4/incognito_tab.js index 5a955b13..cece91f4 100644 --- a/chrome/browser/resources/ntp4/incognito_tab.js +++ b/chrome/browser/resources/ntp4/incognito_tab.js
@@ -3,7 +3,7 @@ // found in the LICENSE file. import {addWebUiListener} from 'chrome://resources/js/cr.js'; -import {$} from 'chrome://resources/js/util.js'; +import {$} from 'chrome://resources/js/util_ts.js'; window.addEventListener('load', function() { let cookieSettingsUrl;
diff --git a/chrome/browser/resources/ntp4/new_tab.js b/chrome/browser/resources/ntp4/new_tab.js index b8a879a..0802beb 100644 --- a/chrome/browser/resources/ntp4/new_tab.js +++ b/chrome/browser/resources/ntp4/new_tab.js
@@ -7,7 +7,7 @@ import {assert} from 'chrome://resources/js/assert.js'; import {addWebUiListener} from 'chrome://resources/js/cr.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; -import {$, appendParam, getRequiredElement} from 'chrome://resources/js/util.js'; +import {$, appendParam, getRequiredElement} from 'chrome://resources/js/util_ts.js'; import {AppInfo} from './app_info.js'; import {APP_LAUNCH, AppsPage} from './apps_page.js';
diff --git a/chrome/browser/resources/ntp4/page_list_view.js b/chrome/browser/resources/ntp4/page_list_view.js index baf97ce..8fcf14fb 100644 --- a/chrome/browser/resources/ntp4/page_list_view.js +++ b/chrome/browser/resources/ntp4/page_list_view.js
@@ -5,7 +5,7 @@ import {assert} from 'chrome://resources/js/assert.js'; import {EventTracker} from 'chrome://resources/js/event_tracker.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; -import {$, isRTL} from 'chrome://resources/js/util.js'; +import {$, isRTL} from 'chrome://resources/js/util_ts.js'; import {AppInfo} from './app_info.js'; import {App, AppsPage} from './apps_page.js';
diff --git a/chrome/browser/resources/ntp4/tile_page.js b/chrome/browser/resources/ntp4/tile_page.js index 72c15f07..536c982 100644 --- a/chrome/browser/resources/ntp4/tile_page.js +++ b/chrome/browser/resources/ntp4/tile_page.js
@@ -6,7 +6,7 @@ import {DragWrapper, DragWrapperDelegate} from 'chrome://resources/js/drag_wrapper.js'; import {EventTracker} from 'chrome://resources/js/event_tracker.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; -import {$, isRTL} from 'chrome://resources/js/util.js'; +import {$, isRTL} from 'chrome://resources/js/util_ts.js'; import {App} from './apps_page.js'; import {dispatchSimpleEvent} from './cr_deprecated.js';
diff --git a/chrome/browser/resources/settings/chromeos/device_page/device_page.ts b/chrome/browser/resources/settings/chromeos/device_page/device_page.ts index f223edd7..90d6658 100644 --- a/chrome/browser/resources/settings/chromeos/device_page/device_page.ts +++ b/chrome/browser/resources/settings/chromeos/device_page/device_page.ts
@@ -103,6 +103,17 @@ }, /** + * Whether settings should be split per device. + */ + isDeviceSettingsSplitEnabled_: { + type: Boolean, + value() { + return loadTimeData.getBoolean('enableInputDeviceSettingsSplit'); + }, + readOnly: true, + }, + + /** * Whether storage management info should be hidden. */ hideStorageInfo_: {
diff --git a/chrome/browser/resources/settings/icons.html b/chrome/browser/resources/settings/icons.html index fa7dc9c..3a689f3 100644 --- a/chrome/browser/resources/settings/icons.html +++ b/chrome/browser/resources/settings/icons.html
@@ -6,10 +6,11 @@ <svg> <defs> <g id="account-circle"><path fill-rule="evenodd" clip-rule="evenodd" d="M10 1.667A8.336 8.336 0 0 0 1.667 10c0 4.6 3.733 8.333 8.333 8.333S18.333 14.6 18.333 10 14.6 1.667 10 1.667zM5.89 15.233c.359-.75 2.542-1.483 4.109-1.483 1.566 0 3.758.733 4.108 1.483A6.578 6.578 0 0 1 10 16.667a6.577 6.577 0 0 1-4.109-1.434zM10 12.083c1.216 0 4.108.492 5.3 1.942A6.625 6.625 0 0 0 16.666 10 6.676 6.676 0 0 0 10 3.333 6.676 6.676 0 0 0 3.333 10c0 1.517.517 2.908 1.367 4.025 1.191-1.45 4.083-1.942 5.3-1.942zM10 5a2.91 2.91 0 0 0-2.917 2.917A2.91 2.91 0 0 0 10 10.833a2.91 2.91 0 0 0 2.916-2.916A2.91 2.91 0 0 0 10 5zM8.75 7.917c0 .691.558 1.25 1.25 1.25.691 0 1.25-.559 1.25-1.25 0-.692-.559-1.25-1.25-1.25-.692 0-1.25.558-1.25 1.25z"></path></g> - <g id="bar-chart"><path fill-rule="evenodd" clip-rule="evenodd" d="M8.74996 4.16667H11.25V15.8333H8.74996V4.16667ZM4.16663 7.50001H6.66663V15.8333H4.16663V7.50001ZM15.8333 10.8333H13.3333V15.8333H15.8333V10.8333Z"></path></g> + <g id="bar-chart"><path fill-rule="evenodd" clip-rule="evenodd" d="M4 16V8h3v8Zm4.5 0V4h3v12Zm4.5 0v-6h3v6Z"></path></g> <g id="block"><path fill-rule="evenodd" clip-rule="evenodd" d="M9.99984 1.66667C5.39984 1.66667 1.6665 5.40001 1.6665 10C1.6665 14.6 5.39984 18.3333 9.99984 18.3333C14.5998 18.3333 18.3332 14.6 18.3332 10C18.3332 5.40001 14.5998 1.66667 9.99984 1.66667ZM3.33317 10C3.33317 6.31667 6.3165 3.33334 9.99984 3.33334C11.5415 3.33334 12.9582 3.85834 14.0832 4.74167L4.7415 14.0833C3.85817 12.9583 3.33317 11.5417 3.33317 10ZM5.9165 15.2583C7.0415 16.1417 8.45817 16.6667 9.99984 16.6667C13.6832 16.6667 16.6665 13.6833 16.6665 10C16.6665 8.45834 16.1415 7.04167 15.2582 5.91667L5.9165 15.2583Z"></path></g> <g id="broken"><path fill-rule="evenodd" clip-rule="evenodd" d="M15.8333 2.5H4.16667C3.25 2.5 2.5 3.25 2.5 4.16667V15.8333C2.5 16.75 3.25 17.5 4.16667 17.5H15.8333C16.75 17.5 17.5 16.75 17.5 15.8333V4.16667C17.5 3.25 16.75 2.5 15.8333 2.5ZM15.8333 4.16667V9.29167L14 7L11.3333 10.3333L8.66667 7L6 10.3333L4.16667 8.04167V4.16667H15.8333ZM4.16667 10.7083V15.8333H15.8417V11.9583L14.0083 9.66667L11.3333 13L8.66667 9.66667L6 13L4.16667 10.7083Z"></path></g> <g id="check-circle-outline"><path fill-rule="evenodd" clip-rule="evenodd" d="M9.99984 1.66663C5.39984 1.66663 1.6665 5.39996 1.6665 9.99996C1.6665 14.6 5.39984 18.3333 9.99984 18.3333C14.5998 18.3333 18.3332 14.6 18.3332 9.99996C18.3332 5.39996 14.5998 1.66663 9.99984 1.66663ZM9.99984 16.6666C6.32484 16.6666 3.33317 13.675 3.33317 9.99996C3.33317 6.32496 6.32484 3.33329 9.99984 3.33329C13.6748 3.33329 16.6665 6.32496 16.6665 9.99996C16.6665 13.675 13.6748 16.6666 9.99984 16.6666ZM6.1665 9.66663L8.33317 11.8333L13.8332 6.33329L14.9998 7.49996L8.33317 14.1666L4.99984 10.8333L6.1665 9.66663Z"></path></g> + <g id="checklist"><path d="M4.833 15.5 2 12.667l1.062-1.063 1.75 1.771 3.542-3.542 1.084 1.063Zm0-6.5L2 6.167l1.062-1.063 1.771 1.771 3.521-3.542 1.084 1.063ZM11 14v-1.5h7V14Zm0-6.5V6h7v1.5Z"></path></g> <g id="credit-card"><path d="M16.4,4 L3.6,4 C2.716,4 2.008,4.7271875 2.008,5.625 L2,15.375 C2,16.2728125 2.716,17 3.6,17 L16.4,17 C17.284,17 18,16.2728125 18,15.375 L18,5.625 C18,4.7271875 17.284,4 16.4,4 Z M16.5,15 L3.5,15 L3.5,10 L16.5,10 L16.5,15 Z M16.5,7 L3.5,7 L3.5,5.5 L16.5,5.5 L16.5,7 Z"></path></g> <g id="data"><path d="M0 0h20v20H0z" fill="none" fill-rule="evenodd"></path><path d="M6.5 7v9H4V7h2.5zm5-3v12H9V4h2.5zm5 7v5H14v-5h2.5z"></path></g> <g id="data-connectors-system"><path d="M10 4.16667C10.0833 4.16667 10.2333 4.18333 10.3667 4.30833L13.025 6.96667L15.675 9.60833C15.8083 9.74167 15.825 9.9 15.825 10.0167V10.0417C15.825 10.125 15.8 10.2 15.7667 10.2667C15.7583 10.2833 15.75 10.3 15.7417 10.3083C15.725 10.3333 15.7 10.3667 15.675 10.3917L10.4 15.65L10.3583 15.6917C10.2333 15.8167 10.0833 15.8333 10 15.8333C9.91667 15.8333 9.75 15.8167 9.61667 15.675L4.325 10.3833C4.18333 10.2583 4.16667 10.1 4.16667 9.99167C4.16667 9.90833 4.18333 9.75 4.31667 9.60833L6.44167 7.48333L9.60833 4.325C9.75 4.18333 9.91667 4.16667 10 4.16667ZM10 2.5C9.43333 2.5 8.86667 2.71667 8.44167 3.14167L5.275 6.3L3.15 8.425C2.70833 8.85833 2.5 9.43333 2.5 10C2.5 10.5667 2.70833 11.1417 3.14167 11.575L5.26667 13.7L8.43333 16.8583C8.86667 17.2833 9.43333 17.5 10 17.5C10.5667 17.5 11.1333 17.2833 11.5583 16.8583L16.8583 11.575C16.9667 11.4667 17.0583 11.35 17.1417 11.2333C17.1833 11.175 17.2167 11.1083 17.25 11.05C17.4167 10.7333 17.5 10.375 17.5 10.025C17.5 10.0167 17.5 10.0167 17.5 10.0083C17.5083 9.44167 17.2917 8.86667 16.8583 8.43333L11.5583 3.15C11.1333 2.71667 10.5667 2.5 10 2.5Z"></path><path d="M10 11.6667L8.33333 10L10 8.33333L11.6667 10L10 11.6667Z"></path><path d="M10.5917 7.25833C10.9167 6.93333 10.9167 6.40833 10.5917 6.08333C10.2667 5.75833 9.74167 5.75833 9.41667 6.08333C9.09167 6.40833 9.09167 6.93333 9.41667 7.25833C9.73333 7.58333 10.2667 7.58333 10.5917 7.25833Z"></path><path d="M7.25833 10.5917C7.58333 10.2667 7.58333 9.74167 7.25833 9.41667C6.93333 9.09167 6.40833 9.09167 6.08333 9.41667C5.75833 9.74167 5.75833 10.2667 6.08333 10.5917C6.4 10.9167 6.93333 10.9167 7.25833 10.5917Z"></path><path d="M10.5917 13.925C10.9167 13.6 10.9167 13.075 10.5917 12.75C10.2667 12.425 9.74167 12.425 9.41667 12.75C9.09167 13.075 9.09167 13.6 9.41667 13.925C9.73333 14.25 10.2667 14.25 10.5917 13.925Z"></path><path d="M13.925 10.5917C14.25 10.2667 14.25 9.74167 13.925 9.41667C13.6 9.09167 13.075 9.09167 12.75 9.41667C12.425 9.74167 12.425 10.2667 12.75 10.5917C13.0667 10.9167 13.6 10.9167 13.925 10.5917Z"></g> @@ -21,10 +22,12 @@ <g id="history"><path fill-rule="evenodd" clip-rule="evenodd" d="M3.33341 5.00832V3.33332H1.66675V8.33332H6.66675V6.66666H4.24175C5.39175 4.67499 7.53341 3.33332 10.0001 3.33332C13.6834 3.33332 16.6667 6.31666 16.6667 9.99999C16.6667 13.6833 13.6834 16.6667 10.0001 16.6667C6.31675 16.6667 3.33341 13.6833 3.33341 9.99999H1.66675C1.66675 14.6 5.40008 18.3333 10.0084 18.3333C14.6084 18.3333 18.3334 14.6 18.3334 9.99999C18.3334 5.39999 14.6084 1.66666 10.0084 1.66666C7.27508 1.66666 4.85841 2.98332 3.33341 5.00832ZM10.8334 4.99999V9.99999L14.3584 12.45L13.3084 13.7417L9.16675 10.8333V4.99999H10.8334Z"></path></g> <g id="incognito" fill="#5F6368"><circle cx="6.8" cy="12.964" r="1.764"/><path d="M10 0C4.473 0 0 4.473 0 10s4.473 10 10 10 10-4.473 10-10S15.527 0 10 0zM7.619 4.1a.696.696 0 0 1 .881-.419l1.473.492 1.463-.492a.716.716 0 0 1 .883.419l1.608 4.291H6.02l1.6-4.291zm5.517 11.328a2.463 2.463 0 0 1-2.445-2.256c-.682-.436-1.237-.162-1.455-.017a2.45 2.45 0 0 1-2.445 2.263 2.471 2.471 0 0 1-2.464-2.463 2.47 2.47 0 0 1 2.463-2.464c1.165 0 2.138.809 2.391 1.9a1.934 1.934 0 0 1 1.546.009 2.462 2.462 0 0 1 2.392-1.909 2.47 2.47 0 0 1 2.462 2.463 2.435 2.435 0 0 1-2.445 2.474zM16.31 9.8H3.637v-.709H16.31V9.8h-.001z"/><circle cx="13.136" cy="12.964" r="1.764"/></g> <g id="incognito-unfilled"><path d="M17.5 9.16667H2.5V10H17.5V9.16667Z"></path><path d="M14.6833 8.33334L12.775 3.25001C12.6167 2.83334 12.1583 2.60834 11.7333 2.75L10 3.33334L8.25833 2.75C7.83333 2.60834 7.375 2.83334 7.21667 3.25001L5.31667 8.33334H14.6833Z"></path><path d="M13.75 10.8333C12.3667 10.8333 11.2167 11.8 10.9167 13.0917C10.2167 12.7917 9.56667 12.875 9.08333 13.0833C8.775 11.7917 7.625 10.8333 6.25 10.8333C4.64167 10.8333 3.33333 12.1417 3.33333 13.75C3.33333 15.3583 4.64167 16.6667 6.25 16.6667C7.78333 16.6667 9.025 15.4833 9.14167 13.9833C9.39167 13.8083 10.05 13.4833 10.8583 14C10.9917 15.4917 12.225 16.6667 13.75 16.6667C15.3583 16.6667 16.6667 15.3583 16.6667 13.75C16.6667 12.1417 15.3583 10.8333 13.75 10.8333ZM6.25 15.8333C5.1 15.8333 4.16667 14.9 4.16667 13.75C4.16667 12.6 5.1 11.6667 6.25 11.6667C7.4 11.6667 8.33333 12.6 8.33333 13.75C8.33333 14.9 7.4 15.8333 6.25 15.8333ZM13.75 15.8333C12.6 15.8333 11.6667 14.9 11.6667 13.75C11.6667 12.6 12.6 11.6667 13.75 11.6667C14.9 11.6667 15.8333 12.6 15.8333 13.75C15.8333 14.9 14.9 15.8333 13.75 15.8333Z"></path></g> + <g id="interests"><path d="m2 9 4-7 4 7Zm4 8q-1.25 0-2.125-.875T3 14q0-1.25.875-2.125T6 11q1.25 0 2.125.875T9 14q0 1.25-.875 2.125T6 17Zm0-1.5q.625 0 1.062-.438Q7.5 14.625 7.5 14t-.438-1.062Q6.625 12.5 6 12.5t-1.062.438Q4.5 13.375 4.5 14t.438 1.062Q5.375 15.5 6 15.5Zm-1.396-8h2.792L6 5.021ZM11 17v-6h6v6Zm1.5-1.5h3v-3h-3ZM14 9q-1.125-.938-1.854-1.552-.729-.615-1.167-1.083-.437-.469-.614-.865t-.177-.896q0-.875.583-1.489.583-.615 1.5-.615.541 0 .969.219.427.219.76.677.333-.458.771-.677.437-.219.958-.219.917 0 1.5.615.583.614.583 1.489 0 .5-.166.896-.167.396-.604.854-.438.458-1.177 1.073Q15.125 8.042 14 9Zm0-2q1.417-1.188 1.865-1.635.447-.448.447-.782 0-.229-.166-.406Q15.979 4 15.75 4q-.167 0-.312.083-.146.084-.25.209L14 5.396l-1.167-1.104q-.125-.125-.271-.209Q12.417 4 12.25 4q-.229 0-.396.177-.166.177-.166.406 0 .355.468.813Q12.625 5.854 14 7Zm0-1.604Zm-7.979 1Zm0 7.542Zm7.958 0Z"></path></g> <g id="lightbulb"><path d="M7.49996 17.5C7.49996 17.9583 7.87496 18.3333 8.33329 18.3333H11.6666C12.125 18.3333 12.5 17.9583 12.5 17.5V16.6667H7.49996V17.5ZM9.99996 1.66667C6.78329 1.66667 4.16663 4.28334 4.16663 7.50001C4.16663 9.48334 5.15829 11.225 6.66663 12.2833V14.1667C6.66663 14.625 7.04163 15 7.49996 15H12.5C12.9583 15 13.3333 14.625 13.3333 14.1667V12.2833C14.8416 11.225 15.8333 9.48334 15.8333 7.50001C15.8333 4.28334 13.2166 1.66667 9.99996 1.66667ZM12.375 10.9167L11.6666 11.4167V13.3333H8.33329V11.4167L7.62496 10.9167C6.49996 10.1333 5.83329 8.85834 5.83329 7.50001C5.83329 5.20001 7.69996 3.33334 9.99996 3.33334C12.3 3.33334 14.1666 5.20001 14.1666 7.50001C14.1666 8.85834 13.5 10.1333 12.375 10.9167Z"></path></g> <g id="link"><path fill-rule="evenodd" clip-rule="evenodd" d="M9.16663 12.5H5.83329C4.45829 12.5 3.33329 11.375 3.33329 10C3.33329 8.62501 4.45829 7.50001 5.83329 7.50001H9.16663V5.83334H5.83329C3.53329 5.83334 1.66663 7.70001 1.66663 10C1.66663 12.3 3.53329 14.1667 5.83329 14.1667H9.16663V12.5ZM14.1666 5.83334H10.8333V7.50001H14.1666C15.5416 7.50001 16.6666 8.62501 16.6666 10C16.6666 11.375 15.5416 12.5 14.1666 12.5H10.8333V14.1667H14.1666C16.4666 14.1667 18.3333 12.3 18.3333 10C18.3333 7.70001 16.4666 5.83334 14.1666 5.83334ZM13.3333 9.16668H6.66663V10.8333H13.3333V9.16668Z"></path></g> <g id="logout"><path d="M14.1665 5.83333L12.9915 7.00833L15.1415 9.16667H6.6665V10.8333H15.1415L12.9915 12.9833L14.1665 14.1667L18.3332 10L14.1665 5.83333ZM3.33317 4.16667H9.99984V2.5H3.33317C2.4165 2.5 1.6665 3.25 1.6665 4.16667V15.8333C1.6665 16.75 2.4165 17.5 3.33317 17.5H9.99984V15.8333H3.33317V4.16667Z"></path></g> <g id="public"><path fill-rule="evenodd" clip-rule="evenodd" d="M10 1.667A8.336 8.336 0 0 0 1.667 10c0 4.6 3.733 8.333 8.333 8.333S18.333 14.6 18.333 10 14.6 1.667 10 1.667zM3.333 10c0-.508.067-1.008.175-1.483L7.492 12.5v.833c0 .917.75 1.667 1.666 1.667v1.608C5.883 16.192 3.333 13.392 3.333 10zm9.992 3.333c.75 0 1.367.492 1.583 1.167a6.66 6.66 0 0 0 1.758-4.5 6.67 6.67 0 0 0-4.175-6.175v.342c0 .916-.75 1.666-1.666 1.666H9.158V7.5a.836.836 0 0 1-.833.833H6.658V10h5c.459 0 .834.375.834.833v2.5h.833z"></path></g> + <g id="privacy-sandbox"><path d="M11.708 17.562q-.437.438-1.062.438t-1.063-.438l-7.145-7.145q-.209-.209-.323-.49Q2 9.646 2 9.354V3.5q0-.625.438-1.062Q2.875 2 3.5 2h5.854q.292 0 .563.104.271.104.5.334l7.145 7.145q.438.438.438 1.052 0 .615-.438 1.053ZM10.646 16.5l5.854-5.854L9.354 3.5H3.5v5.854ZM5.5 6.75q.521 0 .885-.365.365-.364.365-.885t-.365-.885Q6.021 4.25 5.5 4.25t-.885.365q-.365.364-.365.885t.365.885q.364.365.885.365Zm-2-3.25Z"></path></g> <g id="security"><path fill-rule="evenodd" clip-rule="evenodd" d="M3.183 4.7L10 1.667 16.816 4.7v4.542c0 4.208-2.908 8.133-6.816 9.091-3.909-.958-6.817-4.883-6.817-9.091V4.7zM15.3 9.992H10V3.325L4.7 5.683V10l5.3-.008v6.775c2.816-.875 4.9-3.65 5.3-6.775z"></path></g> <g id="shoppingcart"><path fill-rule="evenodd" clip-rule="evenodd" d="M12.1585 10.8333H12.8502C13.4502 10.8333 14.0002 10.5083 14.3002 9.99167L17.0335 5.20001C17.2502 4.81667 17.2502 4.33334 17.0335 3.95001C16.8168 3.56667 16.3918 3.33334 15.9502 3.33334H4.61683L3.87516 1.66667H0.833496V3.33334H2.79183L5.74183 9.98334L4.85016 11.7583C4.59183 12.275 4.61683 12.8833 4.92516 13.3833C5.2335 13.8833 5.7585 14.175 6.34183 14.175H15.8335V12.5083H6.35016L7.1835 10.8417H12.1585V10.8333ZM7.50016 16.6667C7.50016 17.5871 6.75397 18.3333 5.8335 18.3333C4.91302 18.3333 4.16683 17.5871 4.16683 16.6667C4.16683 15.7462 4.91302 15 5.8335 15C6.75397 15 7.50016 15.7462 7.50016 16.6667ZM15.8335 16.6667C15.8335 17.5871 15.0873 18.3333 14.1668 18.3333C13.2464 18.3333 12.5002 17.5871 12.5002 16.6667C12.5002 15.7462 13.2464 15 14.1668 15C15.0873 15 15.8335 15.7462 15.8335 16.6667ZM12.8502 9.16667L15.2335 5.00001H5.3585L7.2085 9.16667H12.8502Z"></path></g> <g id="vpn-key"><path d="M10.4727273,8 C9.87272727,6.2525 8.26181818,5 6.36363636,5 C3.95272727,5 2,7.01375 2,9.5 C2,11.98625 3.95272727,14 6.36363636,14 C8.26181818,14 9.87272727,12.7475 10.4727273,11 L13.6363636,11 L13.6363636,14 L16.5454545,14 L16.5454545,11 L18,11 L18,8 L10.4727273,8 Z M6.36363636,11 C5.56,11 4.90909091,10.32875 4.90909091,9.5 C4.90909091,8.67125 5.56,8 6.36363636,8 C7.16727273,8 7.81818182,8.67125 7.81818182,9.5 C7.81818182,10.32875 7.16727273,11 6.36363636,11 Z"></path></g>
diff --git a/chrome/browser/resources/settings/privacy_page/privacy_page.html b/chrome/browser/resources/settings/privacy_page/privacy_page.html index fb679133..4837cf70 100644 --- a/chrome/browser/resources/settings/privacy_page/privacy_page.html +++ b/chrome/browser/resources/settings/privacy_page/privacy_page.html
@@ -61,9 +61,9 @@ role-description="$i18n{subpageArrowRoleDescription}"></cr-link-row> <template is="dom-if" if= "[[isPrivacySandboxSettings4Enabled_(isPrivacySandboxRestricted_, isPrivacySandboxSettings4_)]]"> - <!-- TODO(crbug.com/1378703): Replace strings and icons. --> + <!-- TODO(crbug.com/1378703): Replace strings. --> <cr-link-row id="privacySandboxLinkRow" - start-icon="settings20:experiment" + start-icon="settings20:privacy-sandbox" class="hr" label="$i18n{privacySandboxTitle}" sub-label="[[computePrivacySandboxSublabel_(
diff --git a/chrome/browser/resources/settings/privacy_page/privacy_sandbox/privacy_sandbox_page.html b/chrome/browser/resources/settings/privacy_page/privacy_sandbox/privacy_sandbox_page.html index 4e53070..255335f 100644 --- a/chrome/browser/resources/settings/privacy_page/privacy_sandbox/privacy_sandbox_page.html +++ b/chrome/browser/resources/settings/privacy_page/privacy_sandbox/privacy_sandbox_page.html
@@ -2,21 +2,23 @@ <!-- TODO(b/254413936): Add image header. --> -<!-- TODO(b/254414194): Add icons. --> <!-- TODO(crbug.com/1378703): Use string identifiers. --> <cr-link-row id="privacySandboxTopicsLinkRow" + start-icon="settings20:interests" label="Mauris interdum lectus vitae lacinia" sub-label="[[computePrivacySandboxTopicsSublabel_()]]" on-click="onPrivacySandboxTopicsClick_"></cr-link-row> <cr-link-row id="privacySandboxFledgeLinkRow" + start-icon="settings20:checklist" class="hr" label="Aenean erat leo" sub-label="[[computePrivacySandboxFledgeSublabel_()]]" on-click="onPrivacySandboxFledgeClick_"></cr-link-row> <cr-link-row id="privacySandboxMeasurementLinkRow" + start-icon="settings20:bar-chart" class="hr" label="Vestibulum augue erat" sub-label="[[computePrivacySandboxMeasurementSublabel_()]]"
diff --git a/chrome/browser/supervised_user/chromeos/supervised_user_favicon_request_handler.cc b/chrome/browser/supervised_user/chromeos/supervised_user_favicon_request_handler.cc index 883464c4..e53f786 100644 --- a/chrome/browser/supervised_user/chromeos/supervised_user_favicon_request_handler.cc +++ b/chrome/browser/supervised_user/chromeos/supervised_user_favicon_request_handler.cc
@@ -19,7 +19,7 @@ constexpr int kMonogramSize = 20; const char kFaviconAvailabilityHistogramName[] = - "SupervisedUsers.FaviconAvailability"; + "ChromeOS.FamilyLinkUser.FaviconAvailability"; } // namespace // static
diff --git a/chrome/browser/tab/java/src/org/chromium/chrome/browser/tab/EmptyTabObserver.java b/chrome/browser/tab/java/src/org/chromium/chrome/browser/tab/EmptyTabObserver.java index b6e91be..e327824 100644 --- a/chrome/browser/tab/java/src/org/chromium/chrome/browser/tab/EmptyTabObserver.java +++ b/chrome/browser/tab/java/src/org/chromium/chrome/browser/tab/EmptyTabObserver.java
@@ -147,7 +147,4 @@ @Override public void onContentViewScrollingStateChanged(boolean scrolling) {} - - @Override - public void onContentViewScrollingEnded(int verticalScrollDelta) {} }
diff --git a/chrome/browser/tab/java/src/org/chromium/chrome/browser/tab/TabObserver.java b/chrome/browser/tab/java/src/org/chromium/chrome/browser/tab/TabObserver.java index 4a059348..14a48301 100644 --- a/chrome/browser/tab/java/src/org/chromium/chrome/browser/tab/TabObserver.java +++ b/chrome/browser/tab/java/src/org/chromium/chrome/browser/tab/TabObserver.java
@@ -344,11 +344,4 @@ * @param scrolling {@code true} if scrolling started; {@code false} if stopped. */ void onContentViewScrollingStateChanged(boolean scrolling); - - /** - * Called when the Tab stops scrolling. - * @param verticalScrollDelta The delta between the vertical offsets when the scroll started and - * currently. It is negative when the tab scrolled down and positive when scrolled up. - */ - void onContentViewScrollingEnded(int verticalScrollDelta); }
diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index 7e2e0126..011506e 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn
@@ -2179,8 +2179,6 @@ "app_list/search/ranking/ranker.h", "app_list/search/ranking/ranker_manager.cc", "app_list/search/ranking/ranker_manager.h", - "app_list/search/ranking/ranking_item_util.cc", - "app_list/search/ranking/ranking_item_util.h", "app_list/search/ranking/removed_results_ranker.cc", "app_list/search/ranking/removed_results_ranker.h", "app_list/search/ranking/score_normalizing_ranker.cc", @@ -2881,6 +2879,8 @@ "webui/ash/onc_import_message_handler.h", "webui/ash/parent_access/parent_access_dialog.cc", "webui/ash/parent_access/parent_access_dialog.h", + "webui/ash/parent_access/parent_access_state_tracker.cc", + "webui/ash/parent_access/parent_access_state_tracker.h", "webui/ash/parent_access/parent_access_ui.cc", "webui/ash/parent_access/parent_access_ui.h", "webui/ash/parent_access/parent_access_ui_handler_delegate.h",
diff --git a/chrome/browser/ui/android/webid/account_selection_view_android.cc b/chrome/browser/ui/android/webid/account_selection_view_android.cc index 6761cbff..10640fe 100644 --- a/chrome/browser/ui/android/webid/account_selection_view_android.cc +++ b/chrome/browser/ui/android/webid/account_selection_view_android.cc
@@ -160,6 +160,9 @@ delegate_->OnAccountSelected( config_url, ConvertFieldsToAccount(env, account_string_fields, account_picture_url, is_sign_in)); + // The AccountSelectionViewAndroid may be destroyed. + // AccountSelectionView::Delegate::OnAccountSelected() might delete this. + // See https://crbug.com/1393650 for details. } void AccountSelectionViewAndroid::OnDismiss(JNIEnv* env, jint dismiss_reason) {
diff --git a/chrome/browser/ui/app_list/app_list_client_impl.cc b/chrome/browser/ui/app_list/app_list_client_impl.cc index 765c89d9..508264a5 100644 --- a/chrome/browser/ui/app_list/app_list_client_impl.cc +++ b/chrome/browser/ui/app_list/app_list_client_impl.cc
@@ -28,11 +28,11 @@ #include "chrome/browser/ui/app_list/app_list_notifier_impl.h" #include "chrome/browser/ui/app_list/app_list_syncable_service.h" #include "chrome/browser/ui/app_list/app_list_syncable_service_factory.h" +#include "chrome/browser/ui/app_list/app_list_util.h" #include "chrome/browser/ui/app_list/app_sync_ui_state_watcher.h" #include "chrome/browser/ui/app_list/search/chrome_search_result.h" #include "chrome/browser/ui/app_list/search/cros_action_history/cros_action_recorder.h" #include "chrome/browser/ui/app_list/search/ranking/launch_data.h" -#include "chrome/browser/ui/app_list/search/ranking/ranking_item_util.h" #include "chrome/browser/ui/app_list/search/search_controller.h" #include "chrome/browser/ui/app_list/search/search_controller_factory.h" #include "chrome/browser/ui/ash/shelf/app_shortcut_shelf_item_controller.h" @@ -211,8 +211,6 @@ app_list::LaunchData launch_data; launch_data.id = result_id; launch_data.result_type = result->result_type(); - launch_data.ranking_item_type = - app_list::RankingItemTypeFromSearchResult(*result); launch_data.launch_type = launch_type; launch_data.launched_from = launched_from; launch_data.suggestion_index = suggestion_index; @@ -221,7 +219,7 @@ const size_t last_query_length = search_controller_->get_query().size(); if (launch_type == ash::AppListLaunchType::kAppSearchResult && launched_from == ash::AppListLaunchedFrom::kLaunchedFromSearchBox && - launch_data.ranking_item_type == app_list::RankingItemType::kApp && + app_list::IsResultTypeApp(launch_data.result_type) && last_query_length != 0) { ash::RecordSuccessfulAppLaunchUsingSearch(launched_from, last_query_length); } @@ -345,8 +343,6 @@ // We don't have easy access to the search result type here, so // launch_data.result_type isn't set. However we have no need to distinguish // the type of apps launched from the grid in SearchController::Train. - launch_data.ranking_item_type = - app_list::RankingItemTypeFromChromeAppListItem(*item); launch_data.launched_from = launched_from; search_controller_->Train(std::move(launch_data)); }
diff --git a/chrome/browser/ui/app_list/app_list_client_impl.h b/chrome/browser/ui/app_list/app_list_client_impl.h index b031d535..27ccc1f 100644 --- a/chrome/browser/ui/app_list/app_list_client_impl.h +++ b/chrome/browser/ui/app_list/app_list_client_impl.h
@@ -15,8 +15,6 @@ #include "ash/public/cpp/app_list/app_list_client.h" #include "ash/public/cpp/app_list/app_list_metrics.h" -#include "ash/public/cpp/shelf_types.h" -#include "base/callback_forward.h" #include "base/gtest_prod_util.h" #include "base/memory/weak_ptr.h" #include "base/scoped_observation.h"
diff --git a/chrome/browser/ui/app_list/app_list_util.cc b/chrome/browser/ui/app_list/app_list_util.cc index e3b95a4..83be8a7 100644 --- a/chrome/browser/ui/app_list/app_list_util.cc +++ b/chrome/browser/ui/app_list/app_list_util.cc
@@ -4,12 +4,12 @@ #include "chrome/browser/ui/app_list/app_list_util.h" +#include "ash/public/cpp/app_list/app_list_types.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #if BUILDFLAG(IS_CHROMEOS_ASH) #include "ash/constants/ash_features.h" -#include "ash/public/cpp/app_list/app_list_types.h" #endif bool IsAppLauncherEnabled() { @@ -20,8 +20,8 @@ #endif } -#if BUILDFLAG(IS_CHROMEOS_ASH) namespace app_list { +#if BUILDFLAG(IS_CHROMEOS_ASH) std::unique_ptr<ash::AppListItemMetadata> GenerateItemMetadataFromSyncItem( const app_list::AppListSyncableService::SyncItem& sync_item) { DCHECK(sync_item.item_type != sync_pb::AppListSpecifics::TYPE_PAGE_BREAK); @@ -38,5 +38,37 @@ return item_meta_data; } -} // namespace app_list #endif + +bool IsResultTypeApp(ash::AppListSearchResultType result_type) { + switch (result_type) { + case ash::AppListSearchResultType::kInstalledApp: + case ash::AppListSearchResultType::kZeroStateApp: + case ash::AppListSearchResultType::kInternalApp: + case ash::AppListSearchResultType::kGames: + return true; + case ash::AppListSearchResultType::kOmnibox: + case ash::AppListSearchResultType::kLauncher: + case ash::AppListSearchResultType::kFileSearch: + case ash::AppListSearchResultType::kDriveSearch: + case ash::AppListSearchResultType::kUnknown: + case ash::AppListSearchResultType::kPlayStoreApp: + case ash::AppListSearchResultType::kInstantApp: + case ash::AppListSearchResultType::kAnswerCard: + case ash::AppListSearchResultType::kPlayStoreReinstallApp: + case ash::AppListSearchResultType::kOsSettings: + case ash::AppListSearchResultType::kInternalPrivacyInfo: + case ash::AppListSearchResultType::kAssistantText: + case ash::AppListSearchResultType::kPersonalization: + case ash::AppListSearchResultType::kHelpApp: + case ash::AppListSearchResultType::kZeroStateHelpApp: + case ash::AppListSearchResultType::kKeyboardShortcut: + case ash::AppListSearchResultType::kOpenTab: + case ash::AppListSearchResultType::kArcAppShortcut: + case ash::AppListSearchResultType::kZeroStateFile: + case ash::AppListSearchResultType::kZeroStateDrive: + return false; + } +} + +} // namespace app_list
diff --git a/chrome/browser/ui/app_list/app_list_util.h b/chrome/browser/ui/app_list/app_list_util.h index 5b7083f..de99b55 100644 --- a/chrome/browser/ui/app_list/app_list_util.h +++ b/chrome/browser/ui/app_list/app_list_util.h
@@ -5,6 +5,7 @@ #ifndef CHROME_BROWSER_UI_APP_LIST_APP_LIST_UTIL_H_ #define CHROME_BROWSER_UI_APP_LIST_APP_LIST_UTIL_H_ +#include "ash/public/cpp/app_list/app_list_types.h" #include "build/chromeos_buildflags.h" #if BUILDFLAG(IS_CHROMEOS_ASH) @@ -18,16 +19,19 @@ // Returns whether the app launcher has been enabled. bool IsAppLauncherEnabled(); -#if BUILDFLAG(IS_CHROMEOS_ASH) namespace app_list { +#if BUILDFLAG(IS_CHROMEOS_ASH) // Generates app list item meta data from the given sync item. Note that // `AppListItemMetadata` has more attributes than `SyncItem`. Those extra // attributes are not covered by this method. std::unique_ptr<ash::AppListItemMetadata> GenerateItemMetadataFromSyncItem( const app_list::AppListSyncableService::SyncItem& sync_item); +#endif + +// Check if `result_type` is app. +bool IsResultTypeApp(ash::AppListSearchResultType result_type); } // namespace app_list -#endif #endif // CHROME_BROWSER_UI_APP_LIST_APP_LIST_UTIL_H_
diff --git a/chrome/browser/ui/app_list/arc/arc_app_utils.cc b/chrome/browser/ui/app_list/arc/arc_app_utils.cc index cdbb2c0..98df4a7e 100644 --- a/chrome/browser/ui/app_list/arc/arc_app_utils.cc +++ b/chrome/browser/ui/app_list/arc/arc_app_utils.cc
@@ -19,21 +19,15 @@ #include "ash/components/arc/session/arc_bridge_service.h" #include "ash/components/arc/session/arc_service_manager.h" #include "base/check.h" -#include "base/containers/contains.h" #include "base/json/json_writer.h" #include "base/metrics/histogram_functions.h" -#include "base/metrics/histogram_macros.h" #include "base/no_destructor.h" #include "base/observer_list.h" #include "base/scoped_multi_source_observation.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_piece.h" -#include "base/strings/string_util.h" -#include "base/strings/stringprintf.h" -#include "base/synchronization/waitable_event.h" #include "base/values.h" #include "chrome/browser/apps/app_service/intent_util.h" -#include "chrome/browser/apps/app_service/launch_utils.h" #include "chrome/browser/ash/arc/arc_migration_guide_notification.h" #include "chrome/browser/ash/arc/arc_util.h" #include "chrome/browser/ash/arc/boot_phase_monitor/arc_boot_phase_monitor_bridge.h" @@ -49,13 +43,11 @@ #include "chrome/browser/ui/app_list/app_list_client_impl.h" #include "chrome/browser/ui/app_list/arc/intent.h" #include "chrome/browser/ui/app_list/search/ranking/launch_data.h" -#include "chrome/browser/ui/app_list/search/ranking/ranking_item_util.h" #include "chrome/browser/ui/app_list/search/search_controller.h" #include "chrome/browser/ui/ash/shelf/arc_app_shelf_id.h" #include "chrome/browser/ui/ash/shelf/arc_shelf_spinner_item_controller.h" #include "chrome/browser/ui/ash/shelf/chrome_shelf_controller.h" #include "chrome/browser/ui/ash/shelf/shelf_spinner_controller.h" -#include "chrome/common/pref_names.h" #include "components/app_restore/app_restore_utils.h" #include "components/app_restore/features.h" #include "components/arc/common/intent_helper/arc_intent_helper_package.h" @@ -63,7 +55,6 @@ #include "components/prefs/pref_service.h" #include "components/services/app_service/public/cpp/intent_util.h" #include "content/public/browser/browser_context.h" -#include "ui/aura/window.h" #include "ui/display/display.h" #include "ui/display/screen.h" #include "ui/events/event_constants.h" @@ -792,7 +783,6 @@ launch_data.id = ConstructArcAppShortcutUrl(arc_shelf_id.app_id(), shortcut_id), launch_data.result_type = ash::AppListSearchResultType::kArcAppShortcut; - launch_data.ranking_item_type = app_list::RankingItemType::kArcAppShortcut; app_list_client_impl->search_controller()->Train(std::move(launch_data)); }
diff --git a/chrome/browser/ui/app_list/arc/arc_app_utils.h b/chrome/browser/ui/app_list/arc/arc_app_utils.h index 3c5d676..9ae6e4b 100644 --- a/chrome/browser/ui/app_list/arc/arc_app_utils.h +++ b/chrome/browser/ui/app_list/arc/arc_app_utils.h
@@ -15,8 +15,6 @@ #include "base/observer_list_types.h" #include "chrome/browser/ui/app_list/arc/arc_app_list_prefs.h" #include "components/services/app_service/public/cpp/intent.h" -#include "components/services/app_service/public/mojom/types.mojom.h" -#include "third_party/abseil-cpp/absl/types/optional.h" class Profile;
diff --git a/chrome/browser/ui/app_list/search/ranking/best_match_ranker.cc b/chrome/browser/ui/app_list/search/ranking/best_match_ranker.cc index 4e30b26..1b2d41a 100644 --- a/chrome/browser/ui/app_list/search/ranking/best_match_ranker.cc +++ b/chrome/browser/ui/app_list/search/ranking/best_match_ranker.cc
@@ -8,11 +8,8 @@ #include <vector> #include "base/containers/flat_set.h" -#include "base/strings/strcat.h" -#include "base/strings/utf_string_conversions.h" #include "chrome/browser/ui/app_list/search/chrome_search_result.h" #include "chrome/browser/ui/app_list/search/ranking/constants.h" -#include "chrome/browser/ui/app_list/search/ranking/util.h" #include "chrome/browser/ui/app_list/search/types.h" namespace app_list { @@ -36,7 +33,20 @@ case ProviderType::kUnknown: case ProviderType::kInternalPrivacyInfo: return true; - default: + case ProviderType::kInternalApp: + case ProviderType::kArcAppShortcut: + case ProviderType::kKeyboardShortcut: + case ProviderType::kDriveSearch: + case ProviderType::kGames: + case ProviderType::kHelpApp: + case ProviderType::kZeroStateHelpApp: + case ProviderType::kFileSearch: + case ProviderType::kInstalledApp: + case ProviderType::kInstantApp: + case ProviderType::kOmnibox: + case ProviderType::kPersonalization: + case ProviderType::kOpenTab: + case ProviderType::kOsSettings: return false; } } @@ -58,9 +68,9 @@ } // namespace -BestMatchRanker::BestMatchRanker() {} +BestMatchRanker::BestMatchRanker() = default; -BestMatchRanker::~BestMatchRanker() {} +BestMatchRanker::~BestMatchRanker() = default; void BestMatchRanker::Start(const std::u16string& query, ResultsMap& results,
diff --git a/chrome/browser/ui/app_list/search/ranking/launch_data.h b/chrome/browser/ui/app_list/search/ranking/launch_data.h index b6af55cd..32df0e8 100644 --- a/chrome/browser/ui/app_list/search/ranking/launch_data.h +++ b/chrome/browser/ui/app_list/search/ranking/launch_data.h
@@ -8,7 +8,6 @@ #include <string> #include "ash/public/cpp/app_list/app_list_types.h" -#include "chrome/browser/ui/app_list/search/ranking/ranking_item_util.h" namespace app_list { @@ -23,10 +22,6 @@ // The type of the result. ash::AppListSearchResultType result_type = ash::AppListSearchResultType::kUnknown; - // The type of the result used for ranking. - // TODO(crbug.com/1378861): This is no longer needed and can be removed when - // the search_result_ranker/ directory is removed. - RankingItemType ranking_item_type = RankingItemType::kUnknown; ash::AppListLaunchedFrom launched_from = ash::AppListLaunchedFrom::kLaunchedFromShelf; // The type of app launched.
diff --git a/chrome/browser/ui/app_list/search/ranking/ranking_item_util.cc b/chrome/browser/ui/app_list/search/ranking/ranking_item_util.cc deleted file mode 100644 index c224fb3e..0000000 --- a/chrome/browser/ui/app_list/search/ranking/ranking_item_util.cc +++ /dev/null
@@ -1,104 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/app_list/search/ranking/ranking_item_util.h" - -#include "ash/public/cpp/app_list/app_list_features.h" -#include "ash/public/cpp/app_list/app_list_types.h" -#include "base/metrics/field_trial_params.h" -#include "base/strings/string_util.h" -#include "chrome/browser/ui/app_list/chrome_app_list_item.h" -#include "chrome/browser/ui/app_list/search/chrome_search_result.h" -#include "components/omnibox/browser/autocomplete_match_type.h" - -namespace app_list { - -RankingItemType RankingItemTypeFromSearchResult( - const ChromeSearchResult& result) { - switch (result.result_type()) { - case ash::AppListSearchResultType::kInstalledApp: - case ash::AppListSearchResultType::kZeroStateApp: - case ash::AppListSearchResultType::kInternalApp: - case ash::AppListSearchResultType::kGames: - return RankingItemType::kApp; - case ash::AppListSearchResultType::kOmnibox: - return RankingItemType::kOmniboxGeneric; - case ash::AppListSearchResultType::kLauncher: - case ash::AppListSearchResultType::kFileSearch: - case ash::AppListSearchResultType::kDriveSearch: - return RankingItemType::kFile; - case ash::AppListSearchResultType::kUnknown: - case ash::AppListSearchResultType::kPlayStoreApp: - case ash::AppListSearchResultType::kInstantApp: - case ash::AppListSearchResultType::kAnswerCard: - case ash::AppListSearchResultType::kPlayStoreReinstallApp: - case ash::AppListSearchResultType::kOsSettings: - case ash::AppListSearchResultType::kInternalPrivacyInfo: - case ash::AppListSearchResultType::kAssistantText: - case ash::AppListSearchResultType::kPersonalization: - // Types that are only shown in the productivity launcher: - case ash::AppListSearchResultType::kHelpApp: - case ash::AppListSearchResultType::kZeroStateHelpApp: - case ash::AppListSearchResultType::kKeyboardShortcut: - case ash::AppListSearchResultType::kOpenTab: - // NOTE: We don't rank results of type kAssistantChip, kAssistantText - // as those results, if present, are shown in a dedicated slot. - return RankingItemType::kIgnored; - case ash::AppListSearchResultType::kArcAppShortcut: - return RankingItemType::kArcAppShortcut; - case ash::AppListSearchResultType::kZeroStateFile: - return RankingItemType::kZeroStateFile; - case ash::AppListSearchResultType::kZeroStateDrive: - return RankingItemType::kDriveQuickAccess; - } -} - -RankingItemType RankingItemTypeFromChromeAppListItem( - const ChromeAppListItem& item) { - return RankingItemType::kApp; -} - -std::string NormalizeAppId(const std::string& id) { - std::string app_id(id); - // No existing scheme names include the delimiter string "://". - std::size_t delimiter_index = app_id.find("://"); - if (delimiter_index != std::string::npos) - app_id.erase(0, delimiter_index + 3); - if (!app_id.empty() && app_id.back() == '/') - app_id.pop_back(); - return app_id; -} - -std::string SimplifyUrlId(const std::string& url_id) { - std::string result(url_id); - - std::size_t query_index = result.find("?"); - if (query_index != std::string::npos) - result.erase(query_index); - - std::size_t fragment_index = result.find("#"); - if (fragment_index != std::string::npos) - result.erase(fragment_index); - - if (!result.empty() && result.back() == '/' && - result.find("://") != result.size() - 3) - result.pop_back(); - - return result; -} - -std::string SimplifyGoogleDocsUrlId(const std::string& url_id) { - std::string result = SimplifyUrlId(url_id); - - // URLs that end with /view or /edit point to the same document, so should be - // the same for ranking purposes. - if (base::EndsWith(result, "/view", base::CompareCase::INSENSITIVE_ASCII) || - base::EndsWith(result, "/edit", base::CompareCase::INSENSITIVE_ASCII)) { - result = result.substr(0, result.length() - 5); - } - - return result; -} - -} // namespace app_list
diff --git a/chrome/browser/ui/app_list/search/ranking/ranking_item_util.h b/chrome/browser/ui/app_list/search/ranking/ranking_item_util.h deleted file mode 100644 index 279032d..0000000 --- a/chrome/browser/ui/app_list/search/ranking/ranking_item_util.h +++ /dev/null
@@ -1,61 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_APP_LIST_SEARCH_RANKING_RANKING_ITEM_UTIL_H_ -#define CHROME_BROWSER_UI_APP_LIST_SEARCH_RANKING_RANKING_ITEM_UTIL_H_ - -#include <string> - -class ChromeAppListItem; -class ChromeSearchResult; - -namespace app_list { - -// A simplified value describing what kind a search result should be treated as -// for the purposes of ranking. These values are persisted to logs. Entries -// should not be renumbered and numeric values should never be reused. -enum class RankingItemType { - kUnknown = 0, - kIgnored = 1, - kFile = 2, - kApp = 3, - kOmniboxGeneric = 4, - kArcAppShortcut = 5, - kZeroStateFile = 6, - kDriveQuickAccess = 7, - // Deprecated: - // kChip = 8, - kZeroStateFileChip = 9, - kDriveQuickAccessChip = 10, - // Add new types above this line. - kMaxValue = kDriveQuickAccessChip, -}; - -// Convert a |ChromeSearchResult| into its |RankingItemType|. -RankingItemType RankingItemTypeFromSearchResult( - const ChromeSearchResult& result); - -// Return the type of an |ChromeAppListItem|. We currently do not distinguish -// between different kinds of apps, and all |AppServiceAppItem|s are apps, so we -// trivially return |kApp|. -RankingItemType RankingItemTypeFromChromeAppListItem( - const ChromeAppListItem& item); - -// Normalizes app IDs by removing any scheme prefix and trailing slash: -// "arc://[id]/" to "[id]". This is necessary because apps launched from -// different parts of the launcher have differently formatted IDs. -std::string NormalizeAppId(const std::string& id); - -// Given a search result ID representing a URL, removes some components of the -// URL such as the query and fragment. This is intended to normalize URLs that -// should be considered the same for the purposes of ranking. -std::string SimplifyUrlId(const std::string& url_id); - -// Given a search result ID representing a google docs file, remove parts of the -// URL that can vary without affecting what doc the URL resolves to. -std::string SimplifyGoogleDocsUrlId(const std::string& url_id); - -} // namespace app_list - -#endif // CHROME_BROWSER_UI_APP_LIST_SEARCH_RANKING_RANKING_ITEM_UTIL_H_
diff --git a/chrome/browser/ui/app_list/search/ranking/ranking_item_util_unittest.cc b/chrome/browser/ui/app_list/search/ranking/ranking_item_util_unittest.cc deleted file mode 100644 index 8cdb121..0000000 --- a/chrome/browser/ui/app_list/search/ranking/ranking_item_util_unittest.cc +++ /dev/null
@@ -1,65 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/app_list/search/ranking/ranking_item_util.h" - -#include <memory> -#include <string> - -#include "chrome/browser/ui/app_list/app_list_test_util.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace app_list { - -TEST(RankingItemUtilTest, SimplifyUrlId) { - // Test handling different kinds of scheme, domain, and path. These should all - // be no-ops. - EXPECT_EQ(SimplifyUrlId("scheme://domain.com/path"), - "scheme://domain.com/path"); - EXPECT_EQ(SimplifyUrlId("://domain.com"), "://domain.com"); - EXPECT_EQ(SimplifyUrlId("domain.com/path"), "domain.com/path"); - EXPECT_EQ(SimplifyUrlId("domain.com:1123/path"), "domain.com:1123/path"); - EXPECT_EQ(SimplifyUrlId("://"), "://"); - - // Test removing trailing slash. - EXPECT_EQ(SimplifyUrlId("scheme://domain.com/"), "scheme://domain.com"); - EXPECT_EQ(SimplifyUrlId("scheme:///"), "scheme://"); - EXPECT_EQ(SimplifyUrlId("scheme://"), "scheme://"); - - // Test removing queries and fragments. - EXPECT_EQ(SimplifyUrlId("domain.com/path?query=query"), "domain.com/path"); - EXPECT_EQ(SimplifyUrlId("scheme://path?query=query#fragment"), - "scheme://path"); - EXPECT_EQ(SimplifyUrlId("scheme://?query=query#fragment"), "scheme://"); -} - -TEST(RankingItemUtilTest, SimplifyGoogleDocsUrlId) { - EXPECT_EQ(SimplifyGoogleDocsUrlId("docs.google.com/hash/edit?"), - "docs.google.com/hash"); - EXPECT_EQ(SimplifyGoogleDocsUrlId( - "http://docs.google.com/hash/view?query#fragment"), - "http://docs.google.com/hash"); - EXPECT_EQ(SimplifyGoogleDocsUrlId("https://docs.google.com/d/document/hash/"), - "https://docs.google.com/d/document/hash"); - - // We only want to remove one /view or /edit from the end of the URL. - EXPECT_EQ(SimplifyGoogleDocsUrlId("docs.google.com/edit/hash/view/view"), - "docs.google.com/edit/hash/view"); -} - -TEST(RankingItemUtilTest, NormalizeAppID) { - const std::string raw_id = "mgndgikekgjfcpckkfioiadnlibdjbkf"; - const std::string id_with_scheme = - "chrome-extension://mgndgikekgjfcpckkfioiadnlibdjbkf"; - const std::string id_with_slash = "mgndgikekgjfcpckkfioiadnlibdjbkf/"; - const std::string id_with_scheme_and_slash = - "chrome-extension://mgndgikekgjfcpckkfioiadnlibdjbkf/"; - - EXPECT_EQ(NormalizeAppId(raw_id), raw_id); - EXPECT_EQ(NormalizeAppId(id_with_scheme), raw_id); - EXPECT_EQ(NormalizeAppId(id_with_slash), raw_id); - EXPECT_EQ(NormalizeAppId(id_with_scheme_and_slash), raw_id); -} - -} // namespace app_list
diff --git a/chrome/browser/ui/app_list/search/search_controller.h b/chrome/browser/ui/app_list/search/search_controller.h index 2c8cf63..a298dd5 100644 --- a/chrome/browser/ui/app_list/search/search_controller.h +++ b/chrome/browser/ui/app_list/search/search_controller.h
@@ -12,7 +12,6 @@ #include <utility> #include <vector> -#include "base/callback.h" #include "base/containers/flat_map.h" #include "base/observer_list_types.h" #include "base/time/time.h" @@ -34,7 +33,6 @@ class AppSearchDataSource; class SearchProvider; -enum class RankingItemType; // Common types used throughout result ranking. // @@ -67,7 +65,7 @@ const std::vector<const ChromeSearchResult*>& results) {} }; - virtual ~SearchController() {} + virtual ~SearchController() = default; virtual void StartSearch(const std::u16string& query) = 0; virtual void ClearSearch() = 0;
diff --git a/chrome/browser/ui/app_list/search/search_controller_impl.cc b/chrome/browser/ui/app_list/search/search_controller_impl.cc index 970c5bc..0442066 100644 --- a/chrome/browser/ui/app_list/search/search_controller_impl.cc +++ b/chrome/browser/ui/app_list/search/search_controller_impl.cc
@@ -19,6 +19,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/app_list/app_list_controller_delegate.h" #include "chrome/browser/ui/app_list/app_list_model_updater.h" +#include "chrome/browser/ui/app_list/app_list_util.h" #include "chrome/browser/ui/app_list/search/app_search_data_source.h" #include "chrome/browser/ui/app_list/search/chrome_search_result.h" #include "chrome/browser/ui/app_list/search/common/string_util.h" @@ -394,17 +395,17 @@ .SetApp(last_launched_app_id_) .SetSearchQuery(query) .SetSearchQueryLength(query.size()) - .SetProviderType(static_cast<int>(launch_data.ranking_item_type)) + .SetProviderType(static_cast<int>(launch_data.result_type)) .SetHour(now_exploded.hour) .SetScore(launch_data.score) .Record(); // Only record the last launched app if the hashed logging feature flag is // enabled, because it is only used by hashed logging. - if (launch_data.ranking_item_type == RankingItemType::kApp) { + if (IsResultTypeApp(launch_data.result_type)) { last_launched_app_id_ = NormalizeId(launch_data.id); - } else if (launch_data.ranking_item_type == - RankingItemType::kArcAppShortcut) { + } else if (launch_data.result_type == + ash::AppListSearchResultType::kArcAppShortcut) { last_launched_app_id_ = RemoveAppShortcutLabel(NormalizeId(launch_data.id)); } @@ -416,7 +417,7 @@ // CrOS action recorder. CrOSActionRecorder::GetCrosActionRecorder()->RecordAction( {base::StrCat({"SearchResultLaunched-", NormalizeId(launch_data.id)})}, - {{"ResultType", static_cast<int>(launch_data.ranking_item_type)}, + {{"ResultType", static_cast<int>(launch_data.result_type)}, {"Query", static_cast<int>(base::HashMetricName(query))}}); // Train all search result ranking models.
diff --git a/chrome/browser/ui/app_list/search/search_controller_impl.h b/chrome/browser/ui/app_list/search/search_controller_impl.h index c17f49d7..e7c9559 100644 --- a/chrome/browser/ui/app_list/search/search_controller_impl.h +++ b/chrome/browser/ui/app_list/search/search_controller_impl.h
@@ -35,7 +35,6 @@ class SearchMetricsManager; class SearchProvider; -enum class RankingItemType; class SearchControllerImpl : public SearchController { public:
diff --git a/chrome/browser/ui/app_list/search/search_provider.h b/chrome/browser/ui/app_list/search/search_provider.h index 2a7fccd..8e089f3d 100644 --- a/chrome/browser/ui/app_list/search/search_provider.h +++ b/chrome/browser/ui/app_list/search/search_provider.h
@@ -13,9 +13,14 @@ class ChromeSearchResult; +namespace ash { + +enum class AppListSearchResultType; + +} // namespace ash + namespace app_list { -enum class RankingItemType; class SearchController; class SearchProvider { @@ -45,9 +50,10 @@ virtual void StopZeroState() {} // Handles training signals if necessary. A given |SearchProvider| may receive - // training signals for results of any |RankingItemType|, so it is the + // training signals for results of any |AppListSearchResultType|, so it is the // |SearchProvider|'s responsibility to check |type| and ignore if necessary. - virtual void Train(const std::string& id, RankingItemType type) {} + virtual void Train(const std::string& id, ash::AppListSearchResultType type) { + } // Returns the main result type created by this provider. virtual ash::AppListSearchResultType ResultType() const = 0;
diff --git a/chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog_controller_impl.cc b/chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog_controller_impl.cc index dc4caa5..30583fd 100644 --- a/chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog_controller_impl.cc +++ b/chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog_controller_impl.cc
@@ -84,6 +84,8 @@ bool user_closed_dialog, bool server_success) { if (user_closed_dialog) { + // `user_closed_dialog` is only true when the user clicked cancel on the + // dialog. AutofillMetrics::LogCardUnmaskAuthenticationSelectionDialogResultMetric( challenge_option_selected_ ? AutofillMetrics:: @@ -97,6 +99,13 @@ std::move(cancel_unmasking_closure_).Run(); } else if (selected_challenge_option_type_ == CardUnmaskChallengeOptionType::kSmsOtp) { + // If we have an SMS OTP challenge selected and `user_closed_dialog` is + // false, that means that the user accepted the dialog after selecting the + // SMS OTP challenge option, and we have a server response returned since we + // immediately send a SelectChallengeOption request to the server and only + // close the dialog once a response is returned. The SelectChallengeOption + // request is sent to the payments server to generate an SMS OTP with the + // bank or issuer and send it to the user. AutofillMetrics::LogCardUnmaskAuthenticationSelectionDialogResultMetric( server_success ? AutofillMetrics:: @@ -105,9 +114,18 @@ : AutofillMetrics:: CardUnmaskAuthenticationSelectionDialogResultMetric:: kDismissedByServerRequestFailure); + } else if (selected_challenge_option_type_ == + CardUnmaskChallengeOptionType::kCvc) { + // If we have a CVC challenge selected and `user_closed_dialog` is false, + // that means that the user accepted the dialog after selecting the CVC + // challenge option. `server_success` is not used in this case because we do + // not send a SelectChallengeOption request in the case of a CVC challenge + // selected, since we do not need to send the user any type of OTP. Thus, we + // immediately render the CVC input dialog. + AutofillMetrics::LogCardUnmaskAuthenticationSelectionDialogResultMetric( + AutofillMetrics::CardUnmaskAuthenticationSelectionDialogResultMetric:: + kDismissedByUserAcceptanceNoServerRequestNeeded); } - // TODO(crbug.com/1381892): Add OnDialogClosed metrics for Card Unmask Auth - // Select Dialog flow for CVC. challenge_option_selected_ = false; dialog_view_ = nullptr;
diff --git a/chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog_controller_impl_unittest.cc b/chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog_controller_impl_unittest.cc index 2950c5b..faf636e 100644 --- a/chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog_controller_impl_unittest.cc +++ b/chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog_controller_impl_unittest.cc
@@ -61,7 +61,6 @@ DialogCanceledByUserBeforeConfirmation) { base::HistogramTester histogram_tester; - DCHECK(controller()); controller()->SetSelectedChallengeOptionsForTesting( test::GetCardUnmaskChallengeOptions( {CardUnmaskChallengeOptionType::kSmsOtp, @@ -83,7 +82,6 @@ DialogCanceledByUserAfterConfirmation) { base::HistogramTester histogram_tester; - DCHECK(controller()); controller()->SetSelectedChallengeOptionsForTesting( test::GetCardUnmaskChallengeOptions( {CardUnmaskChallengeOptionType::kSmsOtp, @@ -107,7 +105,6 @@ ServerRequestSucceeded) { base::HistogramTester histogram_tester; - DCHECK(controller()); controller()->SetSelectedChallengeOptionsForTesting( test::GetCardUnmaskChallengeOptions( {CardUnmaskChallengeOptionType::kSmsOtp, @@ -131,7 +128,6 @@ ServerRequestFailed) { base::HistogramTester histogram_tester; - DCHECK(controller()); controller()->SetSelectedChallengeOptionsForTesting( test::GetCardUnmaskChallengeOptions( {CardUnmaskChallengeOptionType::kSmsOtp, @@ -153,6 +149,29 @@ } TEST_F(CardUnmaskAuthenticationSelectionDialogControllerImplTest, + AcceptedNoServerRequestNecessary) { + base::HistogramTester histogram_tester; + + controller()->SetSelectedChallengeOptionsForTesting( + test::GetCardUnmaskChallengeOptions( + {CardUnmaskChallengeOptionType::kCvc})); + controller()->SetSelectedChallengeOptionId( + controller()->GetChallengeOptions()[0].id); + EXPECT_EQ(controller()->GetChallengeOptions()[0].id, + controller()->GetSelectedChallengeOptionIdForTesting()); + + controller()->OnOkButtonClicked(); + controller()->OnDialogClosed(/*user_closed_dialog=*/false, + /*server_success=*/false); + + histogram_tester.ExpectUniqueSample( + "Autofill.CardUnmaskAuthenticationSelectionDialog.Result", + AutofillMetrics::CardUnmaskAuthenticationSelectionDialogResultMetric:: + kDismissedByUserAcceptanceNoServerRequestNeeded, + 1); +} + +TEST_F(CardUnmaskAuthenticationSelectionDialogControllerImplTest, SelectedCardUnmaskChallengeOptionType) { // Ensure the challenge option type is initialized to kUnknown. EXPECT_EQ(CardUnmaskChallengeOptionType::kUnknownType,
diff --git a/chrome/browser/ui/browser_command_controller.cc b/chrome/browser/ui/browser_command_controller.cc index f424612..a94aae9 100644 --- a/chrome/browser/ui/browser_command_controller.cc +++ b/chrome/browser/ui/browser_command_controller.cc
@@ -57,6 +57,7 @@ #include "chrome/common/webui_url_constants.h" #include "components/bookmarks/common/bookmark_pref_names.h" #include "components/dom_distiller/core/dom_distiller_features.h" +#include "components/lens/lens_features.h" #include "components/prefs/pref_service.h" #include "components/services/screen_ai/buildflags/buildflags.h" #include "components/sessions/core/tab_restore_service.h" @@ -943,6 +944,12 @@ break; #endif +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) + case IDC_CONTENT_CONTEXT_LENS_REGION_SEARCH: + ExecLensRegionSearch(browser_); + break; +#endif // BUILDFLAG(GOOGLE_CHROME_BRANDING) + default: LOG(WARNING) << "Received Unimplemented Command: " << id; break; @@ -1238,6 +1245,14 @@ true); } +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) + if (base::FeatureList::IsEnabled( + lens::features::kEnableRegionSearchKeyboardShortcut)) { + command_updater_.UpdateCommandEnabled( + IDC_CONTENT_CONTEXT_LENS_REGION_SEARCH, true); + } +#endif + // Initialize other commands whose state changes based on various conditions. UpdateCommandsForFullscreenMode(); UpdateCommandsForContentRestrictionState();
diff --git a/chrome/browser/ui/browser_commands.cc b/chrome/browser/ui/browser_commands.cc index 0bee4ce..3c7613a1 100644 --- a/chrome/browser/ui/browser_commands.cc +++ b/chrome/browser/ui/browser_commands.cc
@@ -36,6 +36,7 @@ #include "chrome/browser/media/router/media_router_feature.h" #include "chrome/browser/prefs/incognito_mode_prefs.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/search/search.h" #include "chrome/browser/sessions/session_service.h" #include "chrome/browser/sessions/session_service_base.h" #include "chrome/browser/sessions/session_service_factory.h" @@ -182,6 +183,12 @@ #include "chrome/browser/apps/intent_helper/supported_links_infobar_delegate.h" #endif +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) +#include "chrome/browser/lens/region_search/lens_region_search_controller.h" +#include "chrome/browser/lens/region_search/lens_region_search_helper.h" +#include "components/lens/lens_features.h" +#endif + namespace { const char kOsOverrideForTabletSite[] = "Linux; Android 9; Chrome tablet"; @@ -1852,4 +1859,24 @@ } #endif // BUILDFLAG(ENABLE_SCREEN_AI_SERVICE) +void ExecLensRegionSearch(Browser* browser) { +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) + Profile* profile = browser->profile(); + WebContents* contents = browser->tab_strip_model()->GetActiveWebContents(); + GURL url = contents->GetController().GetLastCommittedEntry()->GetURL(); + + if (lens::IsRegionSearchEnabled(browser, profile, url)) { + auto lens_region_search_controller_data = + std::make_unique<lens::LensRegionSearchControllerData>(); + lens_region_search_controller_data->lens_region_search_controller = + std::make_unique<lens::LensRegionSearchController>(browser); + lens_region_search_controller_data->lens_region_search_controller->Start( + contents, lens::features::IsLensFullscreenSearchEnabled(), + search::DefaultSearchProviderIsGoogle(profile)); + browser->SetUserData(lens::LensRegionSearchControllerData::kDataKey, + std::move(lens_region_search_controller_data)); + } +#endif // BUILDFLAG(GOOGLE_CHROME_BRANDING) +} + } // namespace chrome
diff --git a/chrome/browser/ui/browser_commands.h b/chrome/browser/ui/browser_commands.h index de5f483b..e8532e9 100644 --- a/chrome/browser/ui/browser_commands.h +++ b/chrome/browser/ui/browser_commands.h
@@ -257,6 +257,8 @@ void RunScreenAIVisualAnnotation(Browser* browser); #endif // BUILDFLAG(ENABLE_SCREEN_AI_SERVICE) +void ExecLensRegionSearch(Browser* browser); + } // namespace chrome #endif // CHROME_BROWSER_UI_BROWSER_COMMANDS_H_
diff --git a/chrome/browser/ui/startup/startup_browser_creator.cc b/chrome/browser/ui/startup/startup_browser_creator.cc index 475cbdc..865330d 100644 --- a/chrome/browser/ui/startup/startup_browser_creator.cc +++ b/chrome/browser/ui/startup/startup_browser_creator.cc
@@ -117,6 +117,7 @@ #endif #if BUILDFLAG(IS_MAC) +#include "chrome/browser/web_applications/app_shim_registry_mac.h" #include "chrome/browser/web_applications/extensions/web_app_extension_shortcut_mac.h" #endif @@ -1248,9 +1249,16 @@ // On Chrome OS, app launches are routed through the AppService and // WebAppPublisherHelper. // - // On Mac, PWA launch is handled in web_app_shim_manager_delegate_mac.cc, but - // tests still rely on this code. - // TODO(crbug.com/1232763): update tests and disable this path on Mac. + // On Mac, PWA launch is normally handled in + // web_app_shim_manager_delegate_mac.cc, but if an app shim for whatever + // reason fails to dlopen chrome we can still end up here. While in that case + // the launch behavior here isn't quite the correct behavior for an app launch + // on Mac OS, this behavior is better than nothing and should result in the + // app shim getting regenerated to hopefully fix future app launches. + // TODO(https://crbug.com/1232763): Some integration tests also rely on this + // code. Ideally those would be fixed to test the normal app launch path on + // Mac instead, and this code should be changed to make it harder to + // accidentally write tests that don't test the normal app launch path. #if !BUILDFLAG(IS_CHROMEOS_ASH) // Try a web app launch. if (web_app::startup::MaybeHandleWebAppLaunch( @@ -1479,9 +1487,27 @@ } #endif // BUILDFLAG(IS_CHROMEOS_LACROS) - if (command_line.HasSwitch(switches::kProfileDirectory)) { - return {user_data_dir.Append( - command_line.GetSwitchValuePath(switches::kProfileDirectory)), + base::FilePath profile_directory = + command_line.GetSwitchValuePath(switches::kProfileDirectory); +#if BUILDFLAG(IS_MAC) + // On Mac OS, when an app shim fails to dlopen chrome, the app shim falls back + // to trying to launch chrome passing its app-id on the command line. In this + // situation, the profile directory passed on the command line could be an + // empty string. When this happens, arbitrarily pick one of the profiles the + // app is installed in as profile directory. While this isn't necesarilly the + // right profile to use, it is good enough for the purpose of (indirectly) + // triggering a rebuild of the app shim, which should resolve whatever + // problem existed that let to this situation. + if (profile_directory.empty() && command_line.HasSwitch(switches::kAppId)) { + std::string app_id = command_line.GetSwitchValueASCII(switches::kAppId); + std::set<base::FilePath> profile_paths = + AppShimRegistry::Get()->GetInstalledProfilesForApp(app_id); + if (!profile_paths.empty()) + profile_directory = profile_paths.begin()->BaseName(); + } +#endif + if (!profile_directory.empty()) { + return {user_data_dir.Append(profile_directory), StartupProfileMode::kBrowserWindow}; }
diff --git a/chrome/browser/ui/views/BUILD.gn b/chrome/browser/ui/views/BUILD.gn index 17d061a..9c07f25 100644 --- a/chrome/browser/ui/views/BUILD.gn +++ b/chrome/browser/ui/views/BUILD.gn
@@ -32,6 +32,7 @@ "//chrome/app:command_ids", "//chrome/app:generated_resources", "//components/keep_alive_registry", + "//components/lens", "//components/services/app_service/public/mojom", "//components/services/screen_ai/buildflags", "//components/vector_icons",
diff --git a/chrome/browser/ui/views/accelerator_table.cc b/chrome/browser/ui/views/accelerator_table.cc index a3ecd7f..c441600 100644 --- a/chrome/browser/ui/views/accelerator_table.cc +++ b/chrome/browser/ui/views/accelerator_table.cc
@@ -16,6 +16,7 @@ #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "chrome/app/chrome_command_ids.h" +#include "components/lens/lens_features.h" #include "components/services/screen_ai/buildflags/buildflags.h" #include "printing/buildflags/buildflags.h" #include "ui/base/accelerators/accelerator.h" @@ -262,6 +263,16 @@ }; #endif +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) +// Accelerators to enable if lens::features::kEnableRegionSearchKeyboardShortcut +// is true. +constexpr AcceleratorMapping kRegionSearchAcceleratorMap[] = { + // TODO(nguyenbryan): This is a temporary hotkey; update when finalized. + {ui::VKEY_L, ui::EF_SHIFT_DOWN | ui::EF_PLATFORM_ACCELERATOR, + IDC_CONTENT_CONTEXT_LENS_REGION_SEARCH}, +}; +#endif // BUILDFLAG(GOOGLE_CHROME_BRANDING) + constexpr int kDebugModifier = ui::EF_CONTROL_DOWN | ui::EF_ALT_DOWN | ui::EF_SHIFT_DOWN; @@ -307,6 +318,15 @@ } #endif +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) + if (base::FeatureList::IsEnabled( + lens::features::kEnableRegionSearchKeyboardShortcut)) { + accelerators->insert(accelerators->begin(), + std::begin(kRegionSearchAcceleratorMap), + std::end(kRegionSearchAcceleratorMap)); + } +#endif // BUILDFLAG(GOOGLE_CHROME_BRANDING) + if (base::FeatureList::IsEnabled(features::kUIDebugTools)) { accelerators->insert(accelerators->begin(), std::begin(kUIDebugAcceleratorMap),
diff --git a/chrome/browser/ui/views/autofill/payments/card_unmask_authentication_selection_dialog_browsertest.cc b/chrome/browser/ui/views/autofill/payments/card_unmask_authentication_selection_dialog_browsertest.cc index b5180df..2e1e34e 100644 --- a/chrome/browser/ui/views/autofill/payments/card_unmask_authentication_selection_dialog_browsertest.cc +++ b/chrome/browser/ui/views/autofill/payments/card_unmask_authentication_selection_dialog_browsertest.cc
@@ -18,26 +18,14 @@ namespace autofill { -// Parameters of the CardUnmaskAuthenticationSelectionDialogBrowserTest. -using ChallengeOptionTypes = std::vector<CardUnmaskChallengeOptionType>; -using EnableCvcForVcnYellowPathIsEnabled = bool; - -class CardUnmaskAuthenticationSelectionDialogBrowserTest - : public DialogBrowserTest, - public testing::WithParamInterface< - std::tuple<ChallengeOptionTypes, - EnableCvcForVcnYellowPathIsEnabled>> { +class CardUnmaskAuthenticationSelectionDialogBrowserTestBase + : public DialogBrowserTest { public: - CardUnmaskAuthenticationSelectionDialogBrowserTest() { - feature_list_.InitWithFeatureState( - /*feature=*/features::kAutofillEnableCvcForVcnYellowPath, - /*enabled=*/GetEnableCvcForVcnYellowPathIsEnabled()); - } - - CardUnmaskAuthenticationSelectionDialogBrowserTest( - const CardUnmaskAuthenticationSelectionDialogBrowserTest&) = delete; - CardUnmaskAuthenticationSelectionDialogBrowserTest& operator=( - const CardUnmaskAuthenticationSelectionDialogBrowserTest&) = delete; + CardUnmaskAuthenticationSelectionDialogBrowserTestBase() = default; + CardUnmaskAuthenticationSelectionDialogBrowserTestBase( + const CardUnmaskAuthenticationSelectionDialogBrowserTestBase&) = delete; + CardUnmaskAuthenticationSelectionDialogBrowserTestBase& operator=( + const CardUnmaskAuthenticationSelectionDialogBrowserTestBase&) = delete; // DialogBrowserTest: void ShowUi(const std::string& name) override { @@ -48,7 +36,7 @@ CardUnmaskAuthenticationSelectionDialogControllerImpl::CreateForWebContents( web_contents); controller()->ShowDialog( - challenge_options_list_, + challenge_options_, /*confirm_unmasking_method_callback=*/base::DoNothing(), /*cancel_unmasking_closure=*/base::DoNothing()); } @@ -66,9 +54,13 @@ dialog_view); } - void SetChallengeOptionList( - std::vector<CardUnmaskChallengeOption> challenge_options_list) { - challenge_options_list_ = challenge_options_list; + void SetChallengeOptions( + std::vector<CardUnmaskChallengeOption> challenge_options) { + challenge_options_ = std::move(challenge_options); + } + + const std::vector<CardUnmaskChallengeOption>& GetChallengeOptions() { + return challenge_options_; } CardUnmaskAuthenticationSelectionDialogControllerImpl* controller() { @@ -80,6 +72,81 @@ FromWebContents(browser()->tab_strip_model()->GetActiveWebContents()); } + protected: + std::vector<CardUnmaskChallengeOption> challenge_options_; +}; + +// Non-parameterized version of +// CardUnmaskAuthenticationSelectionDialogBrowserTestBase. Should be used to +// test the specific functionality of a certain type of challenge option being +// selected, instead of the overall functionality of the dialog. +// TODO(crbug.com/1392940): Add browser tests for specific SMS OTP challenge +// selection logging. +class CardUnmaskAuthenticationSelectionDialogBrowserTestNonParameterized + : public CardUnmaskAuthenticationSelectionDialogBrowserTestBase { + public: + CardUnmaskAuthenticationSelectionDialogBrowserTestNonParameterized() { + feature_list_.InitAndEnableFeature( + features::kAutofillEnableCvcForVcnYellowPath); + } + + private: + base::test::ScopedFeatureList feature_list_; +}; + +// Ensure accepting the CVC challenge option in the selection dialog is +// correctly handled. +IN_PROC_BROWSER_TEST_F( + CardUnmaskAuthenticationSelectionDialogBrowserTestNonParameterized, + AcceptedByUserAfterSelectingCvcAuthResultsMetricsLoggedAsExpected) { + base::HistogramTester histogram_tester; + SetChallengeOptions(test::GetCardUnmaskChallengeOptions( + std::vector<CardUnmaskChallengeOptionType>{ + CardUnmaskChallengeOptionType::kSmsOtp, + CardUnmaskChallengeOptionType::kCvc})); + ShowUi(""); + VerifyUi(); + + // Select the CVC challenge option in the dialog. + auto cvc_challenge_option = base::ranges::find_if( + GetChallengeOptions(), [](const auto& challenge_option) { + return challenge_option.type == CardUnmaskChallengeOptionType::kCvc; + }); + controller()->SetSelectedChallengeOptionId(cvc_challenge_option->id); + + // Accept the authentication selection dialog with the CVC challenge option + // chosen. + GetDialog()->Accept(); + base::RunLoop().RunUntilIdle(); + + histogram_tester.ExpectUniqueSample( + "Autofill.CardUnmaskAuthenticationSelectionDialog.Result", + AutofillMetrics::CardUnmaskAuthenticationSelectionDialogResultMetric:: + kDismissedByUserAcceptanceNoServerRequestNeeded, + 1); +} + +// Parameters of the +// CardUnmaskAuthenticationSelectionDialogBrowserTestParameterized. +using ChallengeOptionTypes = std::vector<CardUnmaskChallengeOptionType>; +using EnableCvcForVcnYellowPathIsEnabled = bool; + +// Parameterized version of +// CardUnmaskAuthenticationSelectionDialogBrowserTestBase. Should be used to +// test the overall functionality of the dialog, across all combinations of +// challenge options and flags related to the dialog. +class CardUnmaskAuthenticationSelectionDialogBrowserTestParameterized + : public CardUnmaskAuthenticationSelectionDialogBrowserTestBase, + public testing::WithParamInterface< + std::tuple<ChallengeOptionTypes, + EnableCvcForVcnYellowPathIsEnabled>> { + public: + CardUnmaskAuthenticationSelectionDialogBrowserTestParameterized() { + feature_list_.InitWithFeatureState( + /*feature=*/features::kAutofillEnableCvcForVcnYellowPath, + /*enabled=*/GetEnableCvcForVcnYellowPathIsEnabled()); + } + ChallengeOptionTypes GetChallengeOptionTypes() { return std::get<0>(GetParam()); } @@ -89,13 +156,12 @@ } private: - std::vector<CardUnmaskChallengeOption> challenge_options_list_; base::test::ScopedFeatureList feature_list_; }; INSTANTIATE_TEST_SUITE_P( , - CardUnmaskAuthenticationSelectionDialogBrowserTest, + CardUnmaskAuthenticationSelectionDialogBrowserTestParameterized, testing::Combine(testing::Values( std::vector<CardUnmaskChallengeOptionType>{ CardUnmaskChallengeOptionType::kSmsOtp}, @@ -105,10 +171,11 @@ testing::Bool())); // Ensures the UI can be shown. -IN_PROC_BROWSER_TEST_P(CardUnmaskAuthenticationSelectionDialogBrowserTest, - InvokeUi_CardUnmaskAuthSelectionDialogDisplays) { +IN_PROC_BROWSER_TEST_P( + CardUnmaskAuthenticationSelectionDialogBrowserTestParameterized, + InvokeUi_CardUnmaskAuthSelectionDialogDisplays) { base::HistogramTester histogram_tester; - SetChallengeOptionList( + SetChallengeOptions( test::GetCardUnmaskChallengeOptions(GetChallengeOptionTypes())); ShowAndVerifyUi(); EXPECT_THAT( @@ -124,10 +191,11 @@ } // Ensures closing tab while dialog being visible is correctly handled. -IN_PROC_BROWSER_TEST_P(CardUnmaskAuthenticationSelectionDialogBrowserTest, - CanCloseTabWhileDialogShowing) { +IN_PROC_BROWSER_TEST_P( + CardUnmaskAuthenticationSelectionDialogBrowserTestParameterized, + CanCloseTabWhileDialogShowing) { base::HistogramTester histogram_tester; - SetChallengeOptionList( + SetChallengeOptions( test::GetCardUnmaskChallengeOptions(GetChallengeOptionTypes())); ShowUi(""); VerifyUi(); @@ -151,10 +219,11 @@ } // Ensures closing browser while dialog being visible is correctly handled. -IN_PROC_BROWSER_TEST_P(CardUnmaskAuthenticationSelectionDialogBrowserTest, - CanCloseBrowserWhileDialogShowing) { +IN_PROC_BROWSER_TEST_P( + CardUnmaskAuthenticationSelectionDialogBrowserTestParameterized, + CanCloseBrowserWhileDialogShowing) { base::HistogramTester histogram_tester; - SetChallengeOptionList( + SetChallengeOptions( test::GetCardUnmaskChallengeOptions(GetChallengeOptionTypes())); ShowUi(""); VerifyUi(); @@ -179,10 +248,10 @@ // Ensure cancelling dialog is correctly handled. IN_PROC_BROWSER_TEST_P( - CardUnmaskAuthenticationSelectionDialogBrowserTest, + CardUnmaskAuthenticationSelectionDialogBrowserTestParameterized, CanceledByUserAfterSelectionResultsMetricsLoggedAsExpected) { base::HistogramTester histogram_tester; - SetChallengeOptionList( + SetChallengeOptions( test::GetCardUnmaskChallengeOptions(GetChallengeOptionTypes())); ShowUi(""); VerifyUi();
diff --git a/chrome/browser/ui/views/renderer_context_menu/render_view_context_menu_views.cc b/chrome/browser/ui/views/renderer_context_menu/render_view_context_menu_views.cc index 649e6058..cadcd10 100644 --- a/chrome/browser/ui/views/renderer_context_menu/render_view_context_menu_views.cc +++ b/chrome/browser/ui/views/renderer_context_menu/render_view_context_menu_views.cc
@@ -8,6 +8,7 @@ #include <utility> #include "base/command_line.h" +#include "base/feature_list.h" #include "base/logging.h" #include "base/memory/raw_ptr.h" #include "base/observer_list.h" @@ -21,6 +22,7 @@ #include "chrome/browser/ui/views/side_panel/side_panel_coordinator.h" #include "chrome/common/chrome_switches.h" #include "chrome/grit/generated_resources.h" +#include "components/lens/lens_features.h" #include "components/renderer_context_menu/views/toolkit_delegate_views.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host.h" @@ -209,6 +211,20 @@ *accel = ui::Accelerator(ui::VKEY_S, ui::EF_CONTROL_DOWN); return true; +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) + case IDC_CONTENT_CONTEXT_LENS_REGION_SEARCH: + case IDC_CONTENT_CONTEXT_WEB_REGION_SEARCH: + if (base::FeatureList::IsEnabled( + lens::features::kEnableRegionSearchKeyboardShortcut)) { + // TODO(nguyenbryan): This is a temporary hotkey; update when finalized. + *accel = ui::Accelerator(ui::VKEY_L, + ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN); + return true; + } else { + return false; + } +#endif // BUILDFLAG(GOOGLE_CHROME_BRANDING) + case IDC_CONTENT_CONTEXT_EXIT_FULLSCREEN: { // Esc only works in HTML5 (site-triggered) fullscreen. if (IsHTML5Fullscreen()) {
diff --git a/chrome/browser/ui/views/side_panel/read_anything/read_anything_controller.cc b/chrome/browser/ui/views/side_panel/read_anything/read_anything_controller.cc index d474fd08..9fe89c1 100644 --- a/chrome/browser/ui/views/side_panel/read_anything/read_anything_controller.cc +++ b/chrome/browser/ui/views/side_panel/read_anything/read_anything_controller.cc
@@ -77,8 +77,8 @@ return model_->GetColorsModel(); } -ui::ColorId ReadAnythingController::GetForegroundColorId() { - return model_->GetForegroundColorId(); +void ReadAnythingController::SetIconColorIds(ui::ColorId color_id) { + return model_->SetIconColorIds(color_id); } void ReadAnythingController::OnLineSpacingChanged(int new_index) {
diff --git a/chrome/browser/ui/views/side_panel/read_anything/read_anything_controller.h b/chrome/browser/ui/views/side_panel/read_anything/read_anything_controller.h index 0fd1ca0..ee4ad09a 100644 --- a/chrome/browser/ui/views/side_panel/read_anything/read_anything_controller.h +++ b/chrome/browser/ui/views/side_panel/read_anything/read_anything_controller.h
@@ -60,7 +60,7 @@ void OnFontSizeChanged(bool increase) override; void OnColorsChanged(int new_index) override; ui::ComboboxModel* GetColorsModel() override; - ui::ColorId GetForegroundColorId() override; + void SetIconColorIds(ui::ColorId color_id) override; void OnLineSpacingChanged(int new_index) override; ui::ComboboxModel* GetLineSpacingModel() override; void OnLetterSpacingChanged(int new_index) override;
diff --git a/chrome/browser/ui/views/side_panel/read_anything/read_anything_model.cc b/chrome/browser/ui/views/side_panel/read_anything/read_anything_model.cc index afa29b86..5a825f0 100644 --- a/chrome/browser/ui/views/side_panel/read_anything/read_anything_model.cc +++ b/chrome/browser/ui/views/side_panel/read_anything/read_anything_model.cc
@@ -11,12 +11,9 @@ #include "base/containers/contains.h" #include "base/ranges/algorithm.h" #include "base/strings/stringprintf.h" -#include "base/strings/utf_string_conversions.h" #include "chrome/app/vector_icons/vector_icons.h" -#include "chrome/browser/ui/views/side_panel/read_anything/read_anything_constants.h" #include "chrome/grit/component_extension_resources.h" #include "chrome/grit/generated_resources.h" -#include "third_party/skia/include/core/SkColor.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/models/image_model.h" #include "ui/base/resource/resource_bundle.h" @@ -24,7 +21,6 @@ #include "ui/gfx/image/image_skia_operations.h" #include "ui/gfx/paint_vector_icon.h" -using read_anything::mojom::ReadAnythingTheme; using read_anything::mojom::Spacing; ReadAnythingModel::ReadAnythingModel() @@ -69,8 +65,8 @@ colors_combobox_index_ = colors_model_->GetStartingStateIndex(); auto& initial_colors = colors_model_->GetColorsAt(colors_combobox_index_); - foreground_color_ = initial_colors.foreground; - background_color_ = initial_colors.background; + foreground_color_id_ = initial_colors.foreground_color_id; + background_color_id_ = initial_colors.background_color_id; SetIconColorIds(initial_colors.foreground_color_id); line_spacing = line_spacing_model_->GetLineSpacingAt( @@ -103,9 +99,8 @@ colors_combobox_index_ = new_index; auto& new_colors = colors_model_->GetColorsAt(new_index); - foreground_color_ = new_colors.foreground; - background_color_ = new_colors.background; - SetIconColorIds(new_colors.foreground_color_id); + foreground_color_id_ = new_colors.foreground_color_id; + background_color_id_ = new_colors.background_color_id; NotifyThemeChanged(); } @@ -116,13 +111,6 @@ letter_spacing_model_->SetIconColorId(color_id); } -ui::ColorId ReadAnythingModel::GetForegroundColorId() { - // Check that the index is valid. - DCHECK(colors_model_->IsValidColorsIndex(colors_combobox_index_)); - - return colors_model_->GetForegroundColorId(colors_combobox_index_); -} - void ReadAnythingModel::SetSelectedLineSpacingByIndex(size_t new_index) { // Check that the index is valid. DCHECK(line_spacing_model_->IsValidLineSpacingIndex(new_index)); @@ -183,9 +171,9 @@ void ReadAnythingModel::NotifyThemeChanged() { for (Observer& obs : observers_) { - obs.OnReadAnythingThemeChanged(ReadAnythingTheme::New( - font_name_, font_scale_, foreground_color_, background_color_, - line_spacing_, letter_spacing_)); + obs.OnReadAnythingThemeChanged(font_name_, font_scale_, + foreground_color_id_, background_color_id_, + line_spacing_, letter_spacing_); } } @@ -263,22 +251,21 @@ ReadAnythingColorsModel::ReadAnythingColorsModel() { // Define the possible sets of colors available to the user. - // TODO (crbug.com/1266555): Define default colors from system theme. ColorInfo kDefaultColors = {u"Default", IDS_READ_ANYTHING_DEFAULT_PNG, - gfx::kGoogleGrey800, gfx::kGoogleGrey050, - ui::kColorReadAnythingForegroundLight}; + ui::kColorReadAnythingForeground, + ui::kColorReadAnythingBackground}; ColorInfo kLightColors = {u"Light", IDS_READ_ANYTHING_LIGHT_PNG, - gfx::kGoogleGrey800, gfx::kGoogleGrey050, - ui::kColorReadAnythingForegroundLight}; + ui::kColorReadAnythingForegroundLight, + ui::kColorReadAnythingBackgroundLight}; ColorInfo kDarkColors = {u"Dark", IDS_READ_ANYTHING_DARK_PNG, - gfx::kGoogleGrey200, gfx::kGoogleGrey900, - ui::kColorReadAnythingForegroundDark}; + ui::kColorReadAnythingForegroundDark, + ui::kColorReadAnythingBackgroundDark}; ColorInfo kYellowColors = {u"Yellow", IDS_READ_ANYTHING_YELLOW_PNG, - gfx::kGoogleGrey800, gfx::kGoogleYellow200, - ui::kColorReadAnythingForegroundYellow}; + ui::kColorReadAnythingForegroundYellow, + ui::kColorReadAnythingBackgroundYellow}; colors_choices_.emplace_back(kDefaultColors); colors_choices_.emplace_back(kLightColors); @@ -299,10 +286,6 @@ return colors_choices_[index]; } -ui::ColorId ReadAnythingColorsModel::GetForegroundColorId(size_t index) { - return GetColorsAt(index).foreground_color_id; -} - absl::optional<size_t> ReadAnythingColorsModel::GetDefaultIndex() const { return default_index_; }
diff --git a/chrome/browser/ui/views/side_panel/read_anything/read_anything_model.h b/chrome/browser/ui/views/side_panel/read_anything/read_anything_model.h index 4ee4909..379083f 100644 --- a/chrome/browser/ui/views/side_panel/read_anything/read_anything_model.h +++ b/chrome/browser/ui/views/side_panel/read_anything/read_anything_model.h
@@ -11,13 +11,16 @@ #include "base/observer_list.h" #include "base/observer_list_types.h" +#include "base/strings/utf_string_conversions.h" +#include "chrome/browser/ui/views/side_panel/read_anything/read_anything_constants.h" #include "chrome/common/accessibility/read_anything.mojom.h" -#include "third_party/skia/include/core/SkColor.h" #include "ui/accessibility/ax_node_id_forward.h" #include "ui/accessibility/ax_tree_update.h" #include "ui/base/models/combobox_model.h" #include "ui/color/color_id.h" +using read_anything::mojom::Spacing; + /////////////////////////////////////////////////////////////////////////////// // ReadAnythingFontModel // @@ -77,19 +80,15 @@ int icon_asset; // The foreground color, used for text and icon hints. - SkColor foreground; + ui::ColorId foreground_color_id; // The background color, used for text background. - SkColor background; - - // The foreground color as a ColorId, used for separators. - ui::ColorId foreground_color_id; + ui::ColorId background_color_id; }; bool IsValidColorsIndex(size_t index); void SetDefaultColorsIndexFromPref(size_t index); ColorInfo& GetColorsAt(size_t index); - ui::ColorId GetForegroundColorId(size_t index); void SetIconColorId(ui::ColorId color_id); // Simple pass-through method so Init can set the starting state colors. @@ -220,7 +219,12 @@ const ui::AXTreeUpdate& snapshot, const std::vector<ui::AXNodeID>& content_node_ids) {} virtual void OnReadAnythingThemeChanged( - read_anything::mojom::ReadAnythingThemePtr new_theme) = 0; + std::string& font_name, + double font_scale, + ui::ColorId foreground_color_id, + ui::ColorId background_color_id, + read_anything::mojom::Spacing line_spacing, + read_anything::mojom::Spacing letter_spacing) = 0; }; ReadAnythingModel(); @@ -244,6 +248,7 @@ double GetValidFontScale(double font_scale); void DecreaseTextSize(); void IncreaseTextSize(); + void SetIconColorIds(ui::ColorId color_id); void SetSelectedColorsByIndex(size_t new_index); void SetSelectedLineSpacingByIndex(size_t new_index); void SetSelectedLetterSpacingByIndex(size_t new_index); @@ -251,7 +256,6 @@ ReadAnythingFontModel* GetFontModel() { return font_model_.get(); } double GetFontScale() { return font_scale_; } ReadAnythingColorsModel* GetColorsModel() { return colors_model_.get(); } - ui::ColorId GetForegroundColorId(); ReadAnythingLineSpacingModel* GetLineSpacingModel() { return line_spacing_model_.get(); } @@ -262,23 +266,22 @@ private: void NotifyAXTreeDistilled(); void NotifyThemeChanged(); - void SetIconColorIds(ui::ColorId color_id); // State: // Members of read_anything::mojom::ReadAnythingTheme: - std::string font_name_; - SkColor foreground_color_; - SkColor background_color_; + std::string font_name_ = kReadAnythingDefaultFontName; + ui::ColorId foreground_color_id_ = ui::kColorReadAnythingForeground; + ui::ColorId background_color_id_ = ui::kColorReadAnythingBackground; // A scale multiplier for font size (internal use only, not shown to user). - float font_scale_; + float font_scale_ = kReadAnythingDefaultFontScale; - read_anything::mojom::Spacing line_spacing_; - read_anything::mojom::Spacing letter_spacing_; + read_anything::mojom::Spacing line_spacing_ = Spacing::kDefault; + read_anything::mojom::Spacing letter_spacing_ = Spacing::kDefault; // Currently selected index for colors combobox - int colors_combobox_index_; + int colors_combobox_index_ = 0; // TODO(crbug.com/1266555): Use |snapshot_| and |content_node_ids_| to keep // scrolls in sync.
diff --git a/chrome/browser/ui/views/side_panel/read_anything/read_anything_model_unittest.cc b/chrome/browser/ui/views/side_panel/read_anything/read_anything_model_unittest.cc index d86a793..2604935 100644 --- a/chrome/browser/ui/views/side_panel/read_anything/read_anything_model_unittest.cc +++ b/chrome/browser/ui/views/side_panel/read_anything/read_anything_model_unittest.cc
@@ -14,7 +14,6 @@ #include "ui/accessibility/accessibility_features.h" -using read_anything::mojom::ReadAnythingThemePtr; using testing::_; using testing::FloatNear; @@ -27,7 +26,12 @@ (override)); MOCK_METHOD(void, OnReadAnythingThemeChanged, - (ReadAnythingThemePtr new_theme), + (std::string & font_name, + double font_scale, + ui::ColorId foreground_color_id, + ui::ColorId background_color_id, + read_anything::mojom::Spacing line_spacing, + read_anything::mojom::Spacing letter_spacing), (override)); }; @@ -63,10 +67,12 @@ model_->AddObserver(&model_observer_1_); EXPECT_CALL(model_observer_1_, OnAXTreeDistilled(_, _)).Times(0); - EXPECT_CALL(model_observer_1_, OnReadAnythingThemeChanged(_)).Times(1); + EXPECT_CALL(model_observer_1_, OnReadAnythingThemeChanged(_, _, _, _, _, _)) + .Times(1); EXPECT_CALL(model_observer_2_, OnAXTreeDistilled(_, _)).Times(0); - EXPECT_CALL(model_observer_2_, OnReadAnythingThemeChanged(_)).Times(1); + EXPECT_CALL(model_observer_2_, OnReadAnythingThemeChanged(_, _, _, _, _, _)) + .Times(1); model_->AddObserver(&model_observer_2_); } @@ -76,13 +82,16 @@ model_->AddObserver(&model_observer_2_); EXPECT_CALL(model_observer_1_, OnAXTreeDistilled(_, _)).Times(0); - EXPECT_CALL(model_observer_1_, OnReadAnythingThemeChanged(_)).Times(1); + EXPECT_CALL(model_observer_1_, OnReadAnythingThemeChanged(_, _, _, _, _, _)) + .Times(1); EXPECT_CALL(model_observer_2_, OnAXTreeDistilled(_, _)).Times(0); - EXPECT_CALL(model_observer_2_, OnReadAnythingThemeChanged(_)).Times(0); + EXPECT_CALL(model_observer_2_, OnReadAnythingThemeChanged(_, _, _, _, _, _)) + .Times(0); EXPECT_CALL(model_observer_3_, OnAXTreeDistilled(_, _)).Times(0); - EXPECT_CALL(model_observer_3_, OnReadAnythingThemeChanged(_)).Times(1); + EXPECT_CALL(model_observer_3_, OnReadAnythingThemeChanged(_, _, _, _, _, _)) + .Times(1); model_->RemoveObserver(&model_observer_2_); model_->AddObserver(&model_observer_3_); @@ -91,7 +100,8 @@ TEST_F(ReadAnythingModelTest, NotificationsOnSetSelectedFontIndex) { model_->AddObserver(&model_observer_1_); - EXPECT_CALL(model_observer_1_, OnReadAnythingThemeChanged(_)).Times(1); + EXPECT_CALL(model_observer_1_, OnReadAnythingThemeChanged(_, _, _, _, _, _)) + .Times(1); model_->SetSelectedFontByIndex(2); } @@ -110,7 +120,8 @@ TEST_F(ReadAnythingModelTest, NotificationsOnDecreasedFontSize) { model_->AddObserver(&model_observer_1_); - EXPECT_CALL(model_observer_1_, OnReadAnythingThemeChanged(_)).Times(1); + EXPECT_CALL(model_observer_1_, OnReadAnythingThemeChanged(_, _, _, _, _, _)) + .Times(1); model_->DecreaseTextSize(); @@ -120,7 +131,8 @@ TEST_F(ReadAnythingModelTest, NotificationsOnIncreasedFontSize) { model_->AddObserver(&model_observer_1_); - EXPECT_CALL(model_observer_1_, OnReadAnythingThemeChanged(_)).Times(1); + EXPECT_CALL(model_observer_1_, OnReadAnythingThemeChanged(_, _, _, _, _, _)) + .Times(1); model_->IncreaseTextSize(); @@ -130,7 +142,8 @@ TEST_F(ReadAnythingModelTest, NotificationsOnSetSelectedColorsIndex) { model_->AddObserver(&model_observer_1_); - EXPECT_CALL(model_observer_1_, OnReadAnythingThemeChanged(_)).Times(1); + EXPECT_CALL(model_observer_1_, OnReadAnythingThemeChanged(_, _, _, _, _, _)) + .Times(1); model_->SetSelectedColorsByIndex(2); } @@ -138,7 +151,8 @@ TEST_F(ReadAnythingModelTest, NotificationsOnSetSelectedLineSpacingIndex) { model_->AddObserver(&model_observer_1_); - EXPECT_CALL(model_observer_1_, OnReadAnythingThemeChanged(_)).Times(1); + EXPECT_CALL(model_observer_1_, OnReadAnythingThemeChanged(_, _, _, _, _, _)) + .Times(1); model_->SetSelectedLineSpacingByIndex(2); } @@ -146,7 +160,8 @@ TEST_F(ReadAnythingModelTest, NotificationsOnSetSelectedLetterSpacingIndex) { model_->AddObserver(&model_observer_1_); - EXPECT_CALL(model_observer_1_, OnReadAnythingThemeChanged(_)).Times(1); + EXPECT_CALL(model_observer_1_, OnReadAnythingThemeChanged(_, _, _, _, _, _)) + .Times(1); model_->SetSelectedLetterSpacingByIndex(2); }
diff --git a/chrome/browser/ui/views/side_panel/read_anything/read_anything_toolbar_view.cc b/chrome/browser/ui/views/side_panel/read_anything/read_anything_toolbar_view.cc index 2661d9b..13e467d 100644 --- a/chrome/browser/ui/views/side_panel/read_anything/read_anything_toolbar_view.cc +++ b/chrome/browser/ui/views/side_panel/read_anything/read_anything_toolbar_view.cc
@@ -113,6 +113,12 @@ coordinator_->AddModelObserver(this); } +// After this view is added to the widget, we have access to the color provider +// to apply the initial theme skcolors. +void ReadAnythingToolbarView::AddedToWidget() { + ChangeColorsCallback(); +} + void ReadAnythingToolbarView::DecreaseFontSizeCallback() { if (delegate_) delegate_->OnFontSizeChanged(/* increase = */ false); @@ -149,26 +155,41 @@ } void ReadAnythingToolbarView::OnReadAnythingThemeChanged( - read_anything::mojom::ReadAnythingThemePtr new_theme) { - SetBackground(views::CreateSolidBackground(new_theme->background_color)); + std::string& font_name, + double font_scale, + ui::ColorId foreground_color_id, + ui::ColorId background_color_id, + read_anything::mojom::Spacing line_spacing, + read_anything::mojom::Spacing letter_spacing) { + if (!GetColorProvider()) + return; + + const SkColor background_skcolor = + GetColorProvider()->GetColor(background_color_id); + const SkColor foreground_skcolor = + GetColorProvider()->GetColor(foreground_color_id); + + SetBackground(views::CreateSolidBackground(background_skcolor)); font_combobox_->SetBackground( - views::CreateSolidBackground(new_theme->background_color)); + views::CreateSolidBackground(background_skcolor)); colors_combobox_->SetBackground( - views::CreateSolidBackground(new_theme->background_color)); + views::CreateSolidBackground(background_skcolor)); lines_combobox_->SetBackground( - views::CreateSolidBackground(new_theme->background_color)); + views::CreateSolidBackground(background_skcolor)); letter_spacing_combobox_->SetBackground( - views::CreateSolidBackground(new_theme->background_color)); + views::CreateSolidBackground(background_skcolor)); decrease_text_size_button_->UpdateIcon(kTextDecreaseIcon, kSmallIconSize, - new_theme->foreground_color); + foreground_skcolor); increase_text_size_button_->UpdateIcon(kTextIncreaseIcon, kLargeIconSize, - new_theme->foreground_color); + foreground_skcolor); for (views::Separator* separator : separators_) { - separator->SetColorId(delegate_->GetForegroundColorId()); + separator->SetColorId(foreground_color_id); } + + delegate_->SetIconColorIds(foreground_color_id); } std::unique_ptr<views::View> ReadAnythingToolbarView::Separator() { @@ -185,7 +206,6 @@ separator_container->SetLayoutManager(std::move(separator_layout_manager)); auto separator = std::make_unique<views::Separator>(); - separator->SetColorId(delegate_->GetForegroundColorId()); separators_.push_back( separator_container->AddChildView(std::move(separator)));
diff --git a/chrome/browser/ui/views/side_panel/read_anything/read_anything_toolbar_view.h b/chrome/browser/ui/views/side_panel/read_anything/read_anything_toolbar_view.h index 9d6ec35..da88dce 100644 --- a/chrome/browser/ui/views/side_panel/read_anything/read_anything_toolbar_view.h +++ b/chrome/browser/ui/views/side_panel/read_anything/read_anything_toolbar_view.h
@@ -32,7 +32,7 @@ virtual void OnFontSizeChanged(bool increase) = 0; virtual void OnColorsChanged(int new_index) = 0; virtual ui::ComboboxModel* GetColorsModel() = 0; - virtual ui::ColorId GetForegroundColorId() = 0; + virtual void SetIconColorIds(ui::ColorId color_id) = 0; virtual void OnLineSpacingChanged(int new_index) = 0; virtual ui::ComboboxModel* GetLineSpacingModel() = 0; virtual void OnLetterSpacingChanged(int new_index) = 0; @@ -49,7 +49,12 @@ // ReadAnythingModel::Observer: void OnReadAnythingThemeChanged( - read_anything::mojom::ReadAnythingThemePtr new_theme) override; + std::string& font_name, + double font_scale, + ui::ColorId foreground_color_id, + ui::ColorId background_color_id, + read_anything::mojom::Spacing line_spacing, + read_anything::mojom::Spacing letter_spacing) override; // ReadAnythingCoordinator::Observer: void OnCoordinatorDestroyed() override; @@ -64,6 +69,7 @@ void ChangeLetterSpacingCallback(); // views::View: + void AddedToWidget() override; void GetAccessibleNodeData(ui::AXNodeData* node_data) override; std::unique_ptr<views::View> Separator();
diff --git a/chrome/browser/ui/views/side_panel/read_anything/read_anything_toolbar_view_browsertest.cc b/chrome/browser/ui/views/side_panel/read_anything/read_anything_toolbar_view_browsertest.cc index 5c9eb759..f4cef61 100644 --- a/chrome/browser/ui/views/side_panel/read_anything/read_anything_toolbar_view_browsertest.cc +++ b/chrome/browser/ui/views/side_panel/read_anything/read_anything_toolbar_view_browsertest.cc
@@ -21,7 +21,7 @@ MOCK_METHOD(void, OnFontSizeChanged, (bool increase), (override)); MOCK_METHOD(void, OnColorsChanged, (int new_index), (override)); MOCK_METHOD(ui::ComboboxModel*, GetColorsModel, (), (override)); - MOCK_METHOD(ui::ColorId, GetForegroundColorId, (), (override)); + MOCK_METHOD(void, SetIconColorIds, (ui::ColorId color_id), (override)); MOCK_METHOD(void, OnLineSpacingChanged, (int new_index), (override)); MOCK_METHOD(ui::ComboboxModel*, GetLineSpacingModel, (), (override)); MOCK_METHOD(void, OnLetterSpacingChanged, (int new_index), (override)); @@ -86,10 +86,7 @@ toolbar_view_->ChangeLetterSpacingCallback(); } - void OnReadAnythingThemeChanged( - read_anything::mojom::ReadAnythingThemePtr new_theme) { - toolbar_view_->OnReadAnythingThemeChanged(std::move(new_theme)); - } + void Separator() { toolbar_view_->Separator(); } protected: MockReadAnythingToolbarViewDelegate toolbar_delegate_; @@ -121,14 +118,6 @@ ChangeColorsCallback(); } -IN_PROC_BROWSER_TEST_F(ReadAnythingToolbarViewTest, ChangeSeparatorColor) { - // GetForegroundColorId() called for each separator (2 separators total) - EXPECT_CALL(toolbar_delegate_, GetForegroundColorId()).Times(2); - - auto theme = read_anything::mojom::ReadAnythingTheme::New(); - OnReadAnythingThemeChanged(std::move(theme)); -} - IN_PROC_BROWSER_TEST_F(ReadAnythingToolbarViewTest, ChangeLineSpacingCallback) { EXPECT_CALL(toolbar_delegate_, OnLineSpacingChanged(1)).Times(1);
diff --git a/chrome/browser/ui/views/web_apps/web_app_integration_browsertest_mac.cc b/chrome/browser/ui/views/web_apps/web_app_integration_browsertest_mac.cc index f37b0130..3dbc1e39 100644 --- a/chrome/browser/ui/views/web_apps/web_app_integration_browsertest_mac.cc +++ b/chrome/browser/ui/views/web_apps/web_app_integration_browsertest_mac.cc
@@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "chrome/browser/browser_process.h" +#include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/views/web_apps/web_app_integration_test_driver.h" #include "content/public/test/browser_test.h" @@ -12,6 +14,40 @@ // Manual tests: +IN_PROC_BROWSER_TEST_F(WebAppIntegration, LaunchFromAppShimFallback) { + helper_.CreateShortcut(Site::kStandalone, WindowOptions::kWindowed); + helper_.CheckWindowCreated(); + // Currently LaunchFromAppShimFallback doesn't quite match how a regular PWA + // launch is supposed to behave on Mac (i.e. it opens a window even if there + // already is one open). As such, this ClosePwa call is redundant today, but + // would be needed if LaunchFromAppShimFallback triggered Mac specific app + // launch logic. + helper_.ClosePwa(); + helper_.LaunchFromAppShimFallback(Site::kStandalone); + helper_.CheckWindowCreated(); +} + +IN_PROC_BROWSER_TEST_F(WebAppIntegration, + LaunchFromAppShimFallbackSecondaryProfile) { + helper_.SwitchActiveProfile(ProfileName::kProfile2); + helper_.CreateShortcut(Site::kStandalone, WindowOptions::kWindowed); + helper_.CheckWindowCreated(); + helper_.ClosePwa(); + + // Make the default profile be the last active profile by activating the + // originally created browser window. This way we can make sure that + // launching works correctly even if the last active profile isn't the profile + // the app is installed in. + browser()->window()->Activate(); + content::RunAllTasksUntilIdle(); + EXPECT_EQ( + g_browser_process->profile_manager()->GetLastUsedProfileDir().BaseName(), + base::FilePath("Default")); + + helper_.LaunchFromAppShimFallback(Site::kStandalone); + helper_.CheckWindowCreated(); +} + // Generated tests: IN_PROC_BROWSER_TEST_F(
diff --git a/chrome/browser/ui/views/web_apps/web_app_integration_test_driver.cc b/chrome/browser/ui/views/web_apps/web_app_integration_test_driver.cc index ed367f1..4f43a31 100644 --- a/chrome/browser/ui/views/web_apps/web_app_integration_test_driver.cc +++ b/chrome/browser/ui/views/web_apps/web_app_integration_test_driver.cc
@@ -149,6 +149,7 @@ #if BUILDFLAG(IS_MAC) #include <ImageIO/ImageIO.h> #include "chrome/browser/apps/app_shim/app_shim_manager_mac.h" +#include "chrome/browser/chrome_browser_main.h" #include "chrome/browser/shell_integration.h" #include "chrome/browser/web_applications/app_shim_registry_mac.h" #include "chrome/browser/web_applications/os_integration/web_app_shortcut_mac.h" @@ -1338,7 +1339,7 @@ app_browser_ = browser_added_waiter.browser_added(); } active_app_id_ = app_id; - EXPECT_EQ(app_browser()->app_controller()->app_id(), app_id); + EXPECT_TRUE(AppBrowserController::IsForWebApp(app_browser(), app_id)); } else { LaunchFromAppShim(site, /*urls=*/{}); } @@ -1350,7 +1351,7 @@ app_browser_ = browser_added_waiter.browser_added(); ActivateBrowserAndWait(app_browser_); active_app_id_ = app_id; - EXPECT_EQ(app_browser()->app_controller()->app_id(), app_id); + EXPECT_TRUE(AppBrowserController::IsForWebApp(app_browser(), app_id)); } else { LaunchAppStartupBrowserCreator(app_id); } @@ -1361,6 +1362,47 @@ #endif } +#if BUILDFLAG(IS_MAC) +void WebAppIntegrationTestDriver::LaunchFromAppShimFallback(Site site) { + if (!BeforeStateChangeAction(__FUNCTION__)) + return; + + AppId app_id = GetAppIdBySiteMode(site); + ASSERT_TRUE(provider()->registrar().GetAppById(app_id)) + << "No app installed for site: " << static_cast<int>(site); + + WebAppRegistrar& app_registrar = provider()->registrar(); + DisplayMode display_mode = app_registrar.GetAppEffectiveDisplayMode(app_id); + bool is_open_in_app_browser = + (display_mode != blink::mojom::DisplayMode::kBrowser); + + base::CommandLine command_line(base::CommandLine::NO_PROGRAM); + command_line.AppendSwitchASCII(switches::kAppId, app_id); + command_line.AppendSwitchASCII(switches::kTestType, "browser"); + command_line.AppendSwitchASCII(switches::kProfileDirectory, ""); + + if (is_open_in_app_browser) { + BrowserAddedWaiter browser_added_waiter; + // This should have similar logic to the IS_MAC branch in + // LaunchFromPlatformShortcut, however currently launching from app shim + // fallback actually uses the non-mac launch code, so for now that is what + // this is expecting. + ASSERT_TRUE(ChromeBrowserMainParts::ProcessSingletonNotificationCallback( + command_line, /*current_directory=*/{})); + content::RunAllTasksUntilIdle(); + browser_added_waiter.Wait(); + app_browser_ = browser_added_waiter.browser_added(); + active_app_id_ = app_id; + EXPECT_TRUE(AppBrowserController::IsForWebApp(app_browser(), app_id)); + } else { + ASSERT_TRUE(ChromeBrowserMainParts::ProcessSingletonNotificationCallback( + command_line, /*current_directory=*/{})); + content::RunAllTasksUntilIdle(); + } + AfterStateChangeAction(); +} +#endif + void WebAppIntegrationTestDriver::OpenAppSettingsFromAppMenu(Site site) { #if !BUILDFLAG(IS_CHROMEOS) if (!BeforeStateChangeAction(__FUNCTION__))
diff --git a/chrome/browser/ui/views/web_apps/web_app_integration_test_driver.h b/chrome/browser/ui/views/web_apps/web_app_integration_test_driver.h index 764059f..96e8d0a8 100644 --- a/chrome/browser/ui/views/web_apps/web_app_integration_test_driver.h +++ b/chrome/browser/ui/views/web_apps/web_app_integration_test_driver.h
@@ -252,6 +252,9 @@ void LaunchFromLaunchIcon(Site site); void LaunchFromMenuOption(Site site); void LaunchFromPlatformShortcut(Site site); +#if BUILDFLAG(IS_MAC) + void LaunchFromAppShimFallback(Site site); +#endif void OpenAppSettingsFromChromeApps(Site site); void OpenAppSettingsFromAppMenu(Site site); void CreateShortcutsFromList(Site site);
diff --git a/chrome/browser/ui/views/web_apps/web_app_uninstall_dialog_view.cc b/chrome/browser/ui/views/web_apps/web_app_uninstall_dialog_view.cc index d0e65a0..d50bddd9 100644 --- a/chrome/browser/ui/views/web_apps/web_app_uninstall_dialog_view.cc +++ b/chrome/browser/ui/views/web_apps/web_app_uninstall_dialog_view.cc
@@ -109,14 +109,18 @@ set_margins(insets + gfx::Insets::TLBR(0, insets.left() + kIconSizeInDip, 0, 0)); - std::u16string checkbox_label = l10n_util::GetStringFUTF16( - IDS_EXTENSION_UNINSTALL_PROMPT_REMOVE_DATA_CHECKBOX, - url_formatter::FormatUrlForSecurityDisplay( - app_start_url_, url_formatter::SchemeDisplay::OMIT_CRYPTOGRAPHIC)); + // For IWAs checkbox will not be displayed, removal of + // storage is automatically enforced. + if (!provider->registrar().IsIsolated(app_id_)) { + std::u16string checkbox_label = l10n_util::GetStringFUTF16( + IDS_EXTENSION_UNINSTALL_PROMPT_REMOVE_DATA_CHECKBOX, + url_formatter::FormatUrlForSecurityDisplay( + app_start_url_, url_formatter::SchemeDisplay::OMIT_CRYPTOGRAPHIC)); - auto checkbox = std::make_unique<views::Checkbox>(checkbox_label); - checkbox->SetMultiLine(true); - checkbox_ = AddChildView(std::move(checkbox)); + auto checkbox = std::make_unique<views::Checkbox>(checkbox_label); + checkbox->SetMultiLine(true); + checkbox_ = AddChildView(std::move(checkbox)); + } uninstall_source_ = uninstall_source; } @@ -130,15 +134,21 @@ if (!dialog_) return; + auto* provider = web_app::WebAppProvider::GetForWebApps(profile_); + DCHECK(provider); + bool is_isolated_web_app = provider->registrar().IsIsolated(app_id_); + HistogramCloseAction action = - checkbox_->GetChecked() + is_isolated_web_app || (checkbox_ && checkbox_->GetChecked()) ? HistogramCloseAction::kUninstallAndCheckboxChecked : HistogramCloseAction::kUninstall; UMA_HISTOGRAM_ENUMERATION("Webapp.UninstallDialogAction", action); Uninstall(); - if (checkbox_->GetChecked()) + + if (is_isolated_web_app || (checkbox_ && checkbox_->GetChecked())) { ClearWebAppSiteData(); + } } void WebAppUninstallDialogDelegateView::OnDialogCanceled() {
diff --git a/chrome/browser/ui/views/webid/fedcm_account_selection_view_desktop.cc b/chrome/browser/ui/views/webid/fedcm_account_selection_view_desktop.cc index dc3fe0e..4095ea73 100644 --- a/chrome/browser/ui/views/webid/fedcm_account_selection_view_desktop.cc +++ b/chrome/browser/ui/views/webid/fedcm_account_selection_view_desktop.cc
@@ -190,7 +190,14 @@ : State::VERIFYING; if (state_ == State::VERIFYING) { notify_delegate_of_dismiss_ = false; + + base::WeakPtr<FedCmAccountSelectionView> weak_ptr( + weak_ptr_factory_.GetWeakPtr()); delegate_->OnAccountSelected(idp_data.idp_metadata_.config_url, account); + // AccountSelectionView::Delegate::OnAccountSelected() might delete this. + // See https://crbug.com/1393650 for details. + if (!weak_ptr) + return; GetBubbleView()->ShowVerifyingSheet(account, idp_data); return;
diff --git a/chrome/browser/ui/views/webid/fedcm_account_selection_view_desktop.h b/chrome/browser/ui/views/webid/fedcm_account_selection_view_desktop.h index 022783bd..8ef96107 100644 --- a/chrome/browser/ui/views/webid/fedcm_account_selection_view_desktop.h +++ b/chrome/browser/ui/views/webid/fedcm_account_selection_view_desktop.h
@@ -7,6 +7,7 @@ #include "chrome/browser/ui/webid/account_selection_view.h" +#include "base/memory/weak_ptr.h" #include "chrome/browser/ui/tabs/tab_strip_model_observer.h" #include "chrome/browser/ui/views/webid/account_selection_bubble_view.h" #include "chrome/browser/ui/views/webid/identity_provider_display_data.h" @@ -108,6 +109,8 @@ bool notify_delegate_of_dismiss_{true}; base::WeakPtr<views::Widget> bubble_widget_; + + base::WeakPtrFactory<FedCmAccountSelectionView> weak_ptr_factory_{this}; }; #endif // CHROME_BROWSER_UI_VIEWS_WEBID_FEDCM_ACCOUNT_SELECTION_VIEW_DESKTOP_H_
diff --git a/chrome/browser/ui/views/webid/fedcm_account_selection_view_desktop_unittest.cc b/chrome/browser/ui/views/webid/fedcm_account_selection_view_desktop_unittest.cc index 29db94b..93621d68 100644 --- a/chrome/browser/ui/views/webid/fedcm_account_selection_view_desktop_unittest.cc +++ b/chrome/browser/ui/views/webid/fedcm_account_selection_view_desktop_unittest.cc
@@ -254,3 +254,60 @@ EXPECT_TRUE(bubble_view_->show_verifying_sheet_); EXPECT_THAT(bubble_view_->account_ids_, testing::ElementsAre(kAccountId2)); } + +namespace { + +// AccountSelectionViewDelegate which deletes the FedCmAccountSelectionView in +// OnAccountSelected(). +class ViewDeletingAccountSelectionViewDelegate + : public MockAccountSelectionViewDelegate { + public: + explicit ViewDeletingAccountSelectionViewDelegate( + content::WebContents* web_contents) + : MockAccountSelectionViewDelegate(web_contents) {} + ~ViewDeletingAccountSelectionViewDelegate() override = default; + + ViewDeletingAccountSelectionViewDelegate( + const ViewDeletingAccountSelectionViewDelegate&) = delete; + ViewDeletingAccountSelectionViewDelegate& operator=( + const ViewDeletingAccountSelectionViewDelegate&) = delete; + + void SetView(std::unique_ptr<FedCmAccountSelectionView> view) { + view_ = std::move(view); + } + + void OnAccountSelected(const GURL&, + const content::IdentityRequestAccount&) override { + view_.reset(); + } + + private: + std::unique_ptr<FedCmAccountSelectionView> view_; +}; + +} // namespace + +TEST_F(FedCmAccountSelectionViewDesktopTest, AccountSelectedDeletesView) { + delegate_ = std::make_unique<ViewDeletingAccountSelectionViewDelegate>( + test_web_contents_.get()); + ViewDeletingAccountSelectionViewDelegate* view_deleting_delegate = + static_cast<ViewDeletingAccountSelectionViewDelegate*>(delegate_.get()); + + const char kAccountId1[] = "account_id1"; + IdentityProviderDisplayData idp_data = CreateIdentityProviderDisplayData({ + {kAccountId1, LoginState::kSignIn}, + }); + const std::vector<Account>& accounts = idp_data.accounts_; + + AccountSelectionBubbleView::Observer* observer = nullptr; + { + std::unique_ptr<TestFedCmAccountSelectionView> controller = + CreateAndShow(accounts); + observer = + static_cast<AccountSelectionBubbleView::Observer*>(controller.get()); + view_deleting_delegate->SetView(std::move(controller)); + } + + // Destroys FedCmAccountSelectionView. Should not cause crash. + observer->OnAccountSelected(accounts[0], idp_data); +}
diff --git a/chrome/browser/ui/web_applications/app_browser_controller.cc b/chrome/browser/ui/web_applications/app_browser_controller.cc index 0f8425be..e7c4ba8 100644 --- a/chrome/browser/ui/web_applications/app_browser_controller.cc +++ b/chrome/browser/ui/web_applications/app_browser_controller.cc
@@ -295,6 +295,14 @@ #endif // BUILDFLAG(IS_CHROMEOS_ASH) std::u16string AppBrowserController::GetLaunchFlashText() const { + // Isolated Web Apps should show the app's name instead of the origin. + // App Short Name is considered trustworthy because manifest comes from signed + // web bundle. + // TODO:(crbug.com/b/1394199) Disable IWA launch flash text for OSs that + // already display name on title bar. + if (IsIsolatedWebApp()) { + return GetAppShortName(); + } return GetFormattedUrlOrigin(); }
diff --git a/chrome/browser/ui/web_applications/web_app_browser_controller.cc b/chrome/browser/ui/web_applications/web_app_browser_controller.cc index d0a727ee..5ffe488e 100644 --- a/chrome/browser/ui/web_applications/web_app_browser_controller.cc +++ b/chrome/browser/ui/web_applications/web_app_browser_controller.cc
@@ -167,12 +167,7 @@ } bool WebAppBrowserController::IsIsolatedWebApp() const { - if (!web_contents()) - return false; - - return web_contents()->GetPrimaryMainFrame()->GetWebExposedIsolationLevel() >= - content::RenderFrameHost::WebExposedIsolationLevel:: - kMaybeIsolatedApplication; + return registrar().IsIsolated(app_id()); } gfx::Rect WebAppBrowserController::GetDefaultBounds() const {
diff --git a/chrome/browser/ui/webui/BUILD.gn b/chrome/browser/ui/webui/BUILD.gn index 44228b0..71d034e 100644 --- a/chrome/browser/ui/webui/BUILD.gn +++ b/chrome/browser/ui/webui/BUILD.gn
@@ -59,6 +59,7 @@ "//ash/webui/eche_app_ui", "//ash/webui/face_ml_app_ui", "//ash/webui/file_manager:file_manager_untrusted_ui", + "//ash/webui/firmware_update_ui:firmware_update_ui", "//ash/webui/help_app_ui", "//ash/webui/os_feedback_ui", "//ash/webui/shortcut_customization_ui",
diff --git a/chrome/browser/ui/webui/ash/parent_access/parent_access_state_tracker.cc b/chrome/browser/ui/webui/ash/parent_access/parent_access_state_tracker.cc new file mode 100644 index 0000000..23571b8 --- /dev/null +++ b/chrome/browser/ui/webui/ash/parent_access/parent_access_state_tracker.cc
@@ -0,0 +1,67 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/ash/parent_access/parent_access_state_tracker.h" + +#include "base/metrics/histogram_functions.h" + +namespace ash { + +namespace { +constexpr char kParentAccessFlowResultHistogramBase[] = + "ChromeOS.FamilyLinkUser.ParentAccess.FlowResult"; + +constexpr char kParentAccessFlowResultSuffixAll[] = "All"; + +constexpr char kParentAccessFlowResultSuffixWebApprovals[] = "WebApprovals"; +} // namespace + +// static +std::string ParentAccessStateTracker::GetParentAccessResultHistogramForFlowType( + absl::optional<parent_access_ui::mojom::ParentAccessParams::FlowType> + flow_type) { + const std::string separator = "."; + if (!flow_type) { + return base::JoinString({kParentAccessFlowResultHistogramBase, + kParentAccessFlowResultSuffixAll}, + separator); + } + switch (flow_type.value()) { + case parent_access_ui::mojom::ParentAccessParams::FlowType::kWebsiteAccess: + return base::JoinString({kParentAccessFlowResultHistogramBase, + kParentAccessFlowResultSuffixWebApprovals}, + separator); + } +} + +ParentAccessStateTracker::ParentAccessStateTracker( + parent_access_ui::mojom::ParentAccessParams::FlowType flow_type) + : flow_type_(flow_type) { + switch (flow_type_) { + case parent_access_ui::mojom::ParentAccessParams::FlowType::kWebsiteAccess: + // Initialize flow result to kParentAuthentication for flows without an + // initial screen. + flow_result_ = FlowResult::kParentAuthentication; + break; + } +} + +ParentAccessStateTracker::~ParentAccessStateTracker() { + base::UmaHistogramEnumeration( + GetParentAccessResultHistogramForFlowType(absl::nullopt), flow_result_, + FlowResult::kNumStates); + + switch (flow_type_) { + case parent_access_ui::mojom::ParentAccessParams::FlowType::kWebsiteAccess: + base::UmaHistogramEnumeration( + GetParentAccessResultHistogramForFlowType(flow_type_), flow_result_, + FlowResult::kNumStates); + break; + } +} + +void ParentAccessStateTracker::OnWebUiStateChanged(FlowResult result) { + flow_result_ = result; +} +} // namespace ash
diff --git a/chrome/browser/ui/webui/ash/parent_access/parent_access_state_tracker.h b/chrome/browser/ui/webui/ash/parent_access/parent_access_state_tracker.h new file mode 100644 index 0000000..06580e5b --- /dev/null +++ b/chrome/browser/ui/webui/ash/parent_access/parent_access_state_tracker.h
@@ -0,0 +1,58 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_ASH_PARENT_ACCESS_PARENT_ACCESS_STATE_TRACKER_H_ +#define CHROME_BROWSER_UI_WEBUI_ASH_PARENT_ACCESS_PARENT_ACCESS_STATE_TRACKER_H_ + +#include <string> + +#include "chrome/browser/ui/webui/ash/parent_access/parent_access_ui.mojom.h" +#include "third_party/abseil-cpp/absl/types/optional.h" + +namespace ash { + +class ParentAccessStateTracker { + public: + // The flow state used to record the status of the flow when it is closed. The + // enum values are recorded in histogram therefore, keep it consistent with + // ParentAccessFlowResult enum in enums.xml. + enum class FlowResult : int { + // User has opened the initial screen of the flow, if it exists. + // TOOD(b/258722110): Add implementation for recording the initial to + // authentication screen transition. + kInitial = 0, + // User has reached the authentication screen. + kParentAuthentication = 1, + // User has reached the approval screen. + kApproval = 2, + // State when parent grants access. + kAccessApproved = 3, + // State when parent declines access. + kAccessDeclined = 4, + // State where the error page is shown. + kError = 5, + kNumStates = 6 + }; + + static std::string GetParentAccessResultHistogramForFlowType( + absl::optional<parent_access_ui::mojom::ParentAccessParams::FlowType> + flow_type); + + explicit ParentAccessStateTracker( + parent_access_ui::mojom::ParentAccessParams::FlowType flow_type); + ParentAccessStateTracker(const ParentAccessStateTracker&) = delete; + ParentAccessStateTracker& operator=(const ParentAccessStateTracker&) = delete; + ~ParentAccessStateTracker(); + + void OnWebUiStateChanged(FlowResult result); + + private: + FlowResult flow_result_; + + const parent_access_ui::mojom::ParentAccessParams::FlowType flow_type_; +}; + +} // namespace ash + +#endif // CHROME_BROWSER_UI_WEBUI_ASH_PARENT_ACCESS_PARENT_ACCESS_STATE_TRACKER_H_
diff --git a/chrome/browser/ui/webui/ash/parent_access/parent_access_ui_handler_impl.cc b/chrome/browser/ui/webui/ash/parent_access/parent_access_ui_handler_impl.cc index 708e4b4e..943f138 100644 --- a/chrome/browser/ui/webui/ash/parent_access/parent_access_ui_handler_impl.cc +++ b/chrome/browser/ui/webui/ash/parent_access/parent_access_ui_handler_impl.cc
@@ -56,7 +56,17 @@ ParentAccessUIHandlerDelegate* delegate) : identity_manager_(identity_manager), delegate_(delegate), - receiver_(this, std::move(receiver)) {} + receiver_(this, std::move(receiver)) { + // ParentAccess state is only tracked when a dialog is created. i.e. not when + // chrome://parent-access is directly accessed. + if (delegate_) { + // TODO(b/260144025): Reduce the number of times params are cloned. + parent_access_ui::mojom::ParentAccessParamsPtr params = + delegate_->CloneParentAccessParams(); + state_tracker_ = + std::make_unique<ParentAccessStateTracker>(params->flow_type); + } +} ParentAccessUIHandlerImpl::~ParentAccessUIHandlerImpl() = default; @@ -108,6 +118,7 @@ std::move(callback).Run(parent_access_ui::mojom::ParentAccessParams::New()); return; } + // TODO(b/260144025): Reduce the number of times params are cloned. std::move(callback).Run(delegate_->CloneParentAccessParams()); return; } @@ -124,6 +135,10 @@ switch (result) { case parent_access_ui::mojom::ParentAccessResult::kApproved: DCHECK(parent_access_token_); + if (state_tracker_) { + state_tracker_->OnWebUiStateChanged( + ParentAccessStateTracker::FlowResult::kAccessApproved); + } delegate_->SetApproved( parent_access_token_->token(), // Only keep the seconds, not the nanoseconds. @@ -131,12 +146,20 @@ parent_access_token_->expire_time().seconds())); break; case parent_access_ui::mojom::ParentAccessResult::kDeclined: + if (state_tracker_) { + state_tracker_->OnWebUiStateChanged( + ParentAccessStateTracker::FlowResult::kAccessDeclined); + } delegate_->SetDeclined(); break; case parent_access_ui::mojom::ParentAccessResult::kCanceled: delegate_->SetCanceled(); break; case parent_access_ui::mojom::ParentAccessResult::kError: + if (state_tracker_) { + state_tracker_->OnWebUiStateChanged( + ParentAccessStateTracker::FlowResult::kError); + } delegate_->SetError(); break; } @@ -166,6 +189,7 @@ DCHECK(GURL(url).DomainIs("google.com")); } + // TODO(b/260144025): Reduce the number of times params are cloned. parent_access_ui::mojom::ParentAccessParamsPtr params = delegate_->CloneParentAccessParams(); @@ -221,7 +245,10 @@ CallbackCase::kOnParentVerified: message->type = parent_access_ui::mojom::ParentAccessServerMessageType:: kParentVerified; - + if (state_tracker_) { + state_tracker_->OnWebUiStateChanged( + ParentAccessStateTracker::FlowResult::kApproval); + } if (parent_access_callback.on_parent_verified() .verification_proof_case() == kids::platform::parentaccess::client::proto::OnParentVerified::
diff --git a/chrome/browser/ui/webui/ash/parent_access/parent_access_ui_handler_impl.h b/chrome/browser/ui/webui/ash/parent_access/parent_access_ui_handler_impl.h index c424c85..f8aab6e 100644 --- a/chrome/browser/ui/webui/ash/parent_access/parent_access_ui_handler_impl.h +++ b/chrome/browser/ui/webui/ash/parent_access/parent_access_ui_handler_impl.h
@@ -9,6 +9,7 @@ #include "base/memory/weak_ptr.h" #include "chrome/browser/ui/webui/ash/parent_access/parent_access_callback.pb.h" +#include "chrome/browser/ui/webui/ash/parent_access/parent_access_state_tracker.h" #include "chrome/browser/ui/webui/ash/parent_access/parent_access_ui.mojom.h" #include "chrome/browser/ui/webui/ash/parent_access/parent_access_ui_handler_delegate.h" #include "mojo/public/cpp/bindings/pending_receiver.h" @@ -81,6 +82,9 @@ kids::platform::parentaccess::client::proto::ParentAccessToken> parent_access_token_; + // Tracks the current state of the webUI, which is used for logging purposes. + std::unique_ptr<ParentAccessStateTracker> state_tracker_; + base::WeakPtrFactory<ParentAccessUIHandlerImpl> weak_ptr_factory_{this}; };
diff --git a/chrome/browser/ui/webui/ash/parent_access/parent_access_ui_handler_impl_unittest.cc b/chrome/browser/ui/webui/ash/parent_access/parent_access_ui_handler_impl_unittest.cc index 9f5f33b..569ebbd 100644 --- a/chrome/browser/ui/webui/ash/parent_access/parent_access_ui_handler_impl_unittest.cc +++ b/chrome/browser/ui/webui/ash/parent_access/parent_access_ui_handler_impl_unittest.cc
@@ -14,6 +14,7 @@ #include "base/run_loop.h" #include "base/system/sys_info.h" #include "base/test/bind.h" +#include "base/test/metrics/histogram_tester.h" #include "base/test/task_environment.h" #include "base/time/time.h" #include "chrome/browser/ui/webui/ash/parent_access/parent_access_dialog.h" @@ -167,6 +168,7 @@ // Verifies that the parent approvals sequence is handled correctly. TEST_F(ParentAccessUIHandlerImplTest, OnParentVerifiedAndApproved) { + base::HistogramTester histogram_tester; // Construct the ParentAccessCallback kids::platform::parentaccess::client::proto::ParentAccessCallback parent_access_callback; @@ -218,6 +220,18 @@ [&]() -> void { parent_approved_run_loop.Quit(); })); parent_approved_run_loop.Run(); + + // Reset handler to simulate dialog closing. + parent_access_ui_handler_.reset(); + histogram_tester.ExpectUniqueSample( + ParentAccessStateTracker::GetParentAccessResultHistogramForFlowType( + absl::nullopt), + ParentAccessStateTracker::FlowResult::kAccessApproved, 1); + histogram_tester.ExpectUniqueSample( + ParentAccessStateTracker::GetParentAccessResultHistogramForFlowType( + parent_access_ui::mojom::ParentAccessParams::FlowType:: + kWebsiteAccess), + ParentAccessStateTracker::FlowResult::kAccessApproved, 1); } // Verifies that an unparsable parent access callback proto is handled @@ -269,6 +283,7 @@ // Verifies that parent declining is handled correctly. TEST_F(ParentAccessUIHandlerImplTest, OnParentDeclined) { + base::HistogramTester histogram_tester; EXPECT_CALL(delegate_, SetDeclined()).Times(1); // Send the declined result status. @@ -278,10 +293,23 @@ base::BindLambdaForTesting([&]() -> void { run_loop.Quit(); })); run_loop.Run(); + + // Reset handler to simulate dialog closing. + parent_access_ui_handler_.reset(); + histogram_tester.ExpectUniqueSample( + ParentAccessStateTracker::GetParentAccessResultHistogramForFlowType( + absl::nullopt), + ParentAccessStateTracker::FlowResult::kAccessDeclined, 1); + histogram_tester.ExpectUniqueSample( + ParentAccessStateTracker::GetParentAccessResultHistogramForFlowType( + parent_access_ui::mojom::ParentAccessParams::FlowType:: + kWebsiteAccess), + ParentAccessStateTracker::FlowResult::kAccessDeclined, 1); } // Verifies canceling the UI is handled correctly. TEST_F(ParentAccessUIHandlerImplTest, OnCanceled) { + base::HistogramTester histogram_tester; EXPECT_CALL(delegate_, SetCanceled()).Times(1); // Send the declined result status. @@ -291,10 +319,23 @@ base::BindLambdaForTesting([&]() -> void { run_loop.Quit(); })); run_loop.Run(); + + // Reset handler to simulate dialog closing. + parent_access_ui_handler_.reset(); + histogram_tester.ExpectUniqueSample( + ParentAccessStateTracker::GetParentAccessResultHistogramForFlowType( + absl::nullopt), + ParentAccessStateTracker::FlowResult::kParentAuthentication, 1); + histogram_tester.ExpectUniqueSample( + ParentAccessStateTracker::GetParentAccessResultHistogramForFlowType( + parent_access_ui::mojom::ParentAccessParams::FlowType:: + kWebsiteAccess), + ParentAccessStateTracker::FlowResult::kParentAuthentication, 1); } // Verifies errors are handled correctly. TEST_F(ParentAccessUIHandlerImplTest, OnError) { + base::HistogramTester histogram_tester; EXPECT_CALL(delegate_, SetError()).Times(1); // Send the declined result status. @@ -304,6 +345,18 @@ base::BindLambdaForTesting([&]() -> void { run_loop.Quit(); })); run_loop.Run(); + + // Reset handler to simulate dialog closing. + parent_access_ui_handler_.reset(); + histogram_tester.ExpectUniqueSample( + ParentAccessStateTracker::GetParentAccessResultHistogramForFlowType( + absl::nullopt), + ParentAccessStateTracker::FlowResult::kError, 1); + histogram_tester.ExpectUniqueSample( + ParentAccessStateTracker::GetParentAccessResultHistogramForFlowType( + parent_access_ui::mojom::ParentAccessParams::FlowType:: + kWebsiteAccess), + ParentAccessStateTracker::FlowResult::kError, 1); } // Verifies that the ConsentDeclined status is ignored.
diff --git a/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc b/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc index f036954..357c462 100644 --- a/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc +++ b/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc
@@ -986,10 +986,6 @@ } if (url.host_piece() == ash::kChromeUIMediaAppHost) return &NewComponentUI<ash::MediaAppUI, ChromeMediaAppUIDelegate>; - if (ash::features::IsFirmwareUpdaterAppEnabled()) { - if (url.host_piece() == ash::kChromeUIFirmwareUpdateAppHost) - return &NewWebUI<ash::FirmwareUpdateAppUI>; - } if (url.host_piece() == ash::multidevice::kChromeUIProximityAuthHost && !profile->IsOffTheRecord()) { return &NewWebUI<ash::multidevice::ProximityAuthUI>;
diff --git a/chrome/browser/ui/webui/chromeos/chrome_web_ui_configs_chromeos.cc b/chrome/browser/ui/webui/chromeos/chrome_web_ui_configs_chromeos.cc index 2011d22..e67969e7 100644 --- a/chrome/browser/ui/webui/chromeos/chrome_web_ui_configs_chromeos.cc +++ b/chrome/browser/ui/webui/chromeos/chrome_web_ui_configs_chromeos.cc
@@ -11,6 +11,7 @@ #include "ash/constants/ash_features.h" #include "ash/webui/camera_app_ui/camera_app_ui.h" #include "ash/webui/color_internals/color_internals_ui.h" +#include "ash/webui/firmware_update_ui/firmware_update_app_ui.h" #include "ash/webui/shortcut_customization_ui/shortcut_customization_app_ui.h" #include "ash/webui/system_extensions_internals_ui/system_extensions_internals_ui.h" #include "chrome/browser/ash/web_applications/camera_app/chrome_camera_app_ui_delegate.h" @@ -111,6 +112,7 @@ map.AddWebUIConfig(std::make_unique<ash::CryptohomeUIConfig>()); map.AddWebUIConfig(std::make_unique<ash::DriveInternalsUIConfig>()); map.AddWebUIConfig(std::make_unique<ash::EmojiUIConfig>()); + map.AddWebUIConfig(std::make_unique<ash::FirmwareUpdateAppUIConfig>()); map.AddWebUIConfig(std::make_unique<ash::HumanPresenceInternalsUIConfig>()); map.AddWebUIConfig(std::make_unique<ash::InternetConfigDialogUIConfig>()); map.AddWebUIConfig(std::make_unique<ash::InternetDetailDialogUIConfig>());
diff --git a/chrome/browser/ui/webui/realbox/realbox_handler.cc b/chrome/browser/ui/webui/realbox/realbox_handler.cc index f094186..9957e893 100644 --- a/chrome/browser/ui/webui/realbox/realbox_handler.cc +++ b/chrome/browser/ui/webui/realbox/realbox_handler.cc
@@ -694,6 +694,8 @@ void RealboxHandler::OnNavigationLikely( uint8_t line, omnibox::mojom::NavigationPredictor navigation_predictor) { + if (line > autocomplete_controller_->result().size()) + return; if (auto* search_prefetch_service = SearchPrefetchServiceFactory::GetForProfile(profile_)) { AutocompleteMatch match(autocomplete_controller_->result().match_at(line));
diff --git a/chrome/browser/ui/webui/settings/ash/device_section.cc b/chrome/browser/ui/webui/settings/ash/device_section.cc index e77b911..a2369222 100644 --- a/chrome/browser/ui/webui/settings/ash/device_section.cc +++ b/chrome/browser/ui/webui/settings/ash/device_section.cc
@@ -1327,6 +1327,10 @@ html_source->AddBoolean( "enableAudioSettingsPage", base::FeatureList::IsEnabled(ash::features::kAudioSettingsPage)); + + html_source->AddBoolean( + "enableInputDeviceSettingsSplit", + base::FeatureList::IsEnabled(ash::features::kInputDeviceSettingsSplit)); } } // namespace ash::settings
diff --git a/chrome/browser/ui/webui/side_panel/read_anything/read_anything_page_handler.cc b/chrome/browser/ui/webui/side_panel/read_anything/read_anything_page_handler.cc index e18e5c2..f95bf0a7 100644 --- a/chrome/browser/ui/webui/side_panel/read_anything/read_anything_page_handler.cc +++ b/chrome/browser/ui/webui/side_panel/read_anything/read_anything_page_handler.cc
@@ -11,20 +11,24 @@ #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/views/side_panel/read_anything/read_anything_controller.h" +#include "content/public/browser/web_ui.h" #include "ui/accessibility/ax_tree_update.h" using read_anything::mojom::Page; using read_anything::mojom::PageHandler; -using read_anything::mojom::ReadAnythingThemePtr; +using read_anything::mojom::ReadAnythingTheme; ReadAnythingPageHandler::ReadAnythingPageHandler( mojo::PendingRemote<Page> page, - mojo::PendingReceiver<PageHandler> receiver) - : receiver_(this, std::move(receiver)), page_(std::move(page)) { + mojo::PendingReceiver<PageHandler> receiver, + content::WebUI* web_ui) + : browser_(chrome::FindLastActive()), + receiver_(this, std::move(receiver)), + page_(std::move(page)), + web_ui_(web_ui) { // Register |this| as a |ReadAnythingModel::Observer| with the coordinator // for the component. This will allow the IPC to update the front-end web ui. - browser_ = chrome::FindLastActive(); if (!browser_) return; @@ -68,8 +72,21 @@ } void ReadAnythingPageHandler::OnReadAnythingThemeChanged( - ReadAnythingThemePtr new_theme_ptr) { - page_->OnThemeChanged(std::move(new_theme_ptr)); + std::string& font_name, + double font_scale, + ui::ColorId foreground_color_id, + ui::ColorId background_color_id, + read_anything::mojom::Spacing line_spacing, + read_anything::mojom::Spacing letter_spacing) { + content::WebContents* web_contents = web_ui_->GetWebContents(); + SkColor foreground_skcolor = + web_contents->GetColorProvider().GetColor(foreground_color_id); + SkColor background_skcolor = + web_contents->GetColorProvider().GetColor(background_color_id); + + page_->OnThemeChanged( + ReadAnythingTheme::New(font_name, font_scale, foreground_skcolor, + background_skcolor, line_spacing, letter_spacing)); } void ReadAnythingPageHandler::OnLinkClicked(const GURL& url,
diff --git a/chrome/browser/ui/webui/side_panel/read_anything/read_anything_page_handler.h b/chrome/browser/ui/webui/side_panel/read_anything/read_anything_page_handler.h index 0a66766..5175ac6 100644 --- a/chrome/browser/ui/webui/side_panel/read_anything/read_anything_page_handler.h +++ b/chrome/browser/ui/webui/side_panel/read_anything/read_anything_page_handler.h
@@ -41,7 +41,8 @@ ReadAnythingPageHandler( mojo::PendingRemote<read_anything::mojom::Page> page, - mojo::PendingReceiver<read_anything::mojom::PageHandler> receiver); + mojo::PendingReceiver<read_anything::mojom::PageHandler> receiver, + content::WebUI* web_ui); ReadAnythingPageHandler(const ReadAnythingPageHandler&) = delete; ReadAnythingPageHandler& operator=(const ReadAnythingPageHandler&) = delete; ~ReadAnythingPageHandler() override; @@ -54,7 +55,12 @@ const ui::AXTreeUpdate& snapshot, const std::vector<ui::AXNodeID>& content_node_ids) override; void OnReadAnythingThemeChanged( - read_anything::mojom::ReadAnythingThemePtr new_theme) override; + std::string& font_name, + double font_scale, + ui::ColorId foreground_color_id, + ui::ColorId background_color_id, + read_anything::mojom::Spacing line_spacing, + read_anything::mojom::Spacing letter_spacing) override; // ReadAnythingCoordinator::Observer: void OnCoordinatorDestroyed() override; @@ -63,10 +69,12 @@ raw_ptr<ReadAnythingCoordinator> coordinator_; raw_ptr<ReadAnythingPageHandler::Delegate> delegate_; - raw_ptr<Browser> browser_; + const raw_ptr<Browser> browser_; - mojo::Receiver<read_anything::mojom::PageHandler> receiver_; - mojo::Remote<read_anything::mojom::Page> page_; + const mojo::Receiver<read_anything::mojom::PageHandler> receiver_; + const mojo::Remote<read_anything::mojom::Page> page_; + + const raw_ptr<content::WebUI> web_ui_; }; #endif // CHROME_BROWSER_UI_WEBUI_SIDE_PANEL_READ_ANYTHING_READ_ANYTHING_PAGE_HANDLER_H_
diff --git a/chrome/browser/ui/webui/side_panel/read_anything/read_anything_ui.cc b/chrome/browser/ui/webui/side_panel/read_anything/read_anything_ui.cc index d0551b24..0ba6bb8b 100644 --- a/chrome/browser/ui/webui/side_panel/read_anything/read_anything_ui.cc +++ b/chrome/browser/ui/webui/side_panel/read_anything/read_anything_ui.cc
@@ -55,7 +55,7 @@ mojo::PendingReceiver<read_anything::mojom::PageHandler> receiver) { DCHECK(page); read_anything_page_handler_ = std::make_unique<ReadAnythingPageHandler>( - std::move(page), std::move(receiver)); + std::move(page), std::move(receiver), web_ui()); if (embedder()) embedder()->ShowUI(); }
diff --git a/chrome/browser/ui/webui/side_panel/reading_list/reading_list_ui.cc b/chrome/browser/ui/webui/side_panel/reading_list/reading_list_ui.cc index 5165c2bd..19519628 100644 --- a/chrome/browser/ui/webui/side_panel/reading_list/reading_list_ui.cc +++ b/chrome/browser/ui/webui/side_panel/reading_list/reading_list_ui.cc
@@ -184,7 +184,7 @@ mojo::PendingReceiver<read_anything::mojom::PageHandler> receiver) { DCHECK(page); read_anything_page_handler_ = std::make_unique<ReadAnythingPageHandler>( - std::move(page), std::move(receiver)); + std::move(page), std::move(receiver), web_ui()); } void ReadingListUI::BindInterface(
diff --git a/chrome/build/mac.pgo.txt b/chrome/build/mac.pgo.txt index f5633a6e..39024ec 100644 --- a/chrome/build/mac.pgo.txt +++ b/chrome/build/mac.pgo.txt
@@ -1 +1 @@ -chrome-mac-main-1669656314-c98d45ab595374a6d7328896e785e597f17bf8b7.profdata +chrome-mac-main-1669679409-17160feae835be11c7b5443d6e516320fe417b04.profdata
diff --git a/chrome/build/win32.pgo.txt b/chrome/build/win32.pgo.txt index 373f869..21432d0 100644 --- a/chrome/build/win32.pgo.txt +++ b/chrome/build/win32.pgo.txt
@@ -1 +1 @@ -chrome-win32-main-1669647535-a05bdcbc278a8a3579c58cc8ea090754a0d65aeb.profdata +chrome-win32-main-1669656314-7f60400a8b686139a11dda9b76be005319cdf47b.profdata
diff --git a/chrome/build/win64.pgo.txt b/chrome/build/win64.pgo.txt index b2ae1cb..2bdf9a1 100644 --- a/chrome/build/win64.pgo.txt +++ b/chrome/build/win64.pgo.txt
@@ -1 +1 @@ -chrome-win64-main-1669647535-1b78e1a15937228f2435c0c69b40ceebbf158dd8.profdata +chrome-win64-main-1669656314-5acaefdeb3611ad3fe946f3de1c200f2cfeeff95.profdata
diff --git a/chrome/common/chrome_features.cc b/chrome/common/chrome_features.cc index c05631e..dc802d8 100644 --- a/chrome/common/chrome_features.cc +++ b/chrome/common/chrome_features.cc
@@ -75,12 +75,6 @@ base::FEATURE_DISABLED_BY_DEFAULT); #endif // BUILDFLAG(IS_CHROMEOS_ASH) -#if BUILDFLAG(IS_CHROMEOS_ASH) -BASE_FEATURE(kAppProvisioningStatic, - "AppProvisioningStatic", - base::FEATURE_DISABLED_BY_DEFAULT); -#endif // BUILDFLAG(IS_CHROMEOS_ASH) - #if BUILDFLAG(IS_MAC) // Can be used to disable RemoteCocoa (hosting NSWindows for apps in the app // process). For debugging purposes only. @@ -261,6 +255,22 @@ BASE_FEATURE(kPreinstalledWebAppDuplicationFixer, "PreinstalledWebAppDuplicationFixer", base::FEATURE_ENABLED_BY_DEFAULT); + +// Enables OS Integration sub managers to execute the +// registration/unregistration functionality and write the new OS states to the +// DB. +BASE_FEATURE(kOsIntegrationSubManagers, + "OsIntegrationSubManagers", + base::FEATURE_DISABLED_BY_DEFAULT); +const base::FeatureParam<OsIntegrationSubManagersStage>::Option + sub_manager_stages[] = { + {OsIntegrationSubManagersStage::kWriteConfig, "write_config"}, + {OsIntegrationSubManagersStage::kExecuteAndWriteConfig, + "execute_and_write_config"}}; +const base::FeatureParam<OsIntegrationSubManagersStage> + kOsIntegrationSubManagersStageParam{ + &kOsIntegrationSubManagers, "stage", + OsIntegrationSubManagersStage::kWriteConfig, &sub_manager_stages}; #endif // Generates customised default offline page that is shown when web app is
diff --git a/chrome/common/chrome_features.h b/chrome/common/chrome_features.h index fabf015f..1cafecfe 100644 --- a/chrome/common/chrome_features.h +++ b/chrome/common/chrome_features.h
@@ -68,10 +68,6 @@ COMPONENT_EXPORT(CHROME_FEATURES) BASE_DECLARE_FEATURE(kAppPreloadService); #endif -#if BUILDFLAG(IS_CHROMEOS_ASH) -COMPONENT_EXPORT(CHROME_FEATURES) BASE_DECLARE_FEATURE(kAppProvisioningStatic); -#endif - #if BUILDFLAG(IS_MAC) COMPONENT_EXPORT(CHROME_FEATURES) BASE_DECLARE_FEATURE(kAppShimRemoteCocoa); COMPONENT_EXPORT(CHROME_FEATURES) @@ -153,6 +149,16 @@ COMPONENT_EXPORT(CHROME_FEATURES) BASE_DECLARE_FEATURE(kPreinstalledWebAppDuplicationFixer); + +COMPONENT_EXPORT(CHROME_FEATURES) +BASE_DECLARE_FEATURE(kOsIntegrationSubManagers); +enum class OsIntegrationSubManagersStage { + kWriteConfig, + kExecuteAndWriteConfig, +}; +COMPONENT_EXPORT(CHROME_FEATURES) +extern const base::FeatureParam<OsIntegrationSubManagersStage> + kOsIntegrationSubManagersStageParam; #endif COMPONENT_EXPORT(CHROME_FEATURES) BASE_DECLARE_FEATURE(kPWAsDefaultOfflinePage);
diff --git a/chrome/common/profiler/unwind_util.cc b/chrome/common/profiler/unwind_util.cc index a42ae1f..4e4c986f 100644 --- a/chrome/common/profiler/unwind_util.cc +++ b/chrome/common/profiler/unwind_util.cc
@@ -52,7 +52,12 @@ #include "base/android/apk_assets.h" #include "base/files/memory_mapped_file.h" #include "base/profiler/arm_cfi_table.h" + +#if BUILDFLAG(USE_ANDROID_UNWINDER_V2) #include "base/profiler/chrome_unwinder_android_v2.h" +#else // BUILDFLAG(USE_ANDROID_UNWINDER_V2) +#include "base/profiler/chrome_unwinder_android.h" +#endif // BUILDFLAG(USE_ANDROID_UNWINDER_V2) #endif // ANDROID_ARM32_UNWINDING_SUPPORTED #if ANDROID_ARM64_UNWINDING_SUPPORTED @@ -76,6 +81,7 @@ // Encapsulates the setup required to create the Chrome unwinder on Android. #if ANDROID_ARM32_UNWINDING_SUPPORTED +#if BUILDFLAG(USE_ANDROID_UNWINDER_V2) class ChromeUnwinderCreator { public: ChromeUnwinderCreator() { @@ -104,6 +110,38 @@ private: base::MemoryMappedFile chrome_cfi_file_; }; +#else // BUILDFLAG(USE_ANDROID_UNWINDER_V2) +class ChromeUnwinderCreator { + public: + ChromeUnwinderCreator() { + constexpr char kCfiFileName[] = "assets/unwind_cfi_32"; + constexpr char kSplitName[] = "stack_unwinder"; + + base::MemoryMappedFile::Region cfi_region; + int fd = base::android::OpenApkAsset(kCfiFileName, kSplitName, &cfi_region); + DCHECK_GE(fd, 0); + bool mapped_file_ok = + chrome_cfi_file_.Initialize(base::File(fd), cfi_region); + DCHECK(mapped_file_ok); + chrome_cfi_table_ = base::ArmCFITable::Parse( + {chrome_cfi_file_.data(), chrome_cfi_file_.length()}); + DCHECK(chrome_cfi_table_); + } + + ChromeUnwinderCreator(const ChromeUnwinderCreator&) = delete; + ChromeUnwinderCreator& operator=(const ChromeUnwinderCreator&) = delete; + + std::unique_ptr<base::Unwinder> Create() { + return std::make_unique<base::ChromeUnwinderAndroid>( + chrome_cfi_table_.get(), + reinterpret_cast<uintptr_t>(&__executable_start)); + } + + private: + base::MemoryMappedFile chrome_cfi_file_; + std::unique_ptr<base::ArmCFITable> chrome_cfi_table_; +}; +#endif // BUILDFLAG(USE_ANDROID_UNWINDER_V2) #elif ANDROID_ARM64_UNWINDING_SUPPORTED // ANDROID_ARM32_UNWINDING_SUPPORTED class ChromeUnwinderCreator { public:
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index b5d61743..2d4559e 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -7467,7 +7467,6 @@ "../browser/ui/app_list/search/ranking/ftrl_ranker_unittest.cc", "../browser/ui/app_list/search/ranking/mrfu_ranker_unittest.cc", "../browser/ui/app_list/search/ranking/query_highlighter_unittest.cc", - "../browser/ui/app_list/search/ranking/ranking_item_util_unittest.cc", "../browser/ui/app_list/search/ranking/removed_results_proto_unittest.cc", "../browser/ui/app_list/search/ranking/removed_results_ranker_unittest.cc", "../browser/ui/app_list/search/ranking/score_normalizing_ranker_unittest.cc",
diff --git a/chrome/test/chromedriver/chrome/bidi_tracker.cc b/chrome/test/chromedriver/chrome/bidi_tracker.cc index a770e20..0ac5e59 100644 --- a/chrome/test/chromedriver/chrome/bidi_tracker.cc +++ b/chrome/test/chromedriver/chrome/bidi_tracker.cc
@@ -10,7 +10,6 @@ #include "base/logging.h" #include "base/strings/string_util.h" -#include "base/values.h" #include "chrome/test/chromedriver/chrome/devtools_client.h" #include "chrome/test/chromedriver/chrome/status.h" @@ -24,12 +23,6 @@ Status BidiTracker::OnEvent(DevToolsClient* client, const std::string& method, - const base::DictionaryValue& params) { - return OnEvent(client, method, params.GetDict()); -} - -Status BidiTracker::OnEvent(DevToolsClient* client, - const std::string& method, const base::Value::Dict& params) { if (method != "Runtime.bindingCalled") { return Status(kOk);
diff --git a/chrome/test/chromedriver/chrome/bidi_tracker.h b/chrome/test/chromedriver/chrome/bidi_tracker.h index dbbf253..db6bb36 100644 --- a/chrome/test/chromedriver/chrome/bidi_tracker.h +++ b/chrome/test/chromedriver/chrome/bidi_tracker.h
@@ -12,10 +12,6 @@ #include "base/values.h" #include "chrome/test/chromedriver/chrome/devtools_event_listener.h" -namespace base { -class DictionaryValue; -} - class DevToolsClient; class Status; typedef base::RepeatingCallback<Status(base::Value::Dict)> SendBidiPayloadFunc; @@ -34,10 +30,7 @@ bool ListensToConnections() const override; Status OnEvent(DevToolsClient* client, const std::string& method, - const base::DictionaryValue& params) override; - Status OnEvent(DevToolsClient* client, - const std::string& method, - const base::Value::Dict& params); + const base::Value::Dict& params) override; void SetBidiCallback(SendBidiPayloadFunc on_bidi_message);
diff --git a/chrome/test/chromedriver/chrome/cast_tracker.cc b/chrome/test/chromedriver/chrome/cast_tracker.cc index 8901596..fd4a6ec 100644 --- a/chrome/test/chromedriver/chrome/cast_tracker.cc +++ b/chrome/test/chromedriver/chrome/cast_tracker.cc
@@ -22,12 +22,6 @@ Status CastTracker::OnEvent(DevToolsClient* client, const std::string& method, - const base::DictionaryValue& params) { - return OnEvent(client, method, params.GetDict()); -} - -Status CastTracker::OnEvent(DevToolsClient* client, - const std::string& method, const base::Value::Dict& params) { if (method == "Cast.sinksUpdated") { const base::Value* sinks = params.Find("sinks");
diff --git a/chrome/test/chromedriver/chrome/cast_tracker.h b/chrome/test/chromedriver/chrome/cast_tracker.h index 2f326af..c537020ff 100644 --- a/chrome/test/chromedriver/chrome/cast_tracker.h +++ b/chrome/test/chromedriver/chrome/cast_tracker.h
@@ -27,10 +27,7 @@ bool ListensToConnections() const override; Status OnEvent(DevToolsClient* client, const std::string& method, - const base::DictionaryValue& params) override; - Status OnEvent(DevToolsClient* client, - const std::string& method, - const base::Value::Dict& params); + const base::Value::Dict& params) override; const base::Value& sinks() const { return sinks_; } const base::Value& issue() const { return issue_; }
diff --git a/chrome/test/chromedriver/chrome/console_logger.cc b/chrome/test/chromedriver/chrome/console_logger.cc index 8aa6881..a600cf60 100644 --- a/chrome/test/chromedriver/chrome/console_logger.cc +++ b/chrome/test/chromedriver/chrome/console_logger.cc
@@ -47,12 +47,6 @@ Status ConsoleLogger::OnEvent(DevToolsClient* client, const std::string& method, - const base::DictionaryValue& params) { - return OnEvent(client, method, params.GetDict()); -} - -Status ConsoleLogger::OnEvent(DevToolsClient* client, - const std::string& method, const base::Value::Dict& params) { if (method == "Log.entryAdded") return OnLogEntryAdded(params);
diff --git a/chrome/test/chromedriver/chrome/console_logger.h b/chrome/test/chromedriver/chrome/console_logger.h index 2b633d8..ac40c96 100644 --- a/chrome/test/chromedriver/chrome/console_logger.h +++ b/chrome/test/chromedriver/chrome/console_logger.h
@@ -31,10 +31,7 @@ // Translates an event into a log entry. Status OnEvent(DevToolsClient* client, const std::string& method, - const base::DictionaryValue& params) override; - Status OnEvent(DevToolsClient* client, - const std::string& method, - const base::Value::Dict& params); + const base::Value::Dict& params) override; private: raw_ptr<Log> log_; // The log where to create entries.
diff --git a/chrome/test/chromedriver/chrome/console_logger_unittest.cc b/chrome/test/chromedriver/chrome/console_logger_unittest.cc index 5e1a1dc6..32db285 100644 --- a/chrome/test/chromedriver/chrome/console_logger_unittest.cc +++ b/chrome/test/chromedriver/chrome/console_logger_unittest.cc
@@ -38,8 +38,7 @@ Status TriggerEvent(const std::string& method, const base::Value::Dict& params) { - return static_cast<ConsoleLogger*>(listener_)->OnEvent(this, method, - params); + return listener_->OnEvent(this, method, params); } // Overridden from DevToolsClient:
diff --git a/chrome/test/chromedriver/chrome/devtools_client_impl.cc b/chrome/test/chromedriver/chrome/devtools_client_impl.cc index e7b6e64..0661b0bf 100644 --- a/chrome/test/chromedriver/chrome/devtools_client_impl.cc +++ b/chrome/test/chromedriver/chrome/devtools_client_impl.cc
@@ -18,7 +18,6 @@ #include "base/memory/raw_ptr.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" -#include "base/values.h" #include "chrome/test/chromedriver/chrome/devtools_event_listener.h" #include "chrome/test/chromedriver/chrome/javascript_dialog_manager.h" #include "chrome/test/chromedriver/chrome/log.h" @@ -1169,8 +1168,8 @@ while (unnotified_event_listeners_.size()) { DevToolsEventListener* listener = unnotified_event_listeners_.front(); unnotified_event_listeners_.pop_front(); - Status status = listener->OnEvent( - this, unnotified_event_->method, *unnotified_event_->params); + const base::Value::Dict& dict = unnotified_event_->params->GetDict(); + Status status = listener->OnEvent(this, unnotified_event_->method, dict); if (status.IsError()) { unnotified_event_listeners_.clear(); return status;
diff --git a/chrome/test/chromedriver/chrome/devtools_client_impl.h b/chrome/test/chromedriver/chrome/devtools_client_impl.h index 98a7eaa..768ad0b 100644 --- a/chrome/test/chromedriver/chrome/devtools_client_impl.h +++ b/chrome/test/chromedriver/chrome/devtools_client_impl.h
@@ -14,15 +14,12 @@ #include "base/memory/raw_ptr.h" #include "base/memory/ref_counted.h" #include "base/memory/scoped_refptr.h" +#include "base/values.h" #include "chrome/test/chromedriver/chrome/devtools_client.h" #include "chrome/test/chromedriver/net/sync_websocket_factory.h" #include "chrome/test/chromedriver/net/timeout.h" #include "url/gurl.h" -namespace base { -class DictionaryValue; -} - namespace internal { enum InspectorMessageType {
diff --git a/chrome/test/chromedriver/chrome/devtools_client_impl_unittest.cc b/chrome/test/chromedriver/chrome/devtools_client_impl_unittest.cc index 5b76de1fb..626d4ef 100644 --- a/chrome/test/chromedriver/chrome/devtools_client_impl_unittest.cc +++ b/chrome/test/chromedriver/chrome/devtools_client_impl_unittest.cc
@@ -654,7 +654,6 @@ } else { *type = internal::kCommandResponseMessageType; command_response->id = expected_id; - base::DictionaryValue params; command_response->result = std::make_unique<base::DictionaryValue>(); command_response->result->GetDict().Set("key", 2); } @@ -684,10 +683,10 @@ Status OnEvent(DevToolsClient* client, const std::string& method, - const base::DictionaryValue& params) override { + const base::Value::Dict& params) override { called_ = true; EXPECT_STREQ("method", method.c_str()); - EXPECT_TRUE(params.GetDict().Find("key")); + EXPECT_TRUE(params.Find("key")); return Status(kOk); } @@ -712,7 +711,6 @@ } else { *type = internal::kCommandResponseMessageType; command_response->id = expected_id; - base::DictionaryValue params; command_response->result = std::make_unique<base::DictionaryValue>(); command_response->result->GetDict().Set("key", 2); } @@ -1421,7 +1419,7 @@ Status OnEvent(DevToolsClient* client, const std::string& method, - const base::DictionaryValue& params) override { + const base::Value::Dict& params) override { EXPECT_EQ(client_, client); EXPECT_STREQ("onconnected-id", client->GetId().c_str()); EXPECT_TRUE(on_connected_called_); @@ -1462,7 +1460,7 @@ if (connect_complete_) { base::Value::Dict response; response.Set("id", cmd_id); - response.Set("result", base::DictionaryValue()); + response.Set("result", base::Value::Dict()); std::string json_response; base::JSONWriter::Write(base::Value(std::move(response)), &json_response); queued_response_.push(std::move(json_response)); @@ -1470,7 +1468,7 @@ // Push one event. base::Value::Dict event; event.Set("method", "updateEvent"); - event.Set("params", base::DictionaryValue()); + event.Set("params", base::Value::Dict()); std::string json_event; base::JSONWriter::Write(base::Value(std::move(event)), &json_event); queued_response_.push(std::move(json_event)); @@ -1569,7 +1567,7 @@ Status OnConnected(DevToolsClient* client) override { return Status(kOk); } Status OnEvent(DevToolsClient* client, const std::string& method, - const base::DictionaryValue& params) override { + const base::Value::Dict& params) override { received_event_ = true; return Status(kOk); } @@ -1592,9 +1590,9 @@ Status OnEvent(DevToolsClient* client, const std::string& method, - const base::DictionaryValue& params) override { + const base::Value::Dict& params) override { EXPECT_EQ(client_, client); - client_->SendCommand("method", params.GetDict()); + client_->SendCommand("method", params); EXPECT_TRUE(other_listener_->received_event_); return Status(kOk); } @@ -1742,11 +1740,11 @@ Status OnEvent(DevToolsClient* client, const std::string& method, - const base::DictionaryValue& params) override { + const base::Value::Dict& params) override { DevToolsClientImpl* client_impl = static_cast<DevToolsClientImpl*>(client); int msg_id = client_impl->NextMessageId(); - Status status = client->SendCommand("hello", params.GetDict()); + Status status = client->SendCommand("hello", params); if (msg_id == expected_blocked_id_) { EXPECT_EQ(kUnexpectedAlertOpen, status.code()); @@ -1845,7 +1843,7 @@ Status OnEvent(DevToolsClient* client, const std::string& method, - const base::DictionaryValue& params) override { + const base::Value::Dict& params) override { msgs_.push_back(method); return Status(kOk); } @@ -2146,7 +2144,7 @@ Status OnEvent(DevToolsClient* client, const std::string& method, - const base::DictionaryValue& event_params) override { + const base::Value::Dict& event_params) override { if (event_handled_) { return Status{kOk}; } @@ -2637,13 +2635,11 @@ Status OnEvent(DevToolsClient* client, const std::string& method, - const base::DictionaryValue& params_dv) override { + const base::Value::Dict& params) override { if (method != "Runtime.bindingCalled") { return Status(kOk); } - const base::Value::Dict& params = params_dv.GetDict(); - const std::string* name = params.FindString("name"); EXPECT_NE(name, nullptr); if (name == nullptr) { @@ -2881,10 +2877,10 @@ Status OnEvent(DevToolsClient* client, const std::string& method, - const base::DictionaryValue& params_dv) override { + const base::Value::Dict& params_dv) override { base::Value::Dict data; data.Set("method", method); - data.Set("params", params_dv.GetDict().Clone()); + data.Set("params", params_dv.Clone()); event_list.push_back(std::move(data)); return Status(kOk); }
diff --git a/chrome/test/chromedriver/chrome/devtools_event_listener.cc b/chrome/test/chromedriver/chrome/devtools_event_listener.cc index 76954d82..7527057 100644 --- a/chrome/test/chromedriver/chrome/devtools_event_listener.cc +++ b/chrome/test/chromedriver/chrome/devtools_event_listener.cc
@@ -18,7 +18,7 @@ Status DevToolsEventListener::OnEvent(DevToolsClient* client, const std::string& method, - const base::DictionaryValue& params) { + const base::Value::Dict& params) { return Status(kOk); }
diff --git a/chrome/test/chromedriver/chrome/devtools_event_listener.h b/chrome/test/chromedriver/chrome/devtools_event_listener.h index d8886dc2..01acd5d7 100644 --- a/chrome/test/chromedriver/chrome/devtools_event_listener.h +++ b/chrome/test/chromedriver/chrome/devtools_event_listener.h
@@ -7,9 +7,7 @@ #include <string> -namespace base { -class DictionaryValue; -} +#include "base/values.h" class DevToolsClient; class Status; @@ -29,7 +27,7 @@ // Called when an event is received. Should avoid blocking if possible. virtual Status OnEvent(DevToolsClient* client, const std::string& method, - const base::DictionaryValue& params); + const base::Value::Dict& params); // Called when a command success response is received. virtual Status OnCommandSuccess(DevToolsClient* client,
diff --git a/chrome/test/chromedriver/chrome/frame_tracker.cc b/chrome/test/chromedriver/chrome/frame_tracker.cc index 1346dd51..76682c3 100644 --- a/chrome/test/chromedriver/chrome/frame_tracker.cc +++ b/chrome/test/chromedriver/chrome/frame_tracker.cc
@@ -93,12 +93,6 @@ Status FrameTracker::OnEvent(DevToolsClient* client, const std::string& method, - const base::DictionaryValue& params) { - return OnEvent(client, method, params.GetDict()); -} - -Status FrameTracker::OnEvent(DevToolsClient* client, - const std::string& method, const base::Value::Dict& params) { if (method == "Runtime.executionContextCreated") { const base::Value::Dict* context = params.FindDict("context");
diff --git a/chrome/test/chromedriver/chrome/frame_tracker.h b/chrome/test/chromedriver/chrome/frame_tracker.h index 4bae08050..b550cf33 100644 --- a/chrome/test/chromedriver/chrome/frame_tracker.h +++ b/chrome/test/chromedriver/chrome/frame_tracker.h
@@ -40,10 +40,7 @@ Status OnConnected(DevToolsClient* client) override; Status OnEvent(DevToolsClient* client, const std::string& method, - const base::DictionaryValue& params) override; - Status OnEvent(DevToolsClient* client, - const std::string& method, - const base::Value::Dict& params); + const base::Value::Dict& params) override; private: std::map<std::string, std::string> frame_to_context_map_;
diff --git a/chrome/test/chromedriver/chrome/geolocation_override_manager.cc b/chrome/test/chromedriver/chrome/geolocation_override_manager.cc index 4562f7f..4c28d25 100644 --- a/chrome/test/chromedriver/chrome/geolocation_override_manager.cc +++ b/chrome/test/chromedriver/chrome/geolocation_override_manager.cc
@@ -28,13 +28,6 @@ return ApplyOverrideIfNeeded(); } -Status GeolocationOverrideManager::OnEvent( - DevToolsClient* client, - const std::string& method, - const base::DictionaryValue& params) { - return OnEvent(client, method, params.GetDict()); -} - Status GeolocationOverrideManager::OnEvent(DevToolsClient* client, const std::string& method, const base::Value::Dict& params) {
diff --git a/chrome/test/chromedriver/chrome/geolocation_override_manager.h b/chrome/test/chromedriver/chrome/geolocation_override_manager.h index 32505e2..83b9f6e 100644 --- a/chrome/test/chromedriver/chrome/geolocation_override_manager.h +++ b/chrome/test/chromedriver/chrome/geolocation_override_manager.h
@@ -34,10 +34,7 @@ Status OnConnected(DevToolsClient* client) override; Status OnEvent(DevToolsClient* client, const std::string& method, - const base::DictionaryValue& params) override; - Status OnEvent(DevToolsClient* client, - const std::string& method, - const base::Value::Dict& params); + const base::Value::Dict& params) override; private: Status ApplyOverrideIfNeeded();
diff --git a/chrome/test/chromedriver/chrome/heap_snapshot_taker.cc b/chrome/test/chromedriver/chrome/heap_snapshot_taker.cc index 8553c9c..df83550 100644 --- a/chrome/test/chromedriver/chrome/heap_snapshot_taker.cc +++ b/chrome/test/chromedriver/chrome/heap_snapshot_taker.cc
@@ -60,12 +60,6 @@ Status HeapSnapshotTaker::OnEvent(DevToolsClient* client, const std::string& method, - const base::DictionaryValue& params) { - return OnEvent(client, method, params.GetDict()); -} - -Status HeapSnapshotTaker::OnEvent(DevToolsClient* client, - const std::string& method, const base::Value::Dict& params) { if (method == "HeapProfiler.addHeapSnapshotChunk") { const std::string* chunk = params.FindString("chunk");
diff --git a/chrome/test/chromedriver/chrome/heap_snapshot_taker.h b/chrome/test/chromedriver/chrome/heap_snapshot_taker.h index 1e70cb9..dd8004b 100644 --- a/chrome/test/chromedriver/chrome/heap_snapshot_taker.h +++ b/chrome/test/chromedriver/chrome/heap_snapshot_taker.h
@@ -31,10 +31,7 @@ bool ListensToConnections() const override; Status OnEvent(DevToolsClient* client, const std::string& method, - const base::DictionaryValue& params) override; - Status OnEvent(DevToolsClient* client, - const std::string& method, - const base::Value::Dict& params); + const base::Value::Dict& params) override; private: Status TakeSnapshotInternal();
diff --git a/chrome/test/chromedriver/chrome/heap_snapshot_taker_unittest.cc b/chrome/test/chromedriver/chrome/heap_snapshot_taker_unittest.cc index c926498..c51b6313 100644 --- a/chrome/test/chromedriver/chrome/heap_snapshot_taker_unittest.cc +++ b/chrome/test/chromedriver/chrome/heap_snapshot_taker_unittest.cc
@@ -36,10 +36,10 @@ bool IsDisabled() { return disabled_; } Status SendAddHeapSnapshotChunkEvent() { - base::DictionaryValue event_params; - event_params.GetDict().Set("uid", uid_); + base::Value::Dict event_params; + event_params.Set("uid", uid_); for (size_t i = 0; i < std::size(chunks); ++i) { - event_params.GetDict().Set("chunk", chunks[i]); + event_params.Set("chunk", chunks[i]); Status status = listeners_.front()->OnEvent( this, "HeapProfiler.addHeapSnapshotChunk", event_params); if (status.IsError())
diff --git a/chrome/test/chromedriver/chrome/javascript_dialog_manager.cc b/chrome/test/chromedriver/chrome/javascript_dialog_manager.cc index 7865f48..448e1cd 100644 --- a/chrome/test/chromedriver/chrome/javascript_dialog_manager.cc +++ b/chrome/test/chromedriver/chrome/javascript_dialog_manager.cc
@@ -77,12 +77,6 @@ Status JavaScriptDialogManager::OnEvent(DevToolsClient* client, const std::string& method, - const base::DictionaryValue& params) { - return OnEvent(client, method, params.GetDict()); -} - -Status JavaScriptDialogManager::OnEvent(DevToolsClient* client, - const std::string& method, const base::Value::Dict& params) { if (method == "Page.javascriptDialogOpening") { const std::string* message = params.FindString("message");
diff --git a/chrome/test/chromedriver/chrome/javascript_dialog_manager.h b/chrome/test/chromedriver/chrome/javascript_dialog_manager.h index 41ff2882..910f204 100644 --- a/chrome/test/chromedriver/chrome/javascript_dialog_manager.h +++ b/chrome/test/chromedriver/chrome/javascript_dialog_manager.h
@@ -39,10 +39,7 @@ Status OnConnected(DevToolsClient* client) override; Status OnEvent(DevToolsClient* client, const std::string& method, - const base::DictionaryValue& params) override; - Status OnEvent(DevToolsClient* client, - const std::string& method, - const base::Value::Dict& params); + const base::Value::Dict& params) override; private: raw_ptr<DevToolsClient> client_;
diff --git a/chrome/test/chromedriver/chrome/javascript_dialog_manager_unittest.cc b/chrome/test/chromedriver/chrome/javascript_dialog_manager_unittest.cc index e64152b..2d8ea16 100644 --- a/chrome/test/chromedriver/chrome/javascript_dialog_manager_unittest.cc +++ b/chrome/test/chromedriver/chrome/javascript_dialog_manager_unittest.cc
@@ -99,9 +99,8 @@ const base::Value::Dict& params, base::Value* result) override { while (closing_count_ > 0) { - base::DictionaryValue empty; - Status status = - listener_->OnEvent(this, "Page.javascriptDialogClosed", empty); + Status status = listener_->OnEvent(this, "Page.javascriptDialogClosed", + base::Value::Dict()); if (status.IsError()) return status; closing_count_--; @@ -124,10 +123,10 @@ FakeDevToolsClient client; BrowserInfo browser_info; JavaScriptDialogManager manager(&client, &browser_info); - base::DictionaryValue params; - params.SetString("message", "hi"); - params.SetString("type", "alert"); - params.SetString("defaultPrompt", ""); + base::Value::Dict params; + params.Set("message", "hi"); + params.Set("type", "alert"); + params.Set("defaultPrompt", ""); ASSERT_FALSE(manager.IsDialogOpen()); std::string message; ASSERT_EQ(kNoSuchAlert, manager.GetDialogMessage(&message).code()); @@ -153,15 +152,15 @@ FakeDevToolsClient client; BrowserInfo browser_info; JavaScriptDialogManager manager(&client, &browser_info); - base::DictionaryValue params; - params.SetString("message", "1"); - params.SetString("type", "confirm"); - params.SetString("defaultPrompt", ""); + base::Value::Dict params; + params.Set("message", "1"); + params.Set("type", "confirm"); + params.Set("defaultPrompt", ""); ASSERT_EQ( kOk, manager.OnEvent(&client, "Page.javascriptDialogOpening", params).code()); - params.SetString("message", "2"); - params.SetString("type", "alert"); + params.Set("message", "2"); + params.Set("type", "alert"); ASSERT_EQ( kOk, manager.OnEvent(&client, "Page.javascriptDialogOpening", params).code()); @@ -192,10 +191,10 @@ StubDevToolsClient client; BrowserInfo browser_info; JavaScriptDialogManager manager(&client, &browser_info); - base::DictionaryValue params; - params.SetString("message", "hi"); - params.SetString("type", "alert"); - params.SetString("defaultPrompt", ""); + base::Value::Dict params; + params.Set("message", "hi"); + params.Set("type", "alert"); + params.Set("defaultPrompt", ""); ASSERT_FALSE(manager.IsDialogOpen()); std::string message; ASSERT_EQ(kNoSuchAlert, manager.GetDialogMessage(&message).code());
diff --git a/chrome/test/chromedriver/chrome/mobile_emulation_override_manager.cc b/chrome/test/chromedriver/chrome/mobile_emulation_override_manager.cc index 49eb74f..5cec97fc 100644 --- a/chrome/test/chromedriver/chrome/mobile_emulation_override_manager.cc +++ b/chrome/test/chromedriver/chrome/mobile_emulation_override_manager.cc
@@ -27,13 +27,6 @@ Status MobileEmulationOverrideManager::OnEvent( DevToolsClient* client, const std::string& method, - const base::DictionaryValue& params) { - return OnEvent(client, method, params.GetDict()); -} - -Status MobileEmulationOverrideManager::OnEvent( - DevToolsClient* client, - const std::string& method, const base::Value::Dict& params) { if (method == "Page.frameNavigated") { if (!params.FindByDottedPath("frame.parentId"))
diff --git a/chrome/test/chromedriver/chrome/mobile_emulation_override_manager.h b/chrome/test/chromedriver/chrome/mobile_emulation_override_manager.h index 0609925..1afe33ba 100644 --- a/chrome/test/chromedriver/chrome/mobile_emulation_override_manager.h +++ b/chrome/test/chromedriver/chrome/mobile_emulation_override_manager.h
@@ -34,10 +34,7 @@ Status OnConnected(DevToolsClient* client) override; Status OnEvent(DevToolsClient* client, const std::string& method, - const base::DictionaryValue& params) override; - Status OnEvent(DevToolsClient* client, - const std::string& method, - const base::Value::Dict& params); + const base::Value::Dict& params) override; bool IsEmulatingTouch() const; bool HasOverrideMetrics() const;
diff --git a/chrome/test/chromedriver/chrome/navigation_tracker.cc b/chrome/test/chromedriver/chrome/navigation_tracker.cc index 02bd71f..b403f59 100644 --- a/chrome/test/chromedriver/chrome/navigation_tracker.cc +++ b/chrome/test/chromedriver/chrome/navigation_tracker.cc
@@ -228,12 +228,6 @@ Status NavigationTracker::OnEvent(DevToolsClient* client, const std::string& method, - const base::DictionaryValue& params) { - return OnEvent(client, method, params.GetDict()); -} - -Status NavigationTracker::OnEvent(DevToolsClient* client, - const std::string& method, const base::Value::Dict& params) { if (client->IsMainPage() && (method == "Page.loadEventFired" ||
diff --git a/chrome/test/chromedriver/chrome/navigation_tracker.h b/chrome/test/chromedriver/chrome/navigation_tracker.h index 48831e8..55ba98d 100644 --- a/chrome/test/chromedriver/chrome/navigation_tracker.h +++ b/chrome/test/chromedriver/chrome/navigation_tracker.h
@@ -58,15 +58,11 @@ Status OnConnected(DevToolsClient* client) override; Status OnEvent(DevToolsClient* client, const std::string& method, - const base::DictionaryValue& params) override; + const base::Value::Dict& params) override; Status OnCommandSuccess(DevToolsClient* client, const std::string& method, const base::DictionaryValue* result, const Timeout& command_timeout) override; - - Status OnEvent(DevToolsClient* client, - const std::string& method, - const base::Value::Dict& params); Status OnCommandSuccess(DevToolsClient* client, const std::string& method, const base::Value::Dict* result,
diff --git a/chrome/test/chromedriver/chrome/navigation_tracker_unittest.cc b/chrome/test/chromedriver/chrome/navigation_tracker_unittest.cc index aab4350..12e9e4c 100644 --- a/chrome/test/chromedriver/chrome/navigation_tracker_unittest.cc +++ b/chrome/test/chromedriver/chrome/navigation_tracker_unittest.cc
@@ -71,8 +71,8 @@ if (send_event_first_.length()) { for (DevToolsEventListener* listener : listeners_) { - Status status = static_cast<NavigationTracker*>(listener)->OnEvent( - this, send_event_first_, *send_event_first_params_); + Status status = listener->OnEvent(this, send_event_first_, + *send_event_first_params_); if (status.IsError()) return status; }
diff --git a/chrome/test/chromedriver/chrome/network_conditions_override_manager.cc b/chrome/test/chromedriver/chrome/network_conditions_override_manager.cc index b4cc5675..4a88a16 100644 --- a/chrome/test/chromedriver/chrome/network_conditions_override_manager.cc +++ b/chrome/test/chromedriver/chrome/network_conditions_override_manager.cc
@@ -32,13 +32,6 @@ Status NetworkConditionsOverrideManager::OnEvent( DevToolsClient* client, const std::string& method, - const base::DictionaryValue& params) { - return OnEvent(client, method, params.GetDict()); -} - -Status NetworkConditionsOverrideManager::OnEvent( - DevToolsClient* client, - const std::string& method, const base::Value::Dict& params) { if (method == "Page.frameNavigated") { if (!params.FindByDottedPath("frame.parentId"))
diff --git a/chrome/test/chromedriver/chrome/network_conditions_override_manager.h b/chrome/test/chromedriver/chrome/network_conditions_override_manager.h index 41e2351..0c1a45c 100644 --- a/chrome/test/chromedriver/chrome/network_conditions_override_manager.h +++ b/chrome/test/chromedriver/chrome/network_conditions_override_manager.h
@@ -35,10 +35,7 @@ Status OnConnected(DevToolsClient* client) override; Status OnEvent(DevToolsClient* client, const std::string& method, - const base::DictionaryValue& params) override; - Status OnEvent(DevToolsClient* client, - const std::string& method, - const base::Value::Dict& params); + const base::Value::Dict& params) override; private: Status ApplyOverrideIfNeeded();
diff --git a/chrome/test/chromedriver/chrome/page_tracker.cc b/chrome/test/chromedriver/chrome/page_tracker.cc index 315c9d3b..5e716830 100644 --- a/chrome/test/chromedriver/chrome/page_tracker.cc +++ b/chrome/test/chromedriver/chrome/page_tracker.cc
@@ -26,12 +26,6 @@ Status PageTracker::OnEvent(DevToolsClient* client, const std::string& method, - const base::DictionaryValue& params) { - return OnEvent(client, method, params.GetDict()); -} - -Status PageTracker::OnEvent(DevToolsClient* client, - const std::string& method, const base::Value::Dict& params) { if (method == "Target.detachedFromTarget") { const std::string* target_id = params.FindString("targetId");
diff --git a/chrome/test/chromedriver/chrome/page_tracker.h b/chrome/test/chromedriver/chrome/page_tracker.h index 996fcd4..1892174 100644 --- a/chrome/test/chromedriver/chrome/page_tracker.h +++ b/chrome/test/chromedriver/chrome/page_tracker.h
@@ -32,10 +32,7 @@ Status OnConnected(DevToolsClient* client) override; Status OnEvent(DevToolsClient* client, const std::string& method, - const base::DictionaryValue& params) override; - Status OnEvent(DevToolsClient* client, - const std::string& method, - const base::Value::Dict& params); + const base::Value::Dict& params) override; private: raw_ptr<std::list<std::unique_ptr<WebViewImpl>>> web_views_;
diff --git a/chrome/test/chromedriver/devtools_events_logger.cc b/chrome/test/chromedriver/devtools_events_logger.cc index f459959..b9b019f4 100644 --- a/chrome/test/chromedriver/devtools_events_logger.cc +++ b/chrome/test/chromedriver/devtools_events_logger.cc
@@ -21,12 +21,6 @@ Status DevToolsEventsLogger::OnEvent(DevToolsClient* client, const std::string& method, - const base::DictionaryValue& params) { - return OnEvent(client, method, params.GetDict()); -} - -Status DevToolsEventsLogger::OnEvent(DevToolsClient* client, - const std::string& method, const base::Value::Dict& params) { auto it = events_.find(method); if (it != events_.end()) {
diff --git a/chrome/test/chromedriver/devtools_events_logger.h b/chrome/test/chromedriver/devtools_events_logger.h index a779abb..9109dbe 100644 --- a/chrome/test/chromedriver/devtools_events_logger.h +++ b/chrome/test/chromedriver/devtools_events_logger.h
@@ -36,10 +36,7 @@ Status OnEvent(DevToolsClient* client, const std::string& method, - const base::DictionaryValue& params) override; - Status OnEvent(DevToolsClient* client, - const std::string& method, - const base::Value::Dict& params); + const base::Value::Dict& params) override; private: raw_ptr<Log> log_; // The log where to create entries.
diff --git a/chrome/test/chromedriver/performance_logger.cc b/chrome/test/chromedriver/performance_logger.cc index 08e3dbc7..9ce84a25 100644 --- a/chrome/test/chromedriver/performance_logger.cc +++ b/chrome/test/chromedriver/performance_logger.cc
@@ -101,13 +101,6 @@ return EnableInspectorDomains(client); } -Status PerformanceLogger::OnEvent( - DevToolsClient* client, - const std::string& method, - const base::DictionaryValue& params) { - return OnEvent(client, method, params.GetDict()); -} - Status PerformanceLogger::OnEvent(DevToolsClient* client, const std::string& method, const base::Value::Dict& params) {
diff --git a/chrome/test/chromedriver/performance_logger.h b/chrome/test/chromedriver/performance_logger.h index b14016c3..ec4b410 100644 --- a/chrome/test/chromedriver/performance_logger.h +++ b/chrome/test/chromedriver/performance_logger.h
@@ -52,10 +52,7 @@ // Calls HandleInspectorEvents or HandleTraceEvents depending on client type. Status OnEvent(DevToolsClient* client, const std::string& method, - const base::DictionaryValue& params) override; - Status OnEvent(DevToolsClient* client, - const std::string& method, - const base::Value::Dict& params); + const base::Value::Dict& params) override; // Before allowed commands, if tracing enabled, calls CollectTraceEvents. Status BeforeCommand(const std::string& command_name) override;
diff --git a/chrome/test/chromedriver/performance_logger_unittest.cc b/chrome/test/chromedriver/performance_logger_unittest.cc index 0c932a4..7e217f4 100644 --- a/chrome/test/chromedriver/performance_logger_unittest.cc +++ b/chrome/test/chromedriver/performance_logger_unittest.cc
@@ -52,8 +52,7 @@ Status TriggerEvent(const std::string& method, const base::Value::Dict& params) { - return static_cast<PerformanceLogger*>(listener_)->OnEvent(this, method, - params); + return listener_->OnEvent(this, method, params); } Status TriggerEvent(const std::string& method) {
diff --git a/chrome/test/data/webui/bluetooth_internals/bluetooth_internals_test.js b/chrome/test/data/webui/bluetooth_internals/bluetooth_internals_test.js index 3a764ca9..ebd17d2 100644 --- a/chrome/test/data/webui/bluetooth_internals/bluetooth_internals_test.js +++ b/chrome/test/data/webui/bluetooth_internals/bluetooth_internals_test.js
@@ -12,7 +12,7 @@ import {ValueDataType} from 'chrome://bluetooth-internals/value_control.js'; import {assert} from 'chrome://resources/js/assert.js'; import {PromiseResolver} from 'chrome://resources/js/promise_resolver.js'; -import {$} from 'chrome://resources/js/util.js'; +import {$} from 'chrome://resources/js/util_ts.js'; import {fakeAdapterInfo, fakeCharacteristicInfo1, fakeDeviceInfo1, fakeDeviceInfo2, fakeDeviceInfo3, fakeServiceInfo1, fakeServiceInfo2, TestAdapter, TestBluetoothInternalsHandler, TestDevice} from './test_utils.js'; @@ -545,7 +545,7 @@ deviceInspectLink.click(); assertEquals('#' + deviceDetailsPageId, window.location.hash); - let detailsPage = $(deviceDetailsPageId); + let detailsPage = document.getElementById(deviceDetailsPageId); assertTrue(!!detailsPage); return internalsHandler.adapter.deviceImplMap.get(device.address) @@ -556,7 +556,7 @@ detailsPage.querySelector('.forget').click(); assertEquals('#devices', window.location.hash); - detailsPage = $(deviceDetailsPageId); + detailsPage = document.getElementById(deviceDetailsPageId); assertFalse(!!detailsPage); }); }); @@ -573,7 +573,7 @@ deviceLinks[0].click(); assertEquals('#' + deviceDetailsPageId, window.location.hash); - let detailsPage = $(deviceDetailsPageId); + let detailsPage = document.getElementById(deviceDetailsPageId); assertTrue(!!detailsPage); return internalsHandler.adapter.deviceImplMap.get(device.address) @@ -585,7 +585,7 @@ // Second link is 'Forget'. deviceLinks[1].click(); assertEquals('#devices', window.location.hash); - detailsPage = $(deviceDetailsPageId); + detailsPage = document.getElementById(deviceDetailsPageId); assertFalse(!!detailsPage); }); });
diff --git a/chrome/test/data/webui/bookmarks/app_test.js b/chrome/test/data/webui/bookmarks/app_test.js index effb0ae..c173fe1 100644 --- a/chrome/test/data/webui/bookmarks/app_test.js +++ b/chrome/test/data/webui/bookmarks/app_test.js
@@ -4,7 +4,7 @@ import {HIDE_FOCUS_RING_ATTRIBUTE, LOCAL_STORAGE_FOLDER_STATE_KEY, LOCAL_STORAGE_TREE_WIDTH_KEY} from 'chrome://bookmarks/bookmarks.js'; import {isMac} from 'chrome://resources/js/platform.js'; -import {getDeepActiveElement} from 'chrome://resources/js/util.js'; +import {getDeepActiveElement} from 'chrome://resources/js/util_ts.js'; import {down, keyDownOn, pressAndReleaseKeyOn} from 'chrome://resources/polymer/v3_0/iron-test-helpers/mock-interactions.js'; import {flushTasks} from 'chrome://webui-test/polymer_test_util.js';
diff --git a/chrome/test/data/webui/bookmarks/folder_node_focus_test.js b/chrome/test/data/webui/bookmarks/folder_node_focus_test.js index f7c8c58e..2201f93b 100644 --- a/chrome/test/data/webui/bookmarks/folder_node_focus_test.js +++ b/chrome/test/data/webui/bookmarks/folder_node_focus_test.js
@@ -3,9 +3,10 @@ // found in the LICENSE file. import {changeFolderOpen, Command, selectFolder} from 'chrome://bookmarks/bookmarks.js'; -import {getDeepActiveElement} from 'chrome://resources/js/util.js'; +import {getDeepActiveElement} from 'chrome://resources/js/util_ts.js'; import {keyDownOn} from 'chrome://resources/polymer/v3_0/iron-test-helpers/mock-interactions.js'; import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; + import {TestCommandManager} from './test_command_manager.js'; import {TestStore} from './test_store.js'; import {createFolder, createItem, findFolderNode, getAllFoldersOpenState, replaceBody, testTree} from './test_util.js';
diff --git a/chrome/test/data/webui/bookmarks/list_focus_test.js b/chrome/test/data/webui/bookmarks/list_focus_test.js index e6eea14..37b01b0 100644 --- a/chrome/test/data/webui/bookmarks/list_focus_test.js +++ b/chrome/test/data/webui/bookmarks/list_focus_test.js
@@ -5,7 +5,7 @@ import {Command} from 'chrome://bookmarks/bookmarks.js'; import {assert} from 'chrome://resources/js/assert.js'; import {isMac} from 'chrome://resources/js/platform.js'; -import {getDeepActiveElement} from 'chrome://resources/js/util.js'; +import {getDeepActiveElement} from 'chrome://resources/js/util_ts.js'; import {keyDownOn} from 'chrome://resources/polymer/v3_0/iron-test-helpers/mock-interactions.js'; import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {flushTasks} from 'chrome://webui-test/polymer_test_util.js';
diff --git a/chrome/test/data/webui/gaia_auth_host/saml_username_autofill_test.js b/chrome/test/data/webui/gaia_auth_host/saml_username_autofill_test.js index 060b29c3..cceb4efa 100644 --- a/chrome/test/data/webui/gaia_auth_host/saml_username_autofill_test.js +++ b/chrome/test/data/webui/gaia_auth_host/saml_username_autofill_test.js
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import {appendParam} from 'chrome://resources/js/util.js'; +import {appendParam} from 'chrome://resources/js/util_ts.js'; import {maybeAutofillUsername} from 'chrome://webui-test/gaia_auth_host/saml_username_autofill.js'; const IDP_URL_FOR_TESTS = 'https://login.corp.example.com/example';
diff --git a/chrome/test/data/webui/invalidations/invalidations_test.js b/chrome/test/data/webui/invalidations/invalidations_test.js index 8f0e5ff..0a72a72 100644 --- a/chrome/test/data/webui/invalidations/invalidations_test.js +++ b/chrome/test/data/webui/invalidations/invalidations_test.js
@@ -3,7 +3,7 @@ // found in the LICENSE file. import {webUIListenerCallback} from 'chrome://resources/js/cr.js'; -import {$} from 'chrome://resources/js/util.js'; +import {$} from 'chrome://resources/js/util_ts.js'; import {assertEquals, assertNotEquals, assertTrue} from 'chrome://webui-test/chai_assert.js'; window.invalidations_test = {};
diff --git a/chrome/test/data/webui/net_internals/dns_view_test.js b/chrome/test/data/webui/net_internals/dns_view_test.js index a73685e..abbea6084 100644 --- a/chrome/test/data/webui/net_internals/dns_view_test.js +++ b/chrome/test/data/webui/net_internals/dns_view_test.js
@@ -3,8 +3,7 @@ // found in the LICENSE file. import {DnsView} from 'chrome://net-internals/dns_view.js'; -import {$} from 'chrome://resources/js/util.js'; - +import {$} from 'chrome://resources/js/util_ts.js'; import {assertEquals} from 'chrome://webui-test/chai_assert.js'; import {Task, TaskQueue} from './task_queue.js';
diff --git a/chrome/test/data/webui/net_internals/domain_security_policy_view_test.js b/chrome/test/data/webui/net_internals/domain_security_policy_view_test.js index 654d57b..e4acd82 100644 --- a/chrome/test/data/webui/net_internals/domain_security_policy_view_test.js +++ b/chrome/test/data/webui/net_internals/domain_security_policy_view_test.js
@@ -3,8 +3,7 @@ // found in the LICENSE file. import {DomainSecurityPolicyView} from 'chrome://net-internals/domain_security_policy_view.js'; -import {$} from 'chrome://resources/js/util.js'; - +import {$} from 'chrome://resources/js/util_ts.js'; import {assertEquals, assertLE, assertNotEquals} from 'chrome://webui-test/chai_assert.js'; import {Task, TaskQueue} from './task_queue.js';
diff --git a/chrome/test/data/webui/sys_internals/page_drawer_test.js b/chrome/test/data/webui/sys_internals/page_drawer_test.js index 39b74de..c5c01615 100644 --- a/chrome/test/data/webui/sys_internals/page_drawer_test.js +++ b/chrome/test/data/webui/sys_internals/page_drawer_test.js
@@ -3,7 +3,7 @@ // found in the LICENSE file. import {PromiseResolver} from 'chrome://resources/js/promise_resolver.js'; -import {$} from 'chrome://resources/js/util.js'; +import {$} from 'chrome://resources/js/util_ts.js'; import {closeDrawer, initialize, openDrawer, promiseResolvers} from 'chrome://sys-internals/index.js'; suite('Page_Drawer', function() {
diff --git a/chrome/test/data/webui/sys_internals/page_infopage_test.js b/chrome/test/data/webui/sys_internals/page_infopage_test.js index 115af67..a9dece0d 100644 --- a/chrome/test/data/webui/sys_internals/page_infopage_test.js +++ b/chrome/test/data/webui/sys_internals/page_infopage_test.js
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import {$} from 'chrome://resources/js/util.js'; +import {$} from 'chrome://resources/js/util_ts.js'; import {handleUpdateData, lineChart, updateInfoPage} from 'chrome://sys-internals/index.js'; import {getTestData} from './test_util.js';
diff --git a/chrome/test/data/webui/sys_internals/page_switch_test.js b/chrome/test/data/webui/sys_internals/page_switch_test.js index 9c096e9..16938a4 100644 --- a/chrome/test/data/webui/sys_internals/page_switch_test.js +++ b/chrome/test/data/webui/sys_internals/page_switch_test.js
@@ -3,7 +3,7 @@ // found in the LICENSE file. import {PromiseResolver} from 'chrome://resources/js/promise_resolver.js'; -import {$} from 'chrome://resources/js/util.js'; +import {$} from 'chrome://resources/js/util_ts.js'; import {PAGE_HASH} from 'chrome://sys-internals/constants.js'; import {handleUpdateData, initialize, isInfoPage, lineChart, promiseResolvers} from 'chrome://sys-internals/index.js';
diff --git a/chrome/test/interaction/README.md b/chrome/test/interaction/README.md index 90059a4..f1997f7 100644 --- a/chrome/test/interaction/README.md +++ b/chrome/test/interaction/README.md
@@ -113,6 +113,8 @@ - `SelectTab()` - `SelectDropdownItem()` - `EnterText()` + - `ActivateSurface()` + - `SendAccelerator()` - `Confirm()` - `DoDefaultAction()` - `NavigateWebContents()` [Browser]
diff --git a/chrome/updater/app/server/linux/update_service_stub.cc b/chrome/updater/app/server/linux/update_service_stub.cc index 5b982a81..00dbf487b 100644 --- a/chrome/updater/app/server/linux/update_service_stub.cc +++ b/chrome/updater/app/server/linux/update_service_stub.cc
@@ -18,6 +18,7 @@ #include "chrome/updater/linux/ipc_constants.h" #include "chrome/updater/registration_data.h" #include "chrome/updater/updater_version.h" +#include "components/named_mojo_ipc_server/named_mojo_ipc_server.h" #include "mojo/public/cpp/bindings/remote.h" namespace updater { @@ -103,9 +104,11 @@ UpdateServiceStub::UpdateServiceStub(scoped_refptr<updater::UpdateService> impl, UpdaterScope scope) - : server_(GetActiveDutySocketPath(scope)->MaybeAsASCII(), - this, - base::BindRepeating(&IsTrustedIPCEndpoint)), + : server_( + GetActiveDutySocketPath(scope)->MaybeAsASCII(), + named_mojo_ipc_server::NamedMojoIpcServerBase::kUseIsolatedConnection, + this, + base::BindRepeating(&IsTrustedIPCEndpoint)), impl_(impl) { server_.set_disconnect_handler(base::BindRepeating( &UpdateServiceStub::OnClientDisconnected, base::Unretained(this))); @@ -227,6 +230,7 @@ : server_( GetActiveDutyInternalSocketPath(scope, base::Version(kUpdaterVersion)) ->MaybeAsASCII(), + named_mojo_ipc_server::NamedMojoIpcServerBase::kUseIsolatedConnection, this, base::BindRepeating(&IsTrustedIPCEndpoint)), impl_(impl) {
diff --git a/chrome/updater/unittest_util.cc b/chrome/updater/unittest_util.cc index 3c24d065..a2bdb141 100644 --- a/chrome/updater/unittest_util.cc +++ b/chrome/updater/unittest_util.cc
@@ -33,6 +33,7 @@ #include <shlobj.h> #include "base/win/windows_version.h" +#include "chrome/updater/util/win_util.h" #endif namespace updater::test { @@ -115,6 +116,11 @@ return; } + if (!IsServiceRunning(L"WinDefend")) { + VLOG(1) << "WinDefend is not running, no need to add exclusion paths."; + return; + } + base::FilePath program_files; base::FilePath program_files_x86; base::FilePath local_app_data;
diff --git a/components/autofill/core/browser/BUILD.gn b/components/autofill/core/browser/BUILD.gn index b72dfec..40734dc 100644 --- a/components/autofill/core/browser/BUILD.gn +++ b/components/autofill/core/browser/BUILD.gn
@@ -269,6 +269,8 @@ "metrics/form_events/form_event_logger_base.cc", "metrics/form_events/form_event_logger_base.h", "metrics/form_events/form_events.h", + "metrics/payments/card_metadata_metrics.cc", + "metrics/payments/card_metadata_metrics.h", "metrics/payments/card_unmask_authentication_metrics.cc", "metrics/payments/card_unmask_authentication_metrics.h", "metrics/payments/credit_card_save_metrics.cc",
diff --git a/components/autofill/core/browser/autofill_suggestion_generator.cc b/components/autofill/core/browser/autofill_suggestion_generator.cc index ef84c9381..a38b214 100644 --- a/components/autofill/core/browser/autofill_suggestion_generator.cc +++ b/components/autofill/core/browser/autofill_suggestion_generator.cc
@@ -19,6 +19,7 @@ #include "components/autofill/core/browser/field_filler.h" #include "components/autofill/core/browser/form_structure.h" #include "components/autofill/core/browser/metrics/autofill_metrics.h" +#include "components/autofill/core/browser/metrics/payments/card_metadata_metrics.h" #include "components/autofill/core/browser/payments/autofill_offer_manager.h" #include "components/autofill/core/browser/personal_data_manager.h" #include "components/autofill/core/browser/ui/suggestion_selection.h" @@ -148,14 +149,15 @@ const FormFieldData& field, const AutofillType& type, const std::string& app_locale, - bool* should_display_gpay_logo, - bool* with_offer) { + bool& should_display_gpay_logo, + bool& with_offer, + autofill_metrics::CardMetadataLoggingContext& metadata_logging_context) { DCHECK(type.group() == FieldTypeGroup::kCreditCard); std::vector<Suggestion> suggestions; std::map<std::string, AutofillOfferData*> card_linked_offers_map = getCardLinkedOffers(autofill_client_); - *with_offer = !card_linked_offers_map.empty(); + with_offer = !card_linked_offers_map.empty(); DCHECK(personal_data_); std::vector<CreditCard*> cards_to_suggest = @@ -173,9 +175,6 @@ }); } - *should_display_gpay_logo = base::ranges::all_of( - cards_to_suggest, base::not_fn(&CreditCard::IsLocalCard)); - // The field value is sanitized before attempting to match it to the user's // data. auto field_contents = SanitizeCreditCardFieldValue(field.value); @@ -190,6 +189,13 @@ std::u16string field_contents_lower = base::i18n::ToLower(field_contents); + metadata_logging_context = GetMetadataLoggingContext(cards_to_suggest); + + // Set `should_display_gpay_logo` to true if all cards are server cards, and + // to false if any of the card is a local card. + should_display_gpay_logo = base::ranges::all_of( + cards_to_suggest, base::not_fn(&CreditCard::IsLocalCard)); + for (const CreditCard* credit_card : cards_to_suggest) { // The value of the stored data for this field type in the |credit_card|. std::u16string creditcard_field_value = @@ -681,6 +687,46 @@ #endif } +autofill_metrics::CardMetadataLoggingContext +AutofillSuggestionGenerator::GetMetadataLoggingContext( + const std::vector<CreditCard*>& cards_to_suggest) const { + bool card_product_description_available = false; + bool card_art_image_available = false; + bool virtual_card_with_card_art_image = false; + + for (const auto* card : cards_to_suggest) { + if (!card->product_description().empty()) + card_product_description_available = true; + + if (card->card_art_url().is_valid()) { + card_art_image_available = true; + if (card->virtual_card_enrollment_state() == + CreditCard::VirtualCardEnrollmentState::ENROLLED) { + virtual_card_with_card_art_image = true; + } + } + } + + autofill_metrics::CardMetadataLoggingContext metadata_logging_context; + metadata_logging_context.card_metadata_available = + card_product_description_available || card_art_image_available; + + metadata_logging_context.card_product_description_shown = + card_product_description_available && + base::FeatureList::IsEnabled(features::kAutofillEnableCardProductName); + + // `card_art_image_shown` is set to true if art image is available and + // 1. the experiment is enabled or + // 2. the card with art image has a linked virtual card (for virtual cards, + // the card art image is always shown if available). + metadata_logging_context.card_art_image_shown = + card_art_image_available && + (base::FeatureList::IsEnabled(features::kAutofillEnableCardArtImage) || + virtual_card_with_card_art_image); + + return metadata_logging_context; +} + InternalId AutofillSuggestionGenerator::BackendIdToInternalId( const Suggestion::BackendId& backend_id) { if (!base::IsValidGUID(*backend_id))
diff --git a/components/autofill/core/browser/autofill_suggestion_generator.h b/components/autofill/core/browser/autofill_suggestion_generator.h index 58a225e..4f56a78 100644 --- a/components/autofill/core/browser/autofill_suggestion_generator.h +++ b/components/autofill/core/browser/autofill_suggestion_generator.h
@@ -20,6 +20,10 @@ namespace autofill { +namespace autofill_metrics { +struct CardMetadataLoggingContext; +} + class AutofillClient; class AutofillField; class AutofillOfferData; @@ -57,12 +61,15 @@ // application. `should_display_gpay_logo` will be set to true if there are no // credit card suggestions, or all suggestions come from Payments server. // `with_offer` is set to true if ANY card has card-linked offers. + // `metadata_logging_context` contains card metadata related information used + // for metrics logging. std::vector<Suggestion> GetSuggestionsForCreditCards( const FormFieldData& field, const AutofillType& type, const std::string& app_locale, - bool* should_display_gpay_logo, - bool* with_offer); + bool& should_display_gpay_logo, + bool& with_offer, + autofill_metrics::CardMetadataLoggingContext& metadata_logging_context); // Generates suggestions for all available IBANs. static std::vector<Suggestion> GetSuggestionsForIBANs( @@ -162,6 +169,11 @@ const CreditCard& credit_card, bool virtual_card_option) const; + // Return the CardMetadataLoggingContext based on the credit cards + // to be shown in the suggestion. + autofill_metrics::CardMetadataLoggingContext GetMetadataLoggingContext( + const std::vector<CreditCard*>& cards_to_suggest) const; + // Maps suggestion backend ID to and from an internal ID identifying it. Two // of these intermediate internal IDs are packed by MakeFrontendID to make the // IDs that this class generates for the UI and for IPC.
diff --git a/components/autofill/core/browser/autofill_suggestion_generator_unittest.cc b/components/autofill/core/browser/autofill_suggestion_generator_unittest.cc index bd24dbbde..503f155 100644 --- a/components/autofill/core/browser/autofill_suggestion_generator_unittest.cc +++ b/components/autofill/core/browser/autofill_suggestion_generator_unittest.cc
@@ -17,6 +17,7 @@ #include "components/autofill/core/browser/data_model/credit_card.h" #include "components/autofill/core/browser/data_model/iban.h" #include "components/autofill/core/browser/form_structure_test_api.h" +#include "components/autofill/core/browser/metrics/payments/card_metadata_metrics.h" #include "components/autofill/core/browser/test_autofill_client.h" #include "components/autofill/core/browser/test_personal_data_manager.h" #include "components/autofill/core/browser/ui/suggestion.h" @@ -372,17 +373,13 @@ GURL("http://www.example1.com")); personal_data()->AddAutofillOfferData(offer_data); - // Create a credit card form. - FormData credit_card_form; - test::CreateTestCreditCardFormData(&credit_card_form, true, false); - FormStructure form_structure(credit_card_form); - form_structure.DetermineHeuristicTypes(nullptr, nullptr); - - bool should_display_gpay_logo = false; - bool with_offer = false; + bool should_display_gpay_logo; + bool with_offer; + autofill_metrics::CardMetadataLoggingContext metadata_logging_context; auto suggestions = suggestion_generator()->GetSuggestionsForCreditCards( FormFieldData(), AutofillType(CREDIT_CARD_NUMBER), - /*app_locale=*/"en", &should_display_gpay_logo, &with_offer); + /*app_locale=*/"en", should_display_gpay_logo, with_offer, + metadata_logging_context); EXPECT_TRUE(with_offer); ASSERT_EQ(suggestions.size(), 3U); @@ -397,6 +394,102 @@ Suggestion::BackendId("00000000-0000-0000-0000-000000000001")); } +// Verifies that the `should_display_gpay_logo` is set correctly. +TEST_F(AutofillSuggestionGeneratorTest, ShouldDisplayGpayLogo) { + // `should_display_gpay_logo` should be true if suggestions were all for + // server cards. + { + // Create two server cards. + personal_data()->AddServerCreditCard(CreateServerCard( + /*guid=*/"00000000-0000-0000-0000-000000000001", + /*server_id=*/"server_id1", /*instrument_id=*/1)); + personal_data()->AddServerCreditCard(CreateServerCard( + /*guid=*/"00000000-0000-0000-0000-000000000002", + /*server_id=*/"server_id2", /*instrument_id=*/2)); + + bool should_display_gpay_logo; + bool with_offer; + autofill_metrics::CardMetadataLoggingContext metadata_logging_context; + auto suggestions = suggestion_generator()->GetSuggestionsForCreditCards( + FormFieldData(), AutofillType(CREDIT_CARD_NUMBER), + /*app_locale=*/"en", should_display_gpay_logo, with_offer, + metadata_logging_context); + + EXPECT_EQ(suggestions.size(), 2U); + EXPECT_TRUE(should_display_gpay_logo); + } + + personal_data()->ClearCreditCards(); + + // `should_display_gpay_logo` should be false if at least one local card was + // in the suggestions. + { + // Create one server card and one local card. + auto local_card = CreateLocalCard( + /*guid=*/"00000000-0000-0000-0000-000000000001"); + local_card.SetNumber(u"5454545454545454"); + personal_data()->AddCreditCard(local_card); + personal_data()->AddServerCreditCard(CreateServerCard( + /*guid=*/"00000000-0000-0000-0000-000000000002", + /*server_id=*/"server_id2", /*instrument_id=*/2)); + + bool should_display_gpay_logo; + bool with_offer; + autofill_metrics::CardMetadataLoggingContext metadata_logging_context; + auto suggestions = suggestion_generator()->GetSuggestionsForCreditCards( + FormFieldData(), AutofillType(CREDIT_CARD_NUMBER), + /*app_locale=*/"en", should_display_gpay_logo, with_offer, + metadata_logging_context); + + EXPECT_EQ(suggestions.size(), 2U); + EXPECT_FALSE(should_display_gpay_logo); + } + + personal_data()->ClearCreditCards(); + + // `should_display_gpay_logo` should be true if there was an unused expired + // local card in the suggestions. + { + // Create one server card and one unused expired local card. + auto local_card = CreateLocalCard( + /*guid=*/"00000000-0000-0000-0000-000000000001"); + local_card.SetNumber(u"5454545454545454"); + local_card.SetExpirationYear(2020); + local_card.set_use_date(AutofillClock::Now() - base::Days(365)); + personal_data()->AddCreditCard(local_card); + personal_data()->AddServerCreditCard(CreateServerCard( + /*guid=*/"00000000-0000-0000-0000-000000000002", + /*server_id=*/"server_id2", /*instrument_id=*/2)); + + bool should_display_gpay_logo; + bool with_offer; + autofill_metrics::CardMetadataLoggingContext metadata_logging_context; + auto suggestions = suggestion_generator()->GetSuggestionsForCreditCards( + FormFieldData(), AutofillType(CREDIT_CARD_NUMBER), + /*app_locale=*/"en", should_display_gpay_logo, with_offer, + metadata_logging_context); + + EXPECT_EQ(suggestions.size(), 1U); + EXPECT_TRUE(should_display_gpay_logo); + } + + personal_data()->ClearCreditCards(); + + // `should_display_gpay_logo` should be true if there was no card at all. + { + bool should_display_gpay_logo; + bool with_offer; + autofill_metrics::CardMetadataLoggingContext metadata_logging_context; + auto suggestions = suggestion_generator()->GetSuggestionsForCreditCards( + FormFieldData(), AutofillType(CREDIT_CARD_NUMBER), + /*app_locale=*/"en", should_display_gpay_logo, with_offer, + metadata_logging_context); + + EXPECT_TRUE(suggestions.empty()); + EXPECT_TRUE(should_display_gpay_logo); + } +} + // Verify that the suggestion's texts are populated correctly for a virtual card // suggestion when the cardholder name field is focused. TEST_F(AutofillSuggestionGeneratorTest, @@ -826,25 +919,42 @@ class AutofillSuggestionGeneratorTestForMetadata : public AutofillSuggestionGeneratorTest, - public testing::WithParamInterface<bool> { + public testing::WithParamInterface<std::tuple<bool, bool, bool>> { public: AutofillSuggestionGeneratorTestForMetadata() - : card_metadata_enabled_(GetParam()) { - scoped_feature_list_metadata_.InitWithFeatureState( - features::kAutofillEnableCardArtImage, card_metadata_enabled_); + : card_product_description_enabled_(std::get<0>(GetParam())), + card_art_image_enabled_(std::get<1>(GetParam())), + card_has_linked_virtual_card_(std::get<2>(GetParam())) { + feature_list_card_product_description_.InitWithFeatureState( + features::kAutofillEnableCardProductName, + card_product_description_enabled_); + feature_list_card_art_image_.InitWithFeatureState( + features::kAutofillEnableCardArtImage, card_art_image_enabled_); } + ~AutofillSuggestionGeneratorTestForMetadata() override = default; - bool card_metadata_enabled() { return card_metadata_enabled_; } + bool card_product_description_enabled() const { + return card_product_description_enabled_; + } + bool card_art_image_enabled() const { return card_art_image_enabled_; } + bool card_has_linked_virtual_card() const { + return card_has_linked_virtual_card_; + } private: - const bool card_metadata_enabled_; - base::test::ScopedFeatureList scoped_feature_list_metadata_; + const bool card_product_description_enabled_; + const bool card_art_image_enabled_; + const bool card_has_linked_virtual_card_; + base::test::ScopedFeatureList feature_list_card_product_description_; + base::test::ScopedFeatureList feature_list_card_art_image_; }; INSTANTIATE_TEST_SUITE_P(All, AutofillSuggestionGeneratorTestForMetadata, - testing::Bool()); + testing::Combine(testing::Bool(), + testing::Bool(), + testing::Bool())); TEST_P(AutofillSuggestionGeneratorTestForMetadata, CreateCreditCardSuggestion_ServerCard) { @@ -879,7 +989,7 @@ Suggestion::BackendId("00000000-0000-0000-0000-000000000001")); EXPECT_EQ(VerifyCardArtImageExpectation(real_card_suggestion, card_art_url, fake_image), - card_metadata_enabled()); + card_art_image_enabled()); } TEST_P(AutofillSuggestionGeneratorTestForMetadata, @@ -940,7 +1050,62 @@ Suggestion::BackendId("00000000-0000-0000-0000-000000000002")); EXPECT_EQ(VerifyCardArtImageExpectation(real_card_suggestion, card_art_url, fake_image), - card_metadata_enabled()); + card_art_image_enabled()); +} + +// Verifies that the `metadata_logging_context` is correctly set. +TEST_P(AutofillSuggestionGeneratorTestForMetadata, + GetSuggestionsForCreditCards_MetadataLoggingContext) { + { + // Create one server card with no metadata. + CreditCard server_card = CreateServerCard(); + if (card_has_linked_virtual_card()) { + server_card.set_virtual_card_enrollment_state( + CreditCard::VirtualCardEnrollmentState::ENROLLED); + } + personal_data()->AddServerCreditCard(server_card); + + bool should_display_gpay_logo; + bool with_offer; + autofill_metrics::CardMetadataLoggingContext metadata_logging_context; + suggestion_generator()->GetSuggestionsForCreditCards( + FormFieldData(), AutofillType(CREDIT_CARD_NUMBER), + /*app_locale=*/"en", should_display_gpay_logo, with_offer, + metadata_logging_context); + + EXPECT_FALSE(metadata_logging_context.card_metadata_available); + EXPECT_FALSE(metadata_logging_context.card_product_description_shown); + EXPECT_FALSE(metadata_logging_context.card_art_image_shown); + } + + personal_data()->ClearCreditCards(); + + { + // Create a server card with card product description & card art image. + CreditCard server_card_with_metadata = CreateServerCard(); + server_card_with_metadata.set_product_description(u"product_description"); + server_card_with_metadata.set_card_art_url( + GURL("https://www.example.com/card-art.png")); + if (card_has_linked_virtual_card()) { + server_card_with_metadata.set_virtual_card_enrollment_state( + CreditCard::VirtualCardEnrollmentState::ENROLLED); + } + personal_data()->AddServerCreditCard(server_card_with_metadata); + + bool should_display_gpay_logo; + bool with_offer; + autofill_metrics::CardMetadataLoggingContext metadata_logging_context; + suggestion_generator()->GetSuggestionsForCreditCards( + FormFieldData(), AutofillType(CREDIT_CARD_NUMBER), + /*app_locale=*/"en", should_display_gpay_logo, with_offer, + metadata_logging_context); + + EXPECT_TRUE(metadata_logging_context.card_metadata_available); + EXPECT_EQ(metadata_logging_context.card_product_description_shown, + card_product_description_enabled()); + EXPECT_EQ(metadata_logging_context.card_art_image_shown, + card_art_image_enabled() || card_has_linked_virtual_card()); + } } class AutofillSuggestionGeneratorTestForOffer
diff --git a/components/autofill/core/browser/browser_autofill_manager.cc b/components/autofill/core/browser/browser_autofill_manager.cc index 740e0ea..171dec6 100644 --- a/components/autofill/core/browser/browser_autofill_manager.cc +++ b/components/autofill/core/browser/browser_autofill_manager.cc
@@ -70,6 +70,7 @@ #include "components/autofill/core/browser/logging/log_manager.h" #include "components/autofill/core/browser/metrics/autofill_metrics.h" #include "components/autofill/core/browser/metrics/form_events/form_events.h" +#include "components/autofill/core/browser/metrics/payments/card_metadata_metrics.h" #include "components/autofill/core/browser/payments/autofill_offer_manager.h" #include "components/autofill/core/browser/payments/credit_card_access_manager.h" #include "components/autofill/core/browser/payments/payments_client.h" @@ -670,7 +671,7 @@ bool should_display_gpay_logo; auto cards = GetCreditCardSuggestions(FormStructure(form), field_data, type, - &should_display_gpay_logo); + should_display_gpay_logo); DCHECK(!cards.empty()); @@ -2475,17 +2476,20 @@ const FormStructure& form_structure, const FormFieldData& field, const AutofillType& type, - bool* should_display_gpay_logo) const { + bool& should_display_gpay_logo) const { credit_card_form_event_logger_->OnDidPollSuggestions(field, sync_state_); std::vector<Suggestion> suggestions; bool with_offer = false; + autofill_metrics::CardMetadataLoggingContext context; if (!IsInAutofillSuggestionsDisabledExperiment()) { suggestions = suggestion_generator_->GetSuggestionsForCreditCards( - field, type, app_locale_, should_display_gpay_logo, &with_offer); + field, type, app_locale_, should_display_gpay_logo, with_offer, + context); } - credit_card_form_event_logger_->OnDidFetchSuggestion(suggestions, with_offer); + credit_card_form_event_logger_->OnDidFetchSuggestion(suggestions, with_offer, + context); return suggestions; } @@ -2959,7 +2963,7 @@ if (context->is_filling_credit_card) { *suggestions = GetCreditCardSuggestions(*context->form_structure, field, context->focused_field->Type(), - &context->should_display_gpay_logo); + context->should_display_gpay_logo); } else { *suggestions = GetProfileSuggestions(*context->form_structure, field, *context->focused_field);
diff --git a/components/autofill/core/browser/browser_autofill_manager.h b/components/autofill/core/browser/browser_autofill_manager.h index 971fa55..06f29602 100644 --- a/components/autofill/core/browser/browser_autofill_manager.h +++ b/components/autofill/core/browser/browser_autofill_manager.h
@@ -602,7 +602,7 @@ const FormStructure& form_structure, const FormFieldData& field, const AutofillType& type, - bool* should_display_gpay_logo) const; + bool& should_display_gpay_logo) const; // If |initial_interaction_timestamp_| is unset or is set to a later time than // |interaction_timestamp|, updates the cached timestamp. The latter check is
diff --git a/components/autofill/core/browser/metrics/autofill_metrics.h b/components/autofill/core/browser/metrics/autofill_metrics.h index a06a434..b91cd5d 100644 --- a/components/autofill/core/browser/metrics/autofill_metrics.h +++ b/components/autofill/core/browser/metrics/autofill_metrics.h
@@ -213,7 +213,13 @@ // requested the issuer to send an OTP, and we can not move on to the next // step in this flow. kDismissedByServerRequestFailure = 4, - kMaxValue = kDismissedByServerRequestFailure, + // User accepted a challenge option in the + // CardUnmaskAuthenticationSelectionDialog that does not require a server + // call to get to the next step in this flow. For instance, in the CVC case, + // we can go directly to the CVC input dialog after the user selects the + // challenge option. + kDismissedByUserAcceptanceNoServerRequestNeeded = 5, + kMaxValue = kDismissedByUserAcceptanceNoServerRequestNeeded, }; // Metrics measuring how well we predict field types. These metric values are
diff --git a/components/autofill/core/browser/metrics/autofill_metrics_unittest.cc b/components/autofill/core/browser/metrics/autofill_metrics_unittest.cc index b4a363e..103d005 100644 --- a/components/autofill/core/browser/metrics/autofill_metrics_unittest.cc +++ b/components/autofill/core/browser/metrics/autofill_metrics_unittest.cc
@@ -6017,6 +6017,112 @@ } } +class AutofillMetricsTestForCardMetadata + : public AutofillMetricsTest, + public testing::WithParamInterface<std::tuple<bool, bool, bool, bool>> { + public: + AutofillMetricsTestForCardMetadata() + : card_product_name_enabled_(std::get<0>(GetParam())), + card_art_image_enabled_(std::get<1>(GetParam())), + card_metadata_available_(std::get<2>(GetParam())), + card_has_linked_virtual_card_(std::get<3>(GetParam())) { + feature_list_card_product_name_.InitWithFeatureState( + features::kAutofillEnableCardProductName, card_product_name_enabled_); + feature_list_card_art_image_.InitWithFeatureState( + features::kAutofillEnableCardArtImage, card_art_image_enabled_); + } + + ~AutofillMetricsTestForCardMetadata() override = default; + + bool card_product_name_enabled() { return card_product_name_enabled_; } + bool card_art_image_enabled() { return card_art_image_enabled_; } + bool card_metadata_available() { return card_metadata_available_; } + bool card_has_linked_virtual_card() { return card_has_linked_virtual_card_; } + + private: + const bool card_product_name_enabled_; + const bool card_art_image_enabled_; + const bool card_metadata_available_; + const bool card_has_linked_virtual_card_; + base::test::ScopedFeatureList feature_list_card_product_name_; + base::test::ScopedFeatureList feature_list_card_art_image_; +}; + +INSTANTIATE_TEST_SUITE_P(All, + AutofillMetricsTestForCardMetadata, + testing::Combine(testing::Bool(), + testing::Bool(), + testing::Bool(), + testing::Bool())); + +// Test that we log card metadata related metrics only when card metadata is +// available. +TEST_P(AutofillMetricsTestForCardMetadata, LogCardMetadataMetrics) { + base::TimeTicks now = AutofillTickClock::NowTicks(); + TestAutofillTickClock test_clock; + test_clock.SetNowTicks(now); + + // Set up the form data. Reset form action to skip the IsFormMixedContent + // check. + FormData form = + GetAndAddSeenForm({.description_for_logging = "CardMetadata", + .fields = {{.role = CREDIT_CARD_NAME_FULL}, + {.role = CREDIT_CARD_NUMBER}, + {.role = CREDIT_CARD_EXP_MONTH}, + {.role = CREDIT_CARD_EXP_2_DIGIT_YEAR}}, + .action = ""}); + + CreditCard masked_server_card = test::GetMaskedServerCard(); + masked_server_card.set_guid(kTestMaskedCardId); + if (card_metadata_available()) { + masked_server_card.set_product_description(u"card_description"); + masked_server_card.set_card_art_url( + GURL("https://www.example.com/cardart.png")); + } + if (card_has_linked_virtual_card()) { + masked_server_card.set_virtual_card_enrollment_state( + CreditCard::VirtualCardEnrollmentState::ENROLLED); + } + personal_data().AddServerCreditCard(masked_server_card); + personal_data().Refresh(); + + // Simulate activating the autofill popup for the credit card field. + base::HistogramTester histogram_tester; + autofill_manager().OnAskForValuesToFillTest(form, form.fields.back()); + autofill_manager().DidShowSuggestions(/*has_autofill_suggestions=*/true, form, + form.fields.back()); + test_clock.SetNowTicks(now + base::Seconds(2)); + autofill_manager().FillOrPreviewForm( + mojom::RendererFormDataAction::kFill, 0, form, form.fields.front(), + MakeFrontendId({.credit_card_id = kTestMaskedCardId})); + + std::string histogram_prefix = + "Autofill.CreditCard.SuggestionAcceptanceLatencySinceShown"; + std::string histogram_name = histogram_prefix; + if (card_metadata_available()) { + // Verify the suggestion acceptance latency was logged when metadata was + // available or the suggestions had one virtual card. + if (card_product_name_enabled() && + (card_art_image_enabled() || card_has_linked_virtual_card())) { + histogram_name += ".ProductDescriptionAndArtImageShown"; + } else if (card_product_name_enabled()) { + histogram_name += ".ProductDescriptionShown"; + } else if (card_art_image_enabled() || card_has_linked_virtual_card()) { + histogram_name += ".ArtImageShown"; + } else { + histogram_name += ".MetadataNotShown"; + } + EXPECT_THAT(histogram_tester.GetTotalCountsForPrefix(histogram_prefix), + ElementsAre(testing::Pair(histogram_name, 1))); + histogram_tester.ExpectUniqueSample(histogram_name, 2000, 1); + } else { + // Verify that no histogram should be logged when metadata was not + // available and the suggestions had no virtual card. + EXPECT_TRUE( + histogram_tester.GetTotalCountsForPrefix(histogram_prefix).empty()); + } +} + // Test that we log parsed form events for address and cards in the same form. TEST_F(AutofillMetricsTest, MixedParsedFormEvents) { FormData form =
diff --git a/components/autofill/core/browser/metrics/form_events/credit_card_form_event_logger.cc b/components/autofill/core/browser/metrics/form_events/credit_card_form_event_logger.cc index 010da3b0..74b8e01 100644 --- a/components/autofill/core/browser/metrics/form_events/credit_card_form_event_logger.cc +++ b/components/autofill/core/browser/metrics/form_events/credit_card_form_event_logger.cc
@@ -19,6 +19,7 @@ #include "components/autofill/core/browser/validation.h" #include "components/autofill/core/common/autofill_internals/log_message.h" #include "components/autofill/core/common/autofill_internals/logging_scope.h" +#include "components/autofill/core/common/autofill_payments_features.h" #include "services/metrics/public/cpp/ukm_builders.h" namespace autofill { @@ -40,8 +41,11 @@ void CreditCardFormEventLogger::OnDidFetchSuggestion( const std::vector<Suggestion>& suggestions, - bool with_offer) { + bool with_offer, + const autofill_metrics::CardMetadataLoggingContext& + metadata_logging_context) { has_eligible_offer_ = with_offer; + metadata_logging_context_ = metadata_logging_context; suggestions_.clear(); for (const auto& suggestion : suggestions) suggestions_.emplace_back(suggestion); @@ -59,6 +63,8 @@ // Also perform the logging actions from the base class: FormEventLoggerBase::OnDidShowSuggestions(form, field, form_parsed_timestamp, sync_state, off_the_record); + + suggestion_shown_timestamp_ = AutofillTickClock::NowTicks(); } void CreditCardFormEventLogger::OnDidSelectCardSuggestion( @@ -97,6 +103,14 @@ } break; } + + // Log the latency between suggestion being shown and suggestion being + // selected. + if (metadata_logging_context_.card_metadata_available) { + autofill_metrics::LogCardSuggestionAcceptanceLatencyMetric( + AutofillTickClock::NowTicks() - suggestion_shown_timestamp_, + metadata_logging_context_); + } } void CreditCardFormEventLogger::OnDidFillSuggestion(
diff --git a/components/autofill/core/browser/metrics/form_events/credit_card_form_event_logger.h b/components/autofill/core/browser/metrics/form_events/credit_card_form_event_logger.h index 67bd2e1..2c340815 100644 --- a/components/autofill/core/browser/metrics/form_events/credit_card_form_event_logger.h +++ b/components/autofill/core/browser/metrics/form_events/credit_card_form_event_logger.h
@@ -15,8 +15,10 @@ #include "components/autofill/core/browser/metrics/autofill_metrics.h" #include "components/autofill/core/browser/metrics/form_events/form_event_logger_base.h" #include "components/autofill/core/browser/metrics/form_events/form_events.h" +#include "components/autofill/core/browser/metrics/payments/card_metadata_metrics.h" #include "components/autofill/core/browser/personal_data_manager.h" #include "components/autofill/core/browser/sync_utils.h" +#include "components/autofill/core/common/autofill_tick_clock.h" #include "components/autofill/core/common/signatures.h" namespace autofill { @@ -47,10 +49,14 @@ is_context_secure_ = is_context_secure; } - // Invoked when |suggestions| are successfully fetched. |with_offer| indicates + // Invoked when `suggestions` are successfully fetched. `with_offer` indicates // whether an offer is attached to any of the suggestion in the list. + // `metadata_logging_context` contains information about whether any card has + // a non-empty product description or art image, and whether they are shown. void OnDidFetchSuggestion(const std::vector<Suggestion>& suggestions, - bool with_offer); + bool with_offer, + const autofill_metrics::CardMetadataLoggingContext& + metadata_logging_context); void OnDidShowSuggestions(const FormStructure& form, const AutofillField& field, @@ -139,6 +145,10 @@ std::vector<Suggestion> suggestions_; bool has_eligible_offer_ = false; bool card_selected_has_offer_ = false; + autofill_metrics::CardMetadataLoggingContext metadata_logging_context_; + + // Set when a list of suggestion is shown. + base::TimeTicks suggestion_shown_timestamp_; // Weak references. raw_ptr<PersonalDataManager> personal_data_manager_;
diff --git a/components/autofill/core/browser/metrics/payments/card_metadata_metrics.cc b/components/autofill/core/browser/metrics/payments/card_metadata_metrics.cc new file mode 100644 index 0000000..52840a0b --- /dev/null +++ b/components/autofill/core/browser/metrics/payments/card_metadata_metrics.cc
@@ -0,0 +1,29 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/autofill/core/browser/metrics/payments/card_metadata_metrics.h" + +#include "base/metrics/histogram_functions.h" + +namespace autofill::autofill_metrics { + +void LogCardSuggestionAcceptanceLatencyMetric( + base::TimeDelta latency, + const CardMetadataLoggingContext& context) { + std::string histogram_name = + "Autofill.CreditCard.SuggestionAcceptanceLatencySinceShown"; + + if (context.card_product_description_shown && context.card_art_image_shown) + histogram_name += ".ProductDescriptionAndArtImageShown"; + else if (context.card_product_description_shown) + histogram_name += ".ProductDescriptionShown"; + else if (context.card_art_image_shown) + histogram_name += ".ArtImageShown"; + else + histogram_name += ".MetadataNotShown"; + + base::UmaHistogramMediumTimes(histogram_name, latency); +} + +} // namespace autofill::autofill_metrics
diff --git a/components/autofill/core/browser/metrics/payments/card_metadata_metrics.h b/components/autofill/core/browser/metrics/payments/card_metadata_metrics.h new file mode 100644 index 0000000..142fd84 --- /dev/null +++ b/components/autofill/core/browser/metrics/payments/card_metadata_metrics.h
@@ -0,0 +1,29 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_AUTOFILL_CORE_BROWSER_METRICS_PAYMENTS_CARD_METADATA_METRICS_H_ +#define COMPONENTS_AUTOFILL_CORE_BROWSER_METRICS_PAYMENTS_CARD_METADATA_METRICS_H_ + +#include "components/autofill/core/browser/metrics/autofill_metrics.h" + +namespace autofill::autofill_metrics { + +// Struct that groups some metadata related information together. Used for +// metrics logging. +struct CardMetadataLoggingContext { + bool card_metadata_available = false; + bool card_product_description_shown = false; + bool card_art_image_shown = false; +}; + +// Log the latency between suggestions being shown and a suggestion was +// selected, in milliseconds. Only logged when at least one card in the +// suggestion list has available card metadata. +void LogCardSuggestionAcceptanceLatencyMetric( + base::TimeDelta latency, + const CardMetadataLoggingContext& context); + +} // namespace autofill::autofill_metrics + +#endif // COMPONENTS_AUTOFILL_CORE_BROWSER_METRICS_PAYMENTS_CARD_METADATA_METRICS_H_
diff --git a/components/autofill/ios/form_util/BUILD.gn b/components/autofill/ios/form_util/BUILD.gn index 6e6a47a..f41a9e7 100644 --- a/components/autofill/ios/form_util/BUILD.gn +++ b/components/autofill/ios/form_util/BUILD.gn
@@ -119,7 +119,6 @@ "//ios/web/public/test", "//ios/web/public/test:test_fixture", "//ios/web/public/test/fakes", - "//ios/web/web_state/js", "//testing/gtest", ] }
diff --git a/components/autofill_assistant/android/BUILD.gn b/components/autofill_assistant/android/BUILD.gn index ac4aa8b0..de36aff 100644 --- a/components/autofill_assistant/android/BUILD.gn +++ b/components/autofill_assistant/android/BUILD.gn
@@ -53,6 +53,7 @@ "//third_party/androidx:androidx_recyclerview_recyclerview_java", "//third_party/androidx:androidx_swiperefreshlayout_swiperefreshlayout_java", "//third_party/blink/public/mojom:android_mojo_bindings_java", + "//ui/accessibility:ax_base_java", "//ui/android:ui_java", "//url:gurl_java", ]
diff --git a/components/autofill_assistant/android/DEPS b/components/autofill_assistant/android/DEPS index 6f9323d..b2a64da5 100644 --- a/components/autofill_assistant/android/DEPS +++ b/components/autofill_assistant/android/DEPS
@@ -14,4 +14,5 @@ "+components/user_prefs", "+content/public/android", "+ui/android", + "+ui/accessibility", ]
diff --git a/components/autofill_assistant/android/java/src/org/chromium/components/autofill_assistant/AutofillAssistantClient.java b/components/autofill_assistant/android/java/src/org/chromium/components/autofill_assistant/AutofillAssistantClient.java index 4a854623..8cfc3090 100644 --- a/components/autofill_assistant/android/java/src/org/chromium/components/autofill_assistant/AutofillAssistantClient.java +++ b/components/autofill_assistant/android/java/src/org/chromium/components/autofill_assistant/AutofillAssistantClient.java
@@ -18,8 +18,8 @@ import org.chromium.components.signin.AccessTokenData; import org.chromium.components.signin.AccountManagerFacadeProvider; import org.chromium.components.signin.identitymanager.IdentityManager; -import org.chromium.content.browser.accessibility.BrowserAccessibilityState; import org.chromium.content_public.browser.WebContents; +import org.chromium.ui.accessibility.AccessibilityState; import java.util.List; @@ -86,16 +86,16 @@ mAccessTokenUtil = accessTokenUtil; // Add listener for accessibility services with "FEEDBACK_SPOKEN" feedback type. - BrowserAccessibilityState.Listener listener = (unused) -> { + AccessibilityState.Listener listener = (unused) -> { if (mNativeClientAndroid == 0) return; AutofillAssistantClientJni.get().onSpokenFeedbackAccessibilityServiceChanged( mNativeClientAndroid, AutofillAssistantClient.this, - BrowserAccessibilityState.hasSpokenFeedbackServicePresent()); + AccessibilityState.hasSpokenFeedbackServicePresent()); }; - // BrowserAccessibilityState listeners are garbage-collected and automatically removed + // AccessibilityState listeners are garbage-collected and automatically removed // from the set of active listeners. - BrowserAccessibilityState.addListener(listener); + AccessibilityState.addListener(listener); } /**
diff --git a/components/autofill_assistant/browser/android/BUILD.gn b/components/autofill_assistant/browser/android/BUILD.gn index 154fb8d0..36173df 100644 --- a/components/autofill_assistant/browser/android/BUILD.gn +++ b/components/autofill_assistant/browser/android/BUILD.gn
@@ -78,6 +78,7 @@ "//google_apis", "//services/metrics/public/cpp:metrics_cpp", "//skia", + "//ui/accessibility:ax_base_android", "//ui/base", "//url", "//url:gurl_android",
diff --git a/components/autofill_assistant/browser/android/DEPS b/components/autofill_assistant/browser/android/DEPS index 98a0a0d..064ead7 100644 --- a/components/autofill_assistant/browser/android/DEPS +++ b/components/autofill_assistant/browser/android/DEPS
@@ -1,3 +1,4 @@ include_rules = [ "+components/keyed_service/content", + "+ui/accessibility", ]
diff --git a/components/autofill_assistant/browser/android/client_android.cc b/components/autofill_assistant/browser/android/client_android.cc index 8195394..71952d3f 100644 --- a/components/autofill_assistant/browser/android/client_android.cc +++ b/components/autofill_assistant/browser/android/client_android.cc
@@ -37,12 +37,12 @@ #include "components/password_manager/core/browser/password_manager_client.h" #include "components/security_state/core/security_state.h" #include "components/version_info/android/channel_getter.h" -#include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/tts_controller.h" #include "content/public/browser/web_contents.h" #include "services/metrics/public/cpp/ukm_recorder.h" +#include "ui/accessibility/android/accessibility_state.h" #include "url/gurl.h" using ::base::android::AppendJavaStringArrayToStringVector; @@ -427,8 +427,7 @@ } bool ClientAndroid::IsSpokenFeedbackAccessibilityServiceEnabled() const { - return content::BrowserAccessibilityState::GetInstance() - ->HasSpokenFeedbackServicePresent(); + return ui::AccessibilityState::HasSpokenFeedbackServicePresent(); } content::WebContents* ClientAndroid::GetWebContents() const {
diff --git a/components/exo/BUILD.gn b/components/exo/BUILD.gn index be0269f..647f60c9 100644 --- a/components/exo/BUILD.gn +++ b/components/exo/BUILD.gn
@@ -23,6 +23,12 @@ sources = [ "buffer.cc", "buffer.h", + "client_controlled_accelerators.cc", + "client_controlled_accelerators.h", + "client_controlled_shell_surface.cc", + "client_controlled_shell_surface.h", + "custom_window_state_delegate.cc", + "custom_window_state_delegate.h", "data_device.cc", "data_device.h", "data_device_delegate.h", @@ -39,17 +45,37 @@ "display.h", "drag_drop_operation.cc", "drag_drop_operation.h", + "extended_drag_offer.cc", + "extended_drag_offer.h", + "extended_drag_source.cc", + "extended_drag_source.h", "frame_sink_resource_manager.cc", "frame_sink_resource_manager.h", + "gamepad.cc", + "gamepad.h", + "gamepad_observer.h", + "gaming_seat.cc", + "gaming_seat.h", + "input_method_surface.cc", + "input_method_surface.h", + "input_method_surface_manager.h", "input_trace.h", "key_state.h", + "keyboard.cc", + "keyboard.h", "keyboard_delegate.h", "keyboard_device_configuration_delegate.h", + "keyboard_modifiers.h", "keyboard_observer.h", "layer_tree_frame_sink_holder.cc", "layer_tree_frame_sink_holder.h", "mime_utils.cc", "mime_utils.h", + "notification.cc", + "notification.h", + "notification_surface.cc", + "notification_surface.h", + "notification_surface_manager.h", "permission.cc", "permission.h", "pointer.cc", @@ -64,6 +90,13 @@ "security_delegate.h", "shared_memory.cc", "shared_memory.h", + "shell_surface.cc", + "shell_surface.h", + "shell_surface_base.cc", + "shell_surface_base.h", + "shell_surface_observer.h", + "shell_surface_presentation_time_recorder.cc", + "shell_surface_presentation_time_recorder.h", "shell_surface_util.cc", "shell_surface_util.h", "sub_surface.cc", @@ -75,21 +108,47 @@ "surface_observer.h", "surface_tree_host.cc", "surface_tree_host.h", + "text_input.cc", + "text_input.h", + "toast_surface.cc", + "toast_surface.h", + "toast_surface_manager.h", "touch.cc", "touch.h", "touch_delegate.h", + "ui_lock_controller.cc", + "ui_lock_controller.h", "vsync_timing_manager.cc", "vsync_timing_manager.h", "window_properties.cc", "window_properties.h", "wm_helper.cc", "wm_helper.h", + "wm_helper_chromeos.cc", + "wm_helper_chromeos.h", + "xdg_shell_surface.cc", + "xdg_shell_surface.h", + "xkb_tracker.cc", + "xkb_tracker.h", ] deps = [ + "//ash", + "//ash/constants", + "//ash/keyboard/ui", + "//ash/public/cpp", + "//ash/resources/vector_icons", "//base", "//build:chromeos_buildflags", "//cc", + "//chromeos/crosapi/cpp:crosapi_constants", + "//chromeos/dbus/power", + "//chromeos/dbus/power:power_manager_proto", + "//chromeos/ui/base", + "//chromeos/ui/frame", + "//components/app_restore", + "//components/fullscreen_control", + "//components/strings", "//components/viz/host", "//device/gamepad", "//device/gamepad/public/cpp:shared_with_blink", @@ -102,6 +161,8 @@ "//third_party/blink/public/common", "//ui/accessibility:ax_base", "//ui/aura", + "//ui/base", + "//ui/base:hit_test", "//ui/base/dragdrop:types", "//ui/base/dragdrop/mojom", "//ui/base/ime", @@ -110,6 +171,7 @@ "//ui/display/manager", "//ui/events/devices:devices", "//ui/events/ozone", + "//ui/events/ozone/layout", "//ui/gfx", "//ui/gfx/geometry", "//ui/gl", @@ -134,76 +196,8 @@ "//ui/base/dragdrop/mojom:mojom_headers", ] - if (is_chromeos_ash) { - deps += [ - "//ash", - "//ash/constants", - "//ash/keyboard/ui", - "//ash/public/cpp", - "//ash/resources/vector_icons", - "//chromeos/crosapi/cpp:crosapi_constants", - "//chromeos/dbus/power", - "//chromeos/dbus/power:power_manager_proto", - "//chromeos/ui/base", - "//chromeos/ui/frame", - "//components/app_restore", - "//components/fullscreen_control", - "//components/strings", - "//ui/base", - "//ui/base:hit_test", - "//ui/events/ozone/layout", - ] - sources += [ - "client_controlled_accelerators.cc", - "client_controlled_accelerators.h", - "client_controlled_shell_surface.cc", - "client_controlled_shell_surface.h", - "custom_window_state_delegate.cc", - "custom_window_state_delegate.h", - "extended_drag_offer.cc", - "extended_drag_offer.h", - "extended_drag_source.cc", - "extended_drag_source.h", - "gamepad.cc", - "gamepad.h", - "gamepad_observer.h", - "gaming_seat.cc", - "gaming_seat.h", - "input_method_surface.cc", - "input_method_surface.h", - "input_method_surface_manager.h", - "keyboard.cc", - "keyboard.h", - "keyboard_modifiers.h", - "notification.cc", - "notification.h", - "notification_surface.cc", - "notification_surface.h", - "notification_surface_manager.h", - "shell_surface.cc", - "shell_surface.h", - "shell_surface_base.cc", - "shell_surface_base.h", - "shell_surface_observer.h", - "shell_surface_presentation_time_recorder.cc", - "shell_surface_presentation_time_recorder.h", - "text_input.cc", - "text_input.h", - "toast_surface.cc", - "toast_surface.h", - "toast_surface_manager.h", - "ui_lock_controller.cc", - "ui_lock_controller.h", - "wm_helper_chromeos.cc", - "wm_helper_chromeos.h", - "xdg_shell_surface.cc", - "xdg_shell_surface.h", - "xkb_tracker.cc", - "xkb_tracker.h", - ] - if (use_xkbcommon) { - configs += [ ":xkbcommon" ] - } + if (use_xkbcommon) { + configs += [ ":xkbcommon" ] } } @@ -213,12 +207,20 @@ sources = [ "mock_vsync_timing_observer.cc", "mock_vsync_timing_observer.h", + "test/exo_test_base.cc", + "test/exo_test_base.h", "test/exo_test_base_views.cc", "test/exo_test_base_views.h", + "test/exo_test_data_exchange_delegate.cc", + "test/exo_test_data_exchange_delegate.h", + "test/exo_test_helper.cc", + "test/exo_test_helper.h", "test/exo_test_suite_aura.cc", "test/exo_test_suite_aura.h", "test/mock_security_delegate.cc", "test/mock_security_delegate.h", + "test/shell_surface_builder.cc", + "test/shell_surface_builder.h", "test/test_security_delegate.cc", "test/test_security_delegate.h", ] @@ -227,8 +229,12 @@ deps = [ ":exo", + "//ash:test_support", + "//ash/public/cpp", "//base", "//base/test:test_support", + "//chromeos/ui/base", + "//components/exo/wayland:weston_test_stub", "//components/viz/service", "//gpu", "//skia", @@ -244,37 +250,67 @@ "//ui/views:test_support", "//ui/wm", ] - - if (is_chromeos_ash) { - sources += [ - "test/exo_test_base.cc", - "test/exo_test_base.h", - "test/exo_test_data_exchange_delegate.cc", - "test/exo_test_data_exchange_delegate.h", - "test/exo_test_helper.cc", - "test/exo_test_helper.h", - "test/shell_surface_builder.cc", - "test/shell_surface_builder.h", - ] - deps += [ - "//ash:test_support", - "//ash/public/cpp", - "//chromeos/ui/base", - "//components/exo/wayland:weston_test_stub", - ] - } } source_set("unit_tests") { testonly = true + sources = [ + "../../ui/events/ozone/gamepad/gamepad_event.cc", + "buffer_unittest.cc", + "client_controlled_shell_surface_unittest.cc", + "data_device_unittest.cc", + "data_offer_unittest.cc", + "data_source_unittest.cc", + "display_unittest.cc", + "drag_drop_operation_unittest.cc", + "event_latency_metrics_unittest.cc", + "extended_drag_source_unittest.cc", + "gamepad_unittest.cc", + "gaming_seat_unittest.cc", + "input_method_surface_unittest.cc", + "keyboard_unittest.cc", + "mime_utils_unittest.cc", + "notification_unittest.cc", + "permission_unittest.cc", + "pointer_unittest.cc", + "seat_unittest.cc", + "shared_memory_unittest.cc", + "shell_surface_presentation_time_recorder_unittest.cc", + "shell_surface_unittest.cc", + "shell_surface_util_unittest.cc", + "sub_surface_unittest.cc", + "surface_test_util.cc", + "surface_test_util.h", + "surface_tree_host_unittest.cc", + "surface_unittest.cc", + "text_input_unittest.cc", + "toast_surface_unittest.cc", + "touch_unittest.cc", + "ui_lock_controller_unittest.cc", + "wm_helper_chromeos_unittest.cc", + "xdg_shell_surface_unittest.cc", + ] + deps = [ ":exo", ":test_support", + "//ash", + "//ash:test_support", + "//ash/constants", + "//ash/keyboard/ui", + "//ash/public/cpp", + "//ash/public/cpp/external_arc", "//base", "//base/test:test_support", + "//build:chromeos_buildflags", "//cc", "//cc:test_support", + "//chromeos/dbus/power", + "//chromeos/dbus/power:power_manager_proto", + "//chromeos/ui/base", + "//chromeos/ui/frame", + "//components/fullscreen_control", "//components/user_manager", "//components/viz/service", "//components/viz/test:test_support", @@ -285,78 +321,23 @@ "//testing/gmock", "//testing/gtest", "//ui/aura", + "//ui/base:test_support", + "//ui/base/cursor/mojom:cursor_type", + "//ui/base/dragdrop:types", + "//ui/base/dragdrop/mojom", + "//ui/base/ime/ash", "//ui/compositor:test_support", "//ui/compositor_extra", "//ui/events:dom_keycode_converter", "//ui/events:test_support", "//ui/events/ozone", "//ui/gfx", + "//ui/gfx:test_support", + "//ui/gfx/geometry", "//ui/message_center", "//ui/views", "//ui/wm", ] - - sources = [ "mime_utils_unittest.cc" ] - - if (is_chromeos_ash) { - sources += [ - "../../ui/events/ozone/gamepad/gamepad_event.cc", - "buffer_unittest.cc", - "client_controlled_shell_surface_unittest.cc", - "data_device_unittest.cc", - "data_offer_unittest.cc", - "data_source_unittest.cc", - "display_unittest.cc", - "drag_drop_operation_unittest.cc", - "event_latency_metrics_unittest.cc", - "extended_drag_source_unittest.cc", - "gamepad_unittest.cc", - "gaming_seat_unittest.cc", - "input_method_surface_unittest.cc", - "keyboard_unittest.cc", - "notification_unittest.cc", - "permission_unittest.cc", - "pointer_unittest.cc", - "seat_unittest.cc", - "shared_memory_unittest.cc", - "shell_surface_presentation_time_recorder_unittest.cc", - "shell_surface_unittest.cc", - "shell_surface_util_unittest.cc", - "sub_surface_unittest.cc", - "surface_test_util.cc", - "surface_test_util.h", - "surface_tree_host_unittest.cc", - "surface_unittest.cc", - "text_input_unittest.cc", - "toast_surface_unittest.cc", - "touch_unittest.cc", - "ui_lock_controller_unittest.cc", - "wm_helper_chromeos_unittest.cc", - "xdg_shell_surface_unittest.cc", - ] - - deps += [ - "//ash", - "//ash:test_support", - "//ash/constants", - "//ash/keyboard/ui", - "//ash/public/cpp", - "//ash/public/cpp/external_arc", - "//build:chromeos_buildflags", - "//chromeos/dbus/power", - "//chromeos/dbus/power:power_manager_proto", - "//chromeos/ui/base", - "//chromeos/ui/frame", - "//components/fullscreen_control", - "//ui/base:test_support", - "//ui/base/cursor/mojom:cursor_type", - "//ui/base/dragdrop:types", - "//ui/base/dragdrop/mojom", - "//ui/base/ime/ash", - "//ui/gfx:test_support", - "//ui/gfx/geometry", - ] - } } test("exo_unittests") { @@ -371,6 +352,9 @@ "//base/test:test_support", "//build:chromeos_buildflags", "//cc:test_support", + "//chromeos/ash/components:test_support", + "//components/exo/server:unit_tests", + "//components/exo/wayland:unit_tests", "//components/viz/test:test_support", "//device/gamepad:test_helpers", "//mojo/core/embedder", @@ -383,15 +367,4 @@ ] data_deps = [] - - if (is_linux || is_chromeos) { - deps += [ "//components/exo/wayland:unit_tests" ] - } - - if (is_chromeos_ash) { - deps += [ - "//chromeos/ash/components:test_support", - "//components/exo/server:unit_tests", - ] - } }
diff --git a/components/exo/wayland/BUILD.gn b/components/exo/wayland/BUILD.gn index 34e5610..581e799 100644 --- a/components/exo/wayland/BUILD.gn +++ b/components/exo/wayland/BUILD.gn
@@ -202,14 +202,6 @@ "//ui/wm/public", ] - if (is_chromeos_ash) { - deps += [ - "//ash", - "//ash/public/cpp", - "//chromeos/ui/base", - ] - } - if (use_xkbcommon) { deps += [ "//ui/events/keycodes:xkb" ] }
diff --git a/components/heavy_ad_intervention/heavy_ad_helper.cc b/components/heavy_ad_intervention/heavy_ad_helper.cc index e2b368c..df08a49 100644 --- a/components/heavy_ad_intervention/heavy_ad_helper.cc +++ b/components/heavy_ad_intervention/heavy_ad_helper.cc
@@ -4,6 +4,8 @@ #include "components/heavy_ad_intervention/heavy_ad_helper.h" +#include <ostream> + #include "base/check.h" #include "base/strings/string_piece.h" #include "components/grit/components_resources.h"
diff --git a/components/history/core/browser/history_backend.cc b/components/history/core/browser/history_backend.cc index 31c8d87a..7331c7d 100644 --- a/components/history/core/browser/history_backend.cc +++ b/components/history/core/browser/history_backend.cc
@@ -1418,6 +1418,12 @@ return false; } +bool HistoryBackend::GetMostRecentVisitForURL(URLID id, VisitRow* visit_row) { + if (db_) + return db_->GetMostRecentVisitForURL(id, visit_row); + return false; +} + bool HistoryBackend::GetMostRecentVisitsForURL(URLID id, int max_visits, VisitVector* visits) {
diff --git a/components/history/core/browser/history_backend.h b/components/history/core/browser/history_backend.h index 21fed113..3eb0db4 100644 --- a/components/history/core/browser/history_backend.h +++ b/components/history/core/browser/history_backend.h
@@ -564,6 +564,8 @@ bool GetVisitsForURL(URLID id, VisitVector* visits); + bool GetMostRecentVisitForURL(URLID id, VisitRow* visit_row) override; + // Fetches up to `max_visits` most recent visits for the passed URL. bool GetMostRecentVisitsForURL(URLID id, int max_visits, VisitVector* visits);
diff --git a/components/history/core/browser/sync/history_backend_for_sync.h b/components/history/core/browser/sync/history_backend_for_sync.h index f72e02c6..761a811 100644 --- a/components/history/core/browser/sync/history_backend_for_sync.h +++ b/components/history/core/browser/sync/history_backend_for_sync.h
@@ -25,6 +25,7 @@ virtual bool GetURLByID(URLID url_id, URLRow* url_row) = 0; virtual bool GetVisitByID(VisitID visit_id, VisitRow* visit_row) = 0; + virtual bool GetMostRecentVisitForURL(URLID id, VisitRow* visit_row) = 0; virtual bool GetLastVisitByTime(base::Time visit_time, VisitRow* visit_row) = 0; virtual VisitVector GetRedirectChain(VisitRow visit) = 0;
diff --git a/components/history/core/browser/sync/history_sync_bridge.cc b/components/history/core/browser/sync/history_sync_bridge.cc index 19314fb..54d0af1 100644 --- a/components/history/core/browser/sync/history_sync_bridge.cc +++ b/components/history/core/browser/sync/history_sync_bridge.cc
@@ -681,14 +681,27 @@ void HistorySyncBridge::OnURLsModified(HistoryBackend* history_backend, const URLRows& changed_urls, bool is_from_expiration) { - // Not interested: This class is watching visits rather than URLs, so - // modifications are handled in OnVisitUpdated(). - // TODO(crbug.com/1318028): The title *can* get updated without a new visit, - // so watch for and commit such changes. Basically: - // - Get most recent visit for the URL. - // - If it's a local visit, and is tracked (and, maybe, is the end of a - // redirect chain): - // - Build the specifics and Put() it. + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + if (!ShouldCommitRightNow()) { + return; + } + + // Not interested in expirations - both the server side and other clients have + // their own, independent expiration logic, so no need to send any updates. + if (is_from_expiration) { + return; + } + + for (const URLRow& url_row : changed_urls) { + VisitRow visit_row; + if (history_backend_->GetMostRecentVisitForURL(url_row.id(), &visit_row) && + visit_row.originator_cache_guid.empty()) { + // It's the URL corresponding to a local visit - probably the title got + // updated. + MaybeCommit(visit_row); + } + } } void HistorySyncBridge::OnURLsDeleted(HistoryBackend* history_backend, @@ -975,7 +988,7 @@ return false; } - // TODO(crbug.com/1318028): Handle updates to the URL-related fields + // TODO(crbug.com/1393079): Handle updates to the URL-related fields // (notably the title - other fields probably can't change). return true; }
diff --git a/components/history/core/browser/sync/history_sync_bridge_unittest.cc b/components/history/core/browser/sync/history_sync_bridge_unittest.cc index 47180852..6ee98c5 100644 --- a/components/history/core/browser/sync/history_sync_bridge_unittest.cc +++ b/components/history/core/browser/sync/history_sync_bridge_unittest.cc
@@ -797,6 +797,39 @@ visit_duration); } +TEST_F(HistorySyncBridgeTest, UploadsUpdatedUrlTitle) { + // Start syncing (with no data yet). + ApplyInitialSyncChanges({}); + + // Visit a URL. + auto [url_row, visit_row] = AddVisitToBackendAndAdvanceClock( + GURL("https://www.url.com"), ui::PAGE_TRANSITION_TYPED); + + // Notify the bridge about the visit - it should be sent to the processor. + bridge()->OnURLVisited( + /*history_backend=*/nullptr, url_row, visit_row); + + const std::string storage_key = + HistorySyncMetadataDatabase::StorageKeyFromVisitTime( + visit_row.visit_time); + ASSERT_EQ(processor()->GetEntities().size(), 1u); + ASSERT_EQ(processor()->GetEntities().count(storage_key), 1u); + + // Update the URL's title. + const std::string new_title("New title!"); + url_row.set_title(base::ASCIIToUTF16(new_title)); + ASSERT_TRUE(backend()->UpdateURL(url_row)); + bridge()->OnURLsModified(/*history_backend=*/nullptr, {url_row}, + /*is_from_expiration=*/false); + + // The updated data should have been sent to the processor. + EXPECT_EQ(processor()->GetEntities().size(), 1u); + ASSERT_EQ(processor()->GetEntities().count(storage_key), 1u); + const syncer::EntityData& entity = processor()->GetEntities().at(storage_key); + ASSERT_EQ(entity.specifics.history().redirect_entries().size(), 1); + EXPECT_EQ(entity.specifics.history().redirect_entries(0).title(), new_title); +} + TEST_F(HistorySyncBridgeTest, UploadsLocalVisitWithRedirects) { // Start syncing (with no data yet). ApplyInitialSyncChanges({});
diff --git a/components/history/core/browser/sync/test_history_backend_for_sync.cc b/components/history/core/browser/sync/test_history_backend_for_sync.cc index 8a7040d..2a14eec 100644 --- a/components/history/core/browser/sync/test_history_backend_for_sync.cc +++ b/components/history/core/browser/sync/test_history_backend_for_sync.cc
@@ -20,6 +20,17 @@ return id; } +bool TestHistoryBackendForSync::UpdateURL(URLRow row) { + DCHECK_NE(row.id(), 0); + for (URLRow& url : urls_) { + if (url.id() == row.id()) { + url = row; + return true; + } + } + return false; +} + VisitID TestHistoryBackendForSync::AddVisit(VisitRow row) { DCHECK_EQ(row.visit_id, 0); VisitID id = next_visit_id_++; @@ -95,6 +106,20 @@ return false; } +bool TestHistoryBackendForSync::GetMostRecentVisitForURL(URLID id, + VisitRow* visit_row) { + *visit_row = VisitRow(); + for (const VisitRow& candidate : visits_) { + if (candidate.url_id == id && + (candidate.visit_time > visit_row->visit_time || + (candidate.visit_time == visit_row->visit_time && + candidate.visit_id > visit_row->visit_id))) { + *visit_row = candidate; + } + } + return visit_row->visit_id != 0; +} + bool TestHistoryBackendForSync::GetLastVisitByTime(base::Time visit_time, VisitRow* visit_row) { *visit_row = VisitRow();
diff --git a/components/history/core/browser/sync/test_history_backend_for_sync.h b/components/history/core/browser/sync/test_history_backend_for_sync.h index 17864076..274961f7 100644 --- a/components/history/core/browser/sync/test_history_backend_for_sync.h +++ b/components/history/core/browser/sync/test_history_backend_for_sync.h
@@ -25,6 +25,7 @@ // Methods to manipulate the contents. These do *not* notify the observers. URLID AddURL(URLRow row); + bool UpdateURL(URLRow row); VisitID AddVisit(VisitRow row); bool UpdateVisit(VisitRow row); @@ -40,6 +41,7 @@ bool IsExpiredVisitTime(const base::Time& time) const override; bool GetURLByID(URLID url_id, URLRow* url_row) override; bool GetVisitByID(VisitID visit_id, VisitRow* visit_row) override; + bool GetMostRecentVisitForURL(URLID id, VisitRow* visit_row) override; bool GetLastVisitByTime(base::Time visit_time, VisitRow* visit_row) override; VisitVector GetRedirectChain(VisitRow visit) override; bool GetForeignVisit(const std::string& originator_cache_guid,
diff --git a/components/lens/lens_features.cc b/components/lens/lens_features.cc index 1d1bd83..081a08a 100644 --- a/components/lens/lens_features.cc +++ b/components/lens/lens_features.cc
@@ -30,6 +30,10 @@ "LensImageLatencyLogging", base::FEATURE_ENABLED_BY_DEFAULT); +BASE_FEATURE(kEnableRegionSearchKeyboardShortcut, + "LensEnableRegionSearchKeyboardShortcut", + base::FEATURE_DISABLED_BY_DEFAULT); + BASE_FEATURE(kEnableRegionSearchOnPdfViewer, "LensEnableRegionSearchOnPdfViewer", base::FEATURE_ENABLED_BY_DEFAULT);
diff --git a/components/lens/lens_features.h b/components/lens/lens_features.h index 69ea044..3bd7689 100644 --- a/components/lens/lens_features.h +++ b/components/lens/lens_features.h
@@ -36,6 +36,10 @@ COMPONENT_EXPORT(LENS_FEATURES) BASE_DECLARE_FEATURE(kEnableLatencyLogging); +// Enable keyboard shortcut for the Lens Region Search feature. +COMPONENT_EXPORT(LENS_FEATURES) +BASE_DECLARE_FEATURE(kEnableRegionSearchKeyboardShortcut); + // Enable the Lens Region Search feature on the PDF viewer. COMPONENT_EXPORT(LENS_FEATURES) BASE_DECLARE_FEATURE(kEnableRegionSearchOnPdfViewer);
diff --git a/components/named_mojo_ipc_server/README.md b/components/named_mojo_ipc_server/README.md index 5d5fbab..107e466 100644 --- a/components/named_mojo_ipc_server/README.md +++ b/components/named_mojo_ipc_server/README.md
@@ -1,29 +1,12 @@ -# Named Mojo IPC Server - -This component provides a helper that uses a mojo::NamedPlatformChannel to -manage multiple concurrent IPCs. Clients that connect to the -NamedPlatformChannel are sent invitations to join an isolated IPC graph -suitable only for direct IPC between the two processes. - -## Caveats - -The isolated connections managed by NamedMojoIpcServer can only be used to -connect two nodes which have been initialized as Mojo brokers. That is, -the `is_broker_process` field in the configuration passed to `mojo::core::Init` -must be set to true. This assumes that these isolated connections effectively -only go between two standalone (i.e. non-Chrome) processes, or between some -standalone process and the browser process; but never between two existing -Chrome processes, or between a standalone process and one of Chrome's child -processes. - -A restriction of isolated connections is that Mojo remotes, receivers, or -message pipes cannot be passed outside of the boundary of the process pairs. -For example, the server cannot be used broker connections between two clients. +This component provides a helper that allows a server process to handle multiple +concurrent IPCs coming through a `NamedPlatformChannel`. ## Example usage In the server process: ```cpp +static const uint64_t kMessagePipeId = 0u; + class MyInterfaceImpl: public mojom::MyInterface { void Start() { server_.set_disconnect_handler( @@ -43,21 +26,38 @@ server_.Close(server_.current_receiver()); } - MojoIpcServer<mojom::MyInterface> server_{"my_server_name", this}; + static bool IsTrustedMojoEndpoint(base::ProcessId caller_pid) { + // Verify the calling process... + return true; + } + + NamedMojoIpcServer<mojom::MyInterface> server_{"my_server_name", + kMessagePipeId, this, + base::BindRepeating(&MyInterfaceImpl::IsTrustedMojoEndpoint)}; }; ``` +Note: In unittests `base::test:TaskEnvironment` should run until idle after +`NamedMojoIpcServer` is shutdown. Otherwise, memory may leak. E.g: + +```cpp +void MyTestFixture::TearDown() { + ipc_server_->StopServer(); + task_environment_.RunUntilIdle(); + } +``` + In the client: ```cpp void ConnectToServer() { mojo::PlatformChannelEndpoint endpoint = mojo::NamedPlatformChannel::ConnectToServer("my_server_name"); - -std::unique_ptr<mojo::IsolatedConnection> connection = - std::make_unique<mojo::IsolatedConnection>(); - +auto invitation = mojo::IncomingInvitation::Accept(std::move(endpoint)); mojo::Remote<mojom::MyInterface> remote( mojo::PendingRemote<mojom::MyInterface>( - connection->Connect(std::move(endpoint)), 0)); + invitation.ExtractMessagePipe(kMessagePipeId), 0)); } ``` + +On Windows, the server needs to have the following access rights on the client +process: `PROCESS_DUP_HANDLE | PROCESS_QUERY_INFORMATION`.
diff --git a/components/named_mojo_ipc_server/named_mojo_ipc_server.cc b/components/named_mojo_ipc_server/named_mojo_ipc_server.cc index 2439c07..4d720a5 100644 --- a/components/named_mojo_ipc_server/named_mojo_ipc_server.cc +++ b/components/named_mojo_ipc_server/named_mojo_ipc_server.cc
@@ -4,6 +4,8 @@ #include "components/named_mojo_ipc_server/named_mojo_ipc_server.h" +#include <stdint.h> + #include <memory> #include "base/bind.h" @@ -12,13 +14,22 @@ #include "base/logging.h" #include "base/memory/weak_ptr.h" #include "base/notreached.h" +#include "base/process/process.h" #include "base/task/thread_pool.h" #include "base/threading/sequence_bound.h" #include "base/time/time.h" #include "build/build_config.h" #include "components/named_mojo_ipc_server/named_mojo_server_endpoint_connector.h" +#include "mojo/public/cpp/bindings/receiver_set.h" +#include "mojo/public/cpp/platform/platform_channel_endpoint.h" +#include "mojo/public/cpp/system/invitation.h" +#include "mojo/public/cpp/system/isolated_connection.h" +#include "mojo/public/cpp/system/message_pipe.h" +#include "third_party/abseil-cpp/absl/types/optional.h" #if BUILDFLAG(IS_WIN) +#include <windows.h> + #include "base/strings/stringprintf.h" #include "base/win/win_util.h" #endif // BUILDFLAG(IS_WIN) @@ -64,12 +75,10 @@ NamedMojoIpcServerBase::DelegateProxy::~DelegateProxy() = default; void NamedMojoIpcServerBase::DelegateProxy::OnServerEndpointConnected( - std::unique_ptr<mojo::IsolatedConnection> connection, - mojo::ScopedMessagePipeHandle message_pipe, + mojo::PlatformChannelEndpoint endpoint, base::ProcessId peer_pid) { if (server_) - server_->OnServerEndpointConnected(std::move(connection), - std::move(message_pipe), peer_pid); + server_->OnServerEndpointConnected(std::move(endpoint), peer_pid); } void NamedMojoIpcServerBase::DelegateProxy::OnServerEndpointConnectionFailed() { @@ -79,8 +88,10 @@ NamedMojoIpcServerBase::NamedMojoIpcServerBase( const mojo::NamedPlatformChannel::ServerName& server_name, + absl::optional<uint64_t> message_pipe_id, IsTrustedMojoEndpointCallback is_trusted_endpoint_callback) : server_name_(server_name), + message_pipe_id_(message_pipe_id), is_trusted_endpoint_callback_(std::move(is_trusted_endpoint_callback)) { io_sequence_ = base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()}); @@ -103,7 +114,7 @@ weak_factory_.GetWeakPtr()), io_sequence_); server_started_ = true; - SendInvitation(); + CreateServerEndpoint(); } void NamedMojoIpcServerBase::StopServer() { @@ -126,7 +137,7 @@ } } -void NamedMojoIpcServerBase::SendInvitation() { +void NamedMojoIpcServerBase::CreateServerEndpoint() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); io_sequence_->PostTaskAndReplyWithResult( @@ -163,24 +174,62 @@ } void NamedMojoIpcServerBase::OnServerEndpointConnected( - std::unique_ptr<mojo::IsolatedConnection> connection, - mojo::ScopedMessagePipeHandle message_pipe, + mojo::PlatformChannelEndpoint endpoint, base::ProcessId peer_pid) { - if (is_trusted_endpoint_callback_.Run(peer_pid)) { - auto receiver_id = TrackMessagePipe(std::move(message_pipe), peer_pid); - active_connections_[receiver_id] = std::move(connection); - } else { - LOG(ERROR) << "Process " << peer_pid - << " is not a trusted mojo endpoint. Connection refused."; - } - - SendInvitation(); + PassAndTrackMessagePipe(std::move(endpoint), peer_pid); + CreateServerEndpoint(); } void NamedMojoIpcServerBase::OnServerEndpointConnectionFailed() { resend_invitation_on_error_timer_.Start( FROM_HERE, kResentInvitationOnErrorDelay, this, - &NamedMojoIpcServerBase::SendInvitation); + &NamedMojoIpcServerBase::CreateServerEndpoint); +} + +void NamedMojoIpcServerBase::PassAndTrackMessagePipe( + mojo::PlatformChannelEndpoint endpoint, + base::ProcessId peer_pid) { + if (!is_trusted_endpoint_callback_.Run(peer_pid)) { + LOG(ERROR) << "Process " << peer_pid + << " is not a trusted mojo endpoint. Connection refused."; + return; + } + + if (!message_pipe_id_.has_value()) { + // Create isolated connection. + auto connection = std::make_unique<mojo::IsolatedConnection>(); + mojo::ScopedMessagePipeHandle message_pipe = + connection->Connect(std::move(endpoint)); + mojo::ReceiverId receiver_id = + TrackMessagePipe(std::move(message_pipe), peer_pid); + active_connections_[receiver_id] = std::move(connection); + return; + } + + // Create non-isolated connection. + mojo::OutgoingInvitation invitation; + mojo::ScopedMessagePipeHandle message_pipe = + invitation.AttachMessagePipe(*message_pipe_id_); +#if BUILDFLAG(IS_WIN) + // Open process with minimum permissions since the client process might have + // restricted its access with DACL. + base::Process peer_process = + base::Process::OpenWithAccess(peer_pid, PROCESS_DUP_HANDLE); +// Windows opens the process with a system call so we use PLOG to extract more +// info. Other OSes (i.e. POSIX) don't do that. +#define INVALID_PROCESS_LOG PLOG +#else + base::Process peer_process = base::Process::Open(peer_pid); +#define INVALID_PROCESS_LOG LOG +#endif + if (!peer_process.IsValid()) { + INVALID_PROCESS_LOG(ERROR) << "Failed to open peer process"; + return; + } +#undef INVALID_PROCESS_LOG + mojo::OutgoingInvitation::Send(std::move(invitation), peer_process.Handle(), + std::move(endpoint)); + TrackMessagePipe(std::move(message_pipe), peer_pid); } } // namespace named_mojo_ipc_server
diff --git a/components/named_mojo_ipc_server/named_mojo_ipc_server.h b/components/named_mojo_ipc_server/named_mojo_ipc_server.h index da08f1b6..f4ddc05 100644 --- a/components/named_mojo_ipc_server/named_mojo_ipc_server.h +++ b/components/named_mojo_ipc_server/named_mojo_ipc_server.h
@@ -5,6 +5,8 @@ #ifndef COMPONENTS_NAMED_MOJO_IPC_SERVER_NAMED_MOJO_IPC_SERVER_H_ #define COMPONENTS_NAMED_MOJO_IPC_SERVER_NAMED_MOJO_IPC_SERVER_H_ +#include <stdint.h> + #include <memory> #include <utility> @@ -25,9 +27,10 @@ #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/receiver_set.h" #include "mojo/public/cpp/platform/named_platform_channel.h" +#include "mojo/public/cpp/platform/platform_channel_endpoint.h" #include "mojo/public/cpp/platform/platform_channel_server_endpoint.h" #include "mojo/public/cpp/system/message_pipe.h" -#include "mojo/public/cpp/system/simple_watcher.h" +#include "third_party/abseil-cpp/absl/types/optional.h" namespace mojo { class IsolatedConnection; @@ -41,6 +44,11 @@ using IsTrustedMojoEndpointCallback = base::RepeatingCallback<bool(base::ProcessId)>; + // DEPRECATED: New callers should not use an isolated connection. Pass a + // valid message pipe ID instead. + static constexpr absl::optional<uint64_t> kUseIsolatedConnection = + absl::nullopt; + // Internal use only. struct PendingConnection; @@ -55,17 +63,14 @@ on_server_endpoint_created_callback_for_testing_ = callback; } - size_t GetNumberOfActiveConnectionsForTesting() const { - return active_connections_.size(); - } - protected: NamedMojoIpcServerBase( const mojo::NamedPlatformChannel::ServerName& server_name, + absl::optional<uint64_t> message_pipe_id, IsTrustedMojoEndpointCallback is_trusted_endpoint_callback); ~NamedMojoIpcServerBase() override; - void SendInvitation(); + void CreateServerEndpoint(); void OnIpcDisconnected(); @@ -91,10 +96,8 @@ ~DelegateProxy() override; // Overrides for NamedMojoServerEndpointConnector::Delegate - void OnServerEndpointConnected( - std::unique_ptr<mojo::IsolatedConnection> connection, - mojo::ScopedMessagePipeHandle message_pipe, - base::ProcessId peer_pid) override; + void OnServerEndpointConnected(mojo::PlatformChannelEndpoint endpoint, + base::ProcessId peer_pid) override; void OnServerEndpointConnectionFailed() override; private: @@ -103,17 +106,19 @@ void OnServerEndpointCreated(mojo::PlatformChannelServerEndpoint endpoint); - void OnServerEndpointConnected( - std::unique_ptr<mojo::IsolatedConnection> connection, - mojo::ScopedMessagePipeHandle message_pipe, - base::ProcessId peer_pid); + void OnServerEndpointConnected(mojo::PlatformChannelEndpoint endpoint, + base::ProcessId peer_pid); void OnServerEndpointConnectionFailed(); + void PassAndTrackMessagePipe(mojo::PlatformChannelEndpoint endpoint, + base::ProcessId peer_pid); + using ActiveConnectionMap = base::flat_map<mojo::ReceiverId, std::unique_ptr<mojo::IsolatedConnection>>; mojo::NamedPlatformChannel::ServerName server_name_; + absl::optional<uint64_t> message_pipe_id_; IsTrustedMojoEndpointCallback is_trusted_endpoint_callback_; bool server_started_ = false; @@ -122,7 +127,10 @@ scoped_refptr<base::SequencedTaskRunner> io_sequence_; base::SequenceBound<NamedMojoServerEndpointConnector> endpoint_connector_; + + // This is only populated if the server uses isolated connections. ActiveConnectionMap active_connections_; + base::OneShotTimer resend_invitation_on_error_timer_; base::RepeatingClosure on_server_endpoint_created_callback_for_testing_ = @@ -134,53 +142,24 @@ // A helper that uses a NamedPlatformChannel to send out mojo invitations and // maintains multiple concurrent IPCs. It keeps one outgoing invitation at a // time and will send a new invitation whenever the previous one has been -// accepted by the client. -// -// Example usage: -// -// class MyInterfaceImpl: public mojom::MyInterface { -// void Start() { -// server_.set_disconnect_handler( -// base::BindRepeating(&MyInterfaceImpl::OnDisconnected, this)); -// server_.StartServer(); -// } - -// void OnDisconnected() { -// LOG(INFO) << "Receiver disconnected: " << server_.current_receiver(); -// } - -// // mojom::MyInterface Implementation. -// void DoWork() override { -// // Do something... - -// // If you want to close the connection: -// server_.Close(server_.current_receiver()); -// } - -// static bool IsTrustedMojoEndpoint(base::ProcessId caller_pid) { -// // Verify the calling process... -// return true; -// } - -// MojoIpcServer<mojom::MyInterface> server_{"my_server_name", this, -// base::BindRepeating(&MyInterfaceImpl::IsTrustedMojoEndpoint)}; -// }; -// Note: In unittests base::test:TaskEnvironment run until idle after -// NamedMojoIpcServer is shutdown. Otherwise, memory may leak. E.g: -// void MyTestFixture::TearDown() { -// ipc_server_->StopServer(); -// task_environment_.RunUntilIdle(); -// } +// accepted by the client. Please see README.md for the example usage. template <typename Interface> class NamedMojoIpcServer final : public NamedMojoIpcServerBase { public: // server_name: The server name to start the NamedPlatformChannel. + // message_pipe_id: The message pipe ID. If provided, the client must call + // ExtractMessagePipe() with the same ID. If not provided (or + // kUseIsolatedConnection is used), the client must connect using an + // isolated connection. Note that using an isolated connection is + // DEPRECATED and new callers should always pass a valid message pipe ID. // is_trusted_endpoint_callback: A predicate which returns true if the process // referred to by the caller PID is a trusted mojo endpoint. NamedMojoIpcServer(const mojo::NamedPlatformChannel::ServerName& server_name, + absl::optional<uint64_t> message_pipe_id, Interface* interface_impl, IsTrustedMojoEndpointCallback is_trusted_endpoint_callback) : NamedMojoIpcServerBase(server_name, + message_pipe_id, std::move(is_trusted_endpoint_callback)), interface_impl_(interface_impl) { receiver_set_.set_disconnect_handler(base::BindRepeating( @@ -204,6 +183,10 @@ return receiver_set_.current_context(); } + size_t GetNumberOfActiveConnectionsForTesting() const { + return receiver_set_.size(); + } + private: // NamedMojoIpcServerBase implementation. mojo::ReceiverId TrackMessagePipe(mojo::ScopedMessagePipeHandle message_pipe,
diff --git a/components/named_mojo_ipc_server/named_mojo_ipc_server_unittest.cc b/components/named_mojo_ipc_server/named_mojo_ipc_server_unittest.cc index 22b00be1..5a6de54 100644 --- a/components/named_mojo_ipc_server/named_mojo_ipc_server_unittest.cc +++ b/components/named_mojo_ipc_server/named_mojo_ipc_server_unittest.cc
@@ -33,6 +33,7 @@ #include "mojo/public/cpp/bindings/remote.h" #include "mojo/public/cpp/platform/named_platform_channel.h" #include "mojo/public/cpp/platform/platform_channel_endpoint.h" +#include "mojo/public/cpp/system/invitation.h" #include "mojo/public/cpp/system/isolated_connection.h" #include "mojo/public/cpp/system/message_pipe.h" #include "testing/gmock/include/gmock/gmock.h" @@ -58,9 +59,14 @@ "named-mojo-ipc-server-test-hang-after-connect"; static const char kClientProcessWaitUntilDisconnectedSwitch[] = "named-mojo-ipc-server-test-wait-until-disconnected"; +static const char kClientProcessUseIsolatedConnectionSwitch[] = + "named-mojo-ipc-server-test-use-isolated-connection"; static constexpr int kInvalidEndpointExitCode = 42; +static constexpr uint64_t kTestMessagePipeId = 0u; -class NamedMojoIpcServerTest : public testing::Test, public test::mojom::Echo { +class NamedMojoIpcServerTest + : public testing::TestWithParam</* is_isolated= */ bool>, + public test::mojom::Echo { public: NamedMojoIpcServerTest(); ~NamedMojoIpcServerTest() override; @@ -132,8 +138,10 @@ void NamedMojoIpcServerTest::CreateIpcServer() { ipc_server_ = std::make_unique<NamedMojoIpcServer<test::mojom::Echo>>( - test_server_name_, this, - base::BindRepeating([](base::ProcessId) { return true; })); + test_server_name_, + GetParam() ? NamedMojoIpcServerBase::kUseIsolatedConnection + : kTestMessagePipeId, + this, base::BindRepeating([](base::ProcessId) { return true; })); ipc_server_->set_on_server_endpoint_created_callback_for_testing( base::BindRepeating(&NamedMojoIpcServerTest::OnServerEndpointCreated, base::Unretained(this))); @@ -152,6 +160,9 @@ if (!extra_switch.empty()) { cmd_line.AppendSwitch(extra_switch); } + if (GetParam()) { + cmd_line.AppendSwitch(kClientProcessUseIsolatedConnectionSwitch); + } return base::SpawnMultiProcessTestChild(kEchoClientName, cmd_line, /* options= */ {}); } @@ -192,14 +203,14 @@ on_server_endpoint_created_run_loop_->Quit(); } -TEST_F(NamedMojoIpcServerTest, SendEcho) { +TEST_P(NamedMojoIpcServerTest, SendEcho) { base::Process child_process = LaunchClientProcess(); base::ProcessId child_pid = child_process.Pid(); EXPECT_EQ(0, WaitForProcessExit(child_process)); EXPECT_EQ(child_pid, last_echo_string_peer_pid_); } -TEST_F(NamedMojoIpcServerTest, DeleteNamedMojoServer_NoLingeringInvitations) { +TEST_P(NamedMojoIpcServerTest, DeleteNamedMojoServer_NoLingeringInvitations) { ipc_server_.reset(); base::RunLoop().RunUntilIdle(); // For posix, the socket doesn't seem to be closed immediately after the @@ -211,7 +222,7 @@ EXPECT_EQ(kInvalidEndpointExitCode, WaitForProcessExit(child_process)); } -TEST_F(NamedMojoIpcServerTest, DisconnectHandler) { +TEST_P(NamedMojoIpcServerTest, DisconnectHandler) { base::RunLoop disconnect_run_loop; base::MockCallback<base::RepeatingClosure> disconnect_handler; EXPECT_CALL(disconnect_handler, Run()).WillOnce([&]() { @@ -226,7 +237,7 @@ disconnect_run_loop.Run(); } -TEST_F(NamedMojoIpcServerTest, DeleteNamedMojoServer_RemoteDisconnected) { +TEST_P(NamedMojoIpcServerTest, DeleteNamedMojoServer_RemoteDisconnected) { base::RunLoop wait_for_echo_string_called_run_loop; on_echo_string_called_ = wait_for_echo_string_called_run_loop.QuitClosure(); base::Process child_process = @@ -237,7 +248,7 @@ WaitForProcessExit(child_process); } -TEST_F(NamedMojoIpcServerTest, StopServer_RemoteDisconnected) { +TEST_P(NamedMojoIpcServerTest, StopServer_RemoteDisconnected) { base::RunLoop wait_for_echo_string_called_run_loop; on_echo_string_called_ = wait_for_echo_string_called_run_loop.QuitClosure(); base::Process child_process = @@ -248,7 +259,7 @@ WaitForProcessExit(child_process); } -TEST_F(NamedMojoIpcServerTest, CloseReceiver_RemoteDisconnected) { +TEST_P(NamedMojoIpcServerTest, CloseReceiver_RemoteDisconnected) { base::RunLoop wait_for_echo_string_called_run_loop; on_echo_string_called_ = wait_for_echo_string_called_run_loop.QuitClosure(); base::Process child_process = @@ -261,13 +272,13 @@ ASSERT_EQ(0u, ipc_server_->GetNumberOfActiveConnectionsForTesting()); } -TEST_F(NamedMojoIpcServerTest, CloseNonexistentReceiver_NoCrash) { +TEST_P(NamedMojoIpcServerTest, CloseNonexistentReceiver_NoCrash) { ASSERT_EQ(0u, ipc_server_->GetNumberOfActiveConnectionsForTesting()); ipc_server_->Close(1u); ASSERT_EQ(0u, ipc_server_->GetNumberOfActiveConnectionsForTesting()); } -TEST_F(NamedMojoIpcServerTest, RemoteProcessTerminated_ConnectionRemoved) { +TEST_P(NamedMojoIpcServerTest, RemoteProcessTerminated_ConnectionRemoved) { base::RunLoop wait_for_echo_string_called_run_loop; on_echo_string_called_ = wait_for_echo_string_called_run_loop.QuitClosure(); base::Process child_process = @@ -282,7 +293,7 @@ ASSERT_EQ(0u, ipc_server_->GetNumberOfActiveConnectionsForTesting()); } -TEST_F(NamedMojoIpcServerTest, +TEST_P(NamedMojoIpcServerTest, RemoteTerminatedBeforeBound_NewServerEndpointCreated) { base::Process child_process = LaunchClientProcess(kClientProcessExitAfterConnectSwitch); @@ -290,14 +301,14 @@ WaitForServerEndpointCreated(); } -TEST_F(NamedMojoIpcServerTest, +TEST_P(NamedMojoIpcServerTest, RemoteConnectsAndHangs_NewServerEndpointCreated) { base::Process child_process = LaunchClientProcess(kClientProcessHangAfterConnectSwitch); WaitForServerEndpointCreated(); } -TEST_F(NamedMojoIpcServerTest, ParallelIpcs) { +TEST_P(NamedMojoIpcServerTest, ParallelIpcs) { base::MockCallback<EchoStringHandler> mock_echo_string_handler; echo_string_handler_ = mock_echo_string_handler.Get(); std::string first_input; @@ -321,7 +332,7 @@ WaitForProcessExit(child_process_2); } -TEST_F(NamedMojoIpcServerTest, IpcServerRestarted_NewIpcsCanBeMade) { +TEST_P(NamedMojoIpcServerTest, IpcServerRestarted_NewIpcsCanBeMade) { base::Process child_process = LaunchClientProcess(); WaitForProcessExit(child_process); @@ -359,11 +370,19 @@ base::RunLoop().Run(); return 0; } - std::unique_ptr<mojo::IsolatedConnection> connection = - std::make_unique<mojo::IsolatedConnection>(); + std::unique_ptr<mojo::IsolatedConnection> connection; + mojo::ScopedMessagePipeHandle message_pipe; + if (cmd_line->HasSwitch(kClientProcessUseIsolatedConnectionSwitch)) { + connection = std::make_unique<mojo::IsolatedConnection>(); + message_pipe = connection->Connect(std::move(endpoint)); + } else { + auto invitation = mojo::IncomingInvitation::Accept(std::move(endpoint)); + message_pipe = invitation.ExtractMessagePipe(kTestMessagePipeId); + } + auto echo_remote = mojo::Remote<test::mojom::Echo>(mojo::PendingRemote<test::mojom::Echo>( - connection->Connect(std::move(endpoint)), /* version= */ 0)); + std::move(message_pipe), /* version= */ 0)); base::RunLoop wait_for_disconnect_run_loop; echo_remote.set_disconnect_handler( wait_for_disconnect_run_loop.QuitClosure()); @@ -385,5 +404,13 @@ return 0; } +INSTANTIATE_TEST_SUITE_P(/* test_prefix */, + NamedMojoIpcServerTest, + testing::Values(true, false), + [](const testing::TestParamInfo<bool>& info) { + return info.param ? "IsolatedConnection" + : "NonIsolatedConnection"; + }); + } // namespace } // namespace named_mojo_ipc_server
diff --git a/components/named_mojo_ipc_server/named_mojo_server_endpoint_connector.h b/components/named_mojo_ipc_server/named_mojo_server_endpoint_connector.h index 41187591..6bd60fb 100644 --- a/components/named_mojo_ipc_server/named_mojo_server_endpoint_connector.h +++ b/components/named_mojo_ipc_server/named_mojo_server_endpoint_connector.h
@@ -5,14 +5,11 @@ #ifndef COMPONENTS_NAMED_MOJO_IPC_SERVER_NAMED_MOJO_SERVER_ENDPOINT_CONNECTOR_H_ #define COMPONENTS_NAMED_MOJO_IPC_SERVER_NAMED_MOJO_SERVER_ENDPOINT_CONNECTOR_H_ -#include <memory> - #include "base/memory/scoped_refptr.h" #include "base/process/process_handle.h" #include "base/threading/sequence_bound.h" +#include "mojo/public/cpp/platform/platform_channel_endpoint.h" #include "mojo/public/cpp/platform/platform_channel_server_endpoint.h" -#include "mojo/public/cpp/system/isolated_connection.h" -#include "mojo/public/cpp/system/message_pipe.h" namespace base { class SequencedTaskRunner; @@ -38,8 +35,7 @@ // Called when the client has connected to the server endpoint. virtual void OnServerEndpointConnected( - std::unique_ptr<mojo::IsolatedConnection> connection, - mojo::ScopedMessagePipeHandle message_pipe, + mojo::PlatformChannelEndpoint endpoint, base::ProcessId peer_pid) = 0; // Called when error occurred during the connection process.
diff --git a/components/named_mojo_ipc_server/named_mojo_server_endpoint_connector_linux.cc b/components/named_mojo_ipc_server/named_mojo_server_endpoint_connector_linux.cc index 2934008..4f4a48f 100644 --- a/components/named_mojo_ipc_server/named_mojo_server_endpoint_connector_linux.cc +++ b/components/named_mojo_ipc_server/named_mojo_server_endpoint_connector_linux.cc
@@ -6,7 +6,7 @@ #include <sys/socket.h> -#include <memory> +#include <utility> #include "base/check.h" #include "base/files/file_descriptor_watcher_posix.h" @@ -77,11 +77,8 @@ delegate_.AsyncCall(&Delegate::OnServerEndpointConnectionFailed); return; } - auto connection = std::make_unique<mojo::IsolatedConnection>(); - auto message_pipe = connection->Connect(std::move(endpoint)); delegate_.AsyncCall(&Delegate::OnServerEndpointConnected) - .WithArgs(std::move(connection), std::move(message_pipe), - unix_peer_identity.pid); + .WithArgs(std::move(endpoint), unix_peer_identity.pid); } // static
diff --git a/components/named_mojo_ipc_server/named_mojo_server_endpoint_connector_win.cc b/components/named_mojo_ipc_server/named_mojo_server_endpoint_connector_win.cc index d8ff6f0..31d3d6d6 100644 --- a/components/named_mojo_ipc_server/named_mojo_server_endpoint_connector_win.cc +++ b/components/named_mojo_ipc_server/named_mojo_server_endpoint_connector_win.cc
@@ -7,7 +7,7 @@ #include <string.h> #include <windows.h> -#include <memory> +#include <utility> #include "base/bind.h" #include "base/check.h" @@ -23,7 +23,6 @@ #include "base/win/windows_types.h" #include "mojo/public/cpp/platform/platform_channel_endpoint.h" #include "mojo/public/cpp/platform/platform_handle.h" -#include "mojo/public/cpp/system/isolated_connection.h" namespace named_mojo_ipc_server { @@ -107,10 +106,8 @@ return; } ResetConnectionObjects(); - auto connection = std::make_unique<mojo::IsolatedConnection>(); - auto message_pipe = connection->Connect(std::move(endpoint)); delegate_.AsyncCall(&Delegate::OnServerEndpointConnected) - .WithArgs(std::move(connection), std::move(message_pipe), peer_pid); + .WithArgs(std::move(endpoint), peer_pid); } void NamedMojoServerEndpointConnectorWin::OnError() {
diff --git a/components/omnibox/browser/shortcuts_provider.cc b/components/omnibox/browser/shortcuts_provider.cc index 354d076..f89a85ae 100644 --- a/components/omnibox/browser/shortcuts_provider.cc +++ b/components/omnibox/browser/shortcuts_provider.cc
@@ -423,6 +423,8 @@ // or keyword mode was invoked explicitly and the keyword in the input // is also of the default search provider. (input.prefer_keyword() && keyword_matches); + match.search_terms_args = + std::make_unique<TemplateURLRef::SearchTermsArgs>(match.contents); } const bool match_has_explicit_keyword =
diff --git a/components/optimization_guide/content/browser/page_content_annotations_model_manager.cc b/components/optimization_guide/content/browser/page_content_annotations_model_manager.cc index e854ee87..0d7fc56 100644 --- a/components/optimization_guide/content/browser/page_content_annotations_model_manager.cc +++ b/components/optimization_guide/content/browser/page_content_annotations_model_manager.cc
@@ -13,14 +13,14 @@ #include "base/task/thread_pool.h" #include "components/optimization_guide/core/optimization_guide_features.h" #include "components/optimization_guide/core/optimization_guide_model_provider.h" -#include "components/optimization_guide/core/page_entities_model_executor.h" +#include "components/optimization_guide/core/page_entities_model_handler.h" #include "components/optimization_guide/optimization_guide_buildflags.h" #include "components/optimization_guide/proto/page_topics_model_metadata.pb.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #if BUILDFLAG(BUILD_WITH_INTERNAL_OPTIMIZATION_GUIDE) -#include "components/optimization_guide/core/page_entities_model_executor_impl.h" +#include "components/optimization_guide/core/page_entities_model_handler_impl.h" #endif namespace optimization_guide { @@ -69,11 +69,10 @@ scoped_refptr<base::SequencedTaskRunner> background_task_runner = base::ThreadPool::CreateSequencedTaskRunner(GetTaskTraits()); - page_entities_model_executor_ = - std::make_unique<PageEntitiesModelExecutorImpl>( - optimization_guide_model_provider, background_task_runner); + page_entities_model_handler_ = std::make_unique<PageEntitiesModelHandlerImpl>( + optimization_guide_model_provider, background_task_runner); - page_entities_model_executor_->AddOnModelUpdatedCallback( + page_entities_model_handler_->AddOnModelUpdatedCallback( base::BindOnce(std::move(callback), true)); #else std::move(callback).Run(false); @@ -81,10 +80,9 @@ } void PageContentAnnotationsModelManager:: - OverridePageEntitiesModelExecutorForTesting( - std::unique_ptr<PageEntitiesModelExecutor> - page_entities_model_executor) { - page_entities_model_executor_ = std::move(page_entities_model_executor); + OverridePageEntitiesModelHandlerForTesting( + std::unique_ptr<PageEntitiesModelHandler> page_entities_model_handler) { + page_entities_model_handler_ = std::move(page_entities_model_handler); } void PageContentAnnotationsModelManager::SetUpPageTopicsV2Model( @@ -92,7 +90,7 @@ if (!features::PageTopicsBatchAnnotationsEnabled()) return; - if (page_topics_model_executor_) + if (page_topics_model_handler_) return; optimization_guide::proto::Any any_metadata; @@ -100,7 +98,7 @@ proto::PageTopicsModelMetadata model_metadata; model_metadata.set_version(kTopicsModelVersion); model_metadata.SerializeToString(any_metadata.mutable_value()); - page_topics_model_executor_ = std::make_unique<PageTopicsModelExecutor>( + page_topics_model_handler_ = std::make_unique<PageTopicsModelHandler>( optimization_guide_model_provider, base::ThreadPool::CreateSequencedTaskRunner(GetTaskTraits()), any_metadata); @@ -123,9 +121,9 @@ void PageContentAnnotationsModelManager::GetMetadataForEntityId( const std::string& entity_id, EntityMetadataRetrievedCallback callback) { - if (page_entities_model_executor_) { - page_entities_model_executor_->GetMetadataForEntityId(entity_id, - std::move(callback)); + if (page_entities_model_handler_) { + page_entities_model_handler_->GetMetadataForEntityId(entity_id, + std::move(callback)); return; } @@ -139,8 +137,8 @@ // No-op if the executor is already setup. SetUpPageTopicsV2Model(optimization_guide_model_provider_); - if (page_topics_model_executor_) { - page_topics_model_executor_->AddOnModelUpdatedCallback( + if (page_topics_model_handler_) { + page_topics_model_handler_->AddOnModelUpdatedCallback( base::BindOnce(std::move(callback), true)); return; } @@ -158,8 +156,8 @@ } if (type == AnnotationType::kPageEntities) { - if (page_entities_model_executor_) { - page_entities_model_executor_->AddOnModelUpdatedCallback( + if (page_entities_model_handler_) { + page_entities_model_handler_->AddOnModelUpdatedCallback( base::BindOnce(std::move(callback), true)); } else { SetUpPageEntitiesModel(optimization_guide_model_provider_, @@ -174,15 +172,15 @@ absl::optional<ModelInfo> PageContentAnnotationsModelManager::GetModelInfoForType( AnnotationType type) const { - if (type == AnnotationType::kPageTopics && page_topics_model_executor_) { - return page_topics_model_executor_->GetModelInfo(); + if (type == AnnotationType::kPageTopics && page_topics_model_handler_) { + return page_topics_model_handler_->GetModelInfo(); } if (type == AnnotationType::kContentVisibility && page_visibility_model_handler_) { return page_visibility_model_handler_->GetModelInfo(); } - if (type == AnnotationType::kPageEntities && page_entities_model_executor_) { - return page_entities_model_executor_->GetModelInfo(); + if (type == AnnotationType::kPageEntities && page_entities_model_handler_) { + return page_entities_model_handler_->GetModelInfo(); } return absl::nullopt; } @@ -219,8 +217,8 @@ JobQueue::Pointer job_ptr = job_queue_.FirstMax(); if (job_ptr.is_null()) { // There are no more jobs to run, so unload all models. - if (page_topics_model_executor_) { - page_topics_model_executor_->UnloadModel(); + if (page_topics_model_handler_) { + page_topics_model_handler_->UnloadModel(); } if (page_visibility_model_handler_) { page_visibility_model_handler_->UnloadModel(); @@ -241,8 +239,8 @@ // Reset every other model from memory so that there aren't a bunch of models // all loaded at the same time. if (job->type() != AnnotationType::kPageTopics && - page_topics_model_executor_) { - page_topics_model_executor_->UnloadModel(); + page_topics_model_handler_) { + page_topics_model_handler_->UnloadModel(); } if (job->type() != AnnotationType::kContentVisibility && page_visibility_model_handler_) { @@ -250,15 +248,15 @@ } if (job->type() == AnnotationType::kPageTopics) { - if (!page_topics_model_executor_) { + if (!page_topics_model_handler_) { job->FillWithNullOutputs(); job->OnComplete(); job.reset(); std::move(on_job_complete_callback).Run(); return; } - page_topics_model_executor_->ExecuteJob(std::move(on_job_complete_callback), - std::move(job)); + page_topics_model_handler_->ExecuteJob(std::move(on_job_complete_callback), + std::move(job)); return; } @@ -276,14 +274,14 @@ } if (job->type() == AnnotationType::kPageEntities) { - if (!page_entities_model_executor_) { + if (!page_entities_model_handler_) { job->FillWithNullOutputs(); job->OnComplete(); job.reset(); std::move(on_job_complete_callback).Run(); return; } - page_entities_model_executor_->ExecuteJob( + page_entities_model_handler_->ExecuteJob( std::move(on_job_complete_callback), std::move(job)); return; }
diff --git a/components/optimization_guide/content/browser/page_content_annotations_model_manager.h b/components/optimization_guide/content/browser/page_content_annotations_model_manager.h index 0bd5f65..1c3780d 100644 --- a/components/optimization_guide/content/browser/page_content_annotations_model_manager.h +++ b/components/optimization_guide/content/browser/page_content_annotations_model_manager.h
@@ -11,7 +11,7 @@ #include "components/optimization_guide/core/model_info.h" #include "components/optimization_guide/core/page_content_annotation_job.h" #include "components/optimization_guide/core/page_content_annotations_common.h" -#include "components/optimization_guide/core/page_topics_model_executor.h" +#include "components/optimization_guide/core/page_topics_model_handler.h" #include "components/optimization_guide/core/page_visibility_model_handler.h" #include "net/base/priority_queue.h" #include "third_party/abseil-cpp/absl/types/optional.h" @@ -19,7 +19,7 @@ namespace optimization_guide { class OptimizationGuideModelProvider; -class PageEntitiesModelExecutor; +class PageEntitiesModelHandler; // Callback to inform the caller that the metadata for an entity ID has been // retrieved. @@ -102,9 +102,9 @@ void SetUpPageVisibilityModel( OptimizationGuideModelProvider* optimization_guide_model_provider); - // Overrides |page_entities_model_executor_| for testing purposes. - void OverridePageEntitiesModelExecutorForTesting( - std::unique_ptr<PageEntitiesModelExecutor> page_entities_model_executor); + // Overrides |page_entities_model_handler_| for testing purposes. + void OverridePageEntitiesModelHandlerForTesting( + std::unique_ptr<PageEntitiesModelHandler> page_entities_model_handler); // Runs the next job in |job_queue_| if there is any. void MaybeStartNextAnnotationJob(); @@ -112,18 +112,18 @@ // Called when a |job| finishes executing, just before it is deleted. void OnJobExecutionComplete(); - // The model executor responsible for executing the on demand page topics + // The model handler responsible for executing the on demand page topics // model. - std::unique_ptr<PageTopicsModelExecutor> page_topics_model_executor_; + std::unique_ptr<PageTopicsModelHandler> page_topics_model_handler_; // The model handler for the page visibility model. std::unique_ptr<PageVisibilityModelHandler> page_visibility_model_handler_; - // The model executor responsible for executing the page entities model. + // The model handler responsible for executing the page entities model. // // Can be nullptr if the page entities model will not be running for the // session. - std::unique_ptr<PageEntitiesModelExecutor> page_entities_model_executor_; + std::unique_ptr<PageEntitiesModelHandler> page_entities_model_handler_; // The queue of all jobs to be executed. This data structure supports FIFO // ordering for elements of the same priority.
diff --git a/components/optimization_guide/content/browser/page_content_annotations_model_manager_unittest.cc b/components/optimization_guide/content/browser/page_content_annotations_model_manager_unittest.cc index 1b00336..88a7a922 100644 --- a/components/optimization_guide/content/browser/page_content_annotations_model_manager_unittest.cc +++ b/components/optimization_guide/content/browser/page_content_annotations_model_manager_unittest.cc
@@ -14,7 +14,7 @@ #include "build/build_config.h" #include "components/optimization_guide/core/execution_status.h" #include "components/optimization_guide/core/optimization_guide_features.h" -#include "components/optimization_guide/core/page_entities_model_executor.h" +#include "components/optimization_guide/core/page_entities_model_handler.h" #include "components/optimization_guide/core/test_model_info_builder.h" #include "components/optimization_guide/core/test_optimization_guide_model_provider.h" #include "components/optimization_guide/proto/page_topics_model_metadata.pb.h" @@ -52,14 +52,14 @@ registered_model_metadata_; }; -class FakePageEntitiesModelExecutor : public PageEntitiesModelExecutor { +class FakePageEntitiesModelHandler : public PageEntitiesModelHandler { public: - explicit FakePageEntitiesModelExecutor( + explicit FakePageEntitiesModelHandler( const base::flat_map<std::string, std::vector<ScoredEntityMetadata>>& entries, const base::flat_map<std::string, EntityMetadata>& entity_metadata) : entries_(entries), entity_metadata_(entity_metadata) {} - ~FakePageEntitiesModelExecutor() override = default; + ~FakePageEntitiesModelHandler() override = default; void ExecuteModelWithInput( const std::string& text, @@ -135,7 +135,7 @@ AnnotationType::kPageTopics, base::DoNothing()); // If the feature flag is disabled, the executor won't have been created so // skip everything else. - if (!model_manager()->page_topics_model_executor_) + if (!model_manager()->page_topics_model_handler_) return; proto::Any any_metadata; @@ -156,7 +156,7 @@ .SetModelFilePath(model_file_path) .SetModelMetadata(any_metadata) .Build(); - model_manager()->page_topics_model_executor_->OnModelUpdated( + model_manager()->page_topics_model_handler_->OnModelUpdated( proto::OPTIMIZATION_TARGET_PAGE_TOPICS_V2, *model_info); RunUntilIdle(); } @@ -187,13 +187,13 @@ RunUntilIdle(); } - void SetPageEntitiesModelExecutor( + void SetPageEntitiesModelHandler( const base::flat_map<std::string, std::vector<ScoredEntityMetadata>>& entries, const base::flat_map<std::string, EntityMetadata>& entity_metadata) { - model_manager()->OverridePageEntitiesModelExecutorForTesting( - std::make_unique<FakePageEntitiesModelExecutor>(entries, - entity_metadata)); + model_manager()->OverridePageEntitiesModelHandlerForTesting( + std::make_unique<FakePageEntitiesModelHandler>(entries, + entity_metadata)); } absl::optional<EntityMetadata> GetMetadataForEntityId( @@ -346,7 +346,7 @@ std::vector<ScoredEntityMetadata> input2_entities = { ScoredEntityMetadata(0.7, EntityMetadata("fish", "fish", {})), }; - SetPageEntitiesModelExecutor( + SetPageEntitiesModelHandler( { {"input1", input1_entities}, {"input2", input2_entities}, @@ -660,7 +660,7 @@ TEST_F(PageContentAnnotationsModelManagerTest, NotifyWhenModelAvailable_EntitiesOnly) { - SetPageEntitiesModelExecutor(/*entries=*/{}, /*entity_metadata=*/{}); + SetPageEntitiesModelHandler(/*entries=*/{}, /*entity_metadata=*/{}); base::RunLoop run_loop; bool success = false; @@ -729,9 +729,9 @@ entity_metadata.human_readable_categories = { {"category1", 0.5}, }; - SetPageEntitiesModelExecutor(/*entries=*/{}, { - {"entity1", entity_metadata}, - }); + SetPageEntitiesModelHandler(/*entries=*/{}, { + {"entity1", entity_metadata}, + }); EXPECT_TRUE(GetMetadataForEntityId("entity1").has_value()); }
diff --git a/components/optimization_guide/core/BUILD.gn b/components/optimization_guide/core/BUILD.gn index 4148160..64603840 100644 --- a/components/optimization_guide/core/BUILD.gn +++ b/components/optimization_guide/core/BUILD.gn
@@ -206,10 +206,10 @@ "model_validator.h", "page_content_annotation_job_executor.cc", "page_content_annotation_job_executor.h", - "page_entities_model_executor.cc", - "page_entities_model_executor.h", - "page_topics_model_executor.cc", - "page_topics_model_executor.h", + "page_entities_model_handler.cc", + "page_entities_model_handler.h", + "page_topics_model_handler.cc", + "page_topics_model_handler.h", "page_visibility_model_handler.cc", "page_visibility_model_handler.h", ] @@ -217,8 +217,8 @@ sources += [ "entity_annotator_native_library.cc", "entity_annotator_native_library.h", - "page_entities_model_executor_impl.cc", - "page_entities_model_executor_impl.h", + "page_entities_model_handler_impl.cc", + "page_entities_model_handler_impl.h", ] } } @@ -402,14 +402,14 @@ "bert_model_executor_unittest.cc", "model_validator_unittest.cc", "page_content_annotation_job_executor_unittest.cc", - "page_topics_model_executor_unittest.cc", + "page_topics_model_handler_unittest.cc", "page_visibility_model_handler_unittest.cc", "tflite_model_executor_unittest.cc", ] if (build_with_internal_optimization_guide) { sources += [ "entity_annotator_native_library_unittest.cc", - "page_entities_model_executor_impl_unittest.cc", + "page_entities_model_handler_impl_unittest.cc", ] } }
diff --git a/components/optimization_guide/core/entity_annotator_native_library.cc b/components/optimization_guide/core/entity_annotator_native_library.cc index b4e72ab..763d3c62 100644 --- a/components/optimization_guide/core/entity_annotator_native_library.cc +++ b/components/optimization_guide/core/entity_annotator_native_library.cc
@@ -59,7 +59,7 @@ ~ScopedEntityAnnotatorCreationStatusRecorder() { DCHECK_NE(status_, EntityAnnotatorCreationStatus::kUnknown); base::UmaHistogramEnumeration( - "OptimizationGuide.PageEntitiesModelExecutor.CreationStatus", status_); + "OptimizationGuide.PageEntitiesModelHandler.CreationStatus", status_); } void set_status(EntityAnnotatorCreationStatus status) { status_ = status; }
diff --git a/components/optimization_guide/core/entity_annotator_native_library.h b/components/optimization_guide/core/entity_annotator_native_library.h index 69c1b04d..db46c58d 100644 --- a/components/optimization_guide/core/entity_annotator_native_library.h +++ b/components/optimization_guide/core/entity_annotator_native_library.h
@@ -17,7 +17,7 @@ // Enumerates the statuses possible when creating an entity annotator. // // Keep this in sync with -// OptimizationGuidePageEntitiesModelExecutorCreationStatus in enums.xml. +// OptimizationGuideEntityAnnotatorCreationStatus in enums.xml. enum class EntityAnnotatorCreationStatus { kUnknown = 0, // The entity annotator was created successfully.
diff --git a/components/optimization_guide/core/hints_manager.cc b/components/optimization_guide/core/hints_manager.cc index a2c2bb4..470fd48 100644 --- a/components/optimization_guide/core/hints_manager.cc +++ b/components/optimization_guide/core/hints_manager.cc
@@ -1125,18 +1125,19 @@ if (IsHintBeingFetchedForNavigation(url)) { CanApplyOptimizationAsync(url, optimization_type, std::move(callback)); } else { - OptimizationMetadata meta; + OptimizationMetadata metadata; + OptimizationTypeDecision type_decision = + CanApplyOptimization(url, optimization_type, &metadata); OptimizationGuideDecision decision = - GetOptimizationGuideDecisionFromOptimizationTypeDecision( - CanApplyOptimization(url, optimization_type, &meta)); + GetOptimizationGuideDecisionFromOptimizationTypeDecision(type_decision); base::UmaHistogramEnumeration( "OptimizationGuide.ApplyDecision." + optimization_guide::GetStringNameForOptimizationType( optimization_type), - decision); + type_decision); - std::move(callback).Run(decision, meta); + std::move(callback).Run(decision, metadata); } }
diff --git a/components/optimization_guide/core/page_entities_model_executor.cc b/components/optimization_guide/core/page_entities_model_handler.cc similarity index 93% rename from components/optimization_guide/core/page_entities_model_executor.cc rename to components/optimization_guide/core/page_entities_model_handler.cc index a6ca7c6..1cf8eb42 100644 --- a/components/optimization_guide/core/page_entities_model_executor.cc +++ b/components/optimization_guide/core/page_entities_model_handler.cc
@@ -2,14 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "components/optimization_guide/core/page_entities_model_executor.h" +#include "components/optimization_guide/core/page_entities_model_handler.h" #include "base/bind.h" #include "base/callback.h" namespace optimization_guide { -void PageEntitiesModelExecutor::ExecuteOnSingleInput( +void PageEntitiesModelHandler::ExecuteOnSingleInput( AnnotationType annotation_type, const std::string& input, base::OnceCallback<void(const BatchAnnotationResult&)> callback) {
diff --git a/components/optimization_guide/core/page_entities_model_executor.h b/components/optimization_guide/core/page_entities_model_handler.h similarity index 84% rename from components/optimization_guide/core/page_entities_model_executor.h rename to components/optimization_guide/core/page_entities_model_handler.h index 351bd82f..6c435f3 100644 --- a/components/optimization_guide/core/page_entities_model_executor.h +++ b/components/optimization_guide/core/page_entities_model_handler.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef COMPONENTS_OPTIMIZATION_GUIDE_CORE_PAGE_ENTITIES_MODEL_EXECUTOR_H_ -#define COMPONENTS_OPTIMIZATION_GUIDE_CORE_PAGE_ENTITIES_MODEL_EXECUTOR_H_ +#ifndef COMPONENTS_OPTIMIZATION_GUIDE_CORE_PAGE_ENTITIES_MODEL_HANDLER_H_ +#define COMPONENTS_OPTIMIZATION_GUIDE_CORE_PAGE_ENTITIES_MODEL_HANDLER_H_ #include <string> #include <vector> @@ -17,11 +17,11 @@ namespace optimization_guide { -// The PageEntitiesModelExecutor is responsible for executing the PAGE_ENTITIES +// The PageEntitiesModelHandler is responsible for executing the PAGE_ENTITIES // model. -class PageEntitiesModelExecutor : public PageContentAnnotationJobExecutor { +class PageEntitiesModelHandler : public PageContentAnnotationJobExecutor { public: - virtual ~PageEntitiesModelExecutor() = default; + virtual ~PageEntitiesModelHandler() = default; using PageEntitiesMetadataModelExecutedCallback = base::OnceCallback<void( const absl::optional<std::vector<ScoredEntityMetadata>>&)>; @@ -58,4 +58,4 @@ } // namespace optimization_guide -#endif // COMPONENTS_OPTIMIZATION_GUIDE_CORE_PAGE_ENTITIES_MODEL_EXECUTOR_H_ +#endif // COMPONENTS_OPTIMIZATION_GUIDE_CORE_PAGE_ENTITIES_MODEL_HANDLER_H_
diff --git a/components/optimization_guide/core/page_entities_model_executor_impl.cc b/components/optimization_guide/core/page_entities_model_handler_impl.cc similarity index 86% rename from components/optimization_guide/core/page_entities_model_executor_impl.cc rename to components/optimization_guide/core/page_entities_model_handler_impl.cc index 0b9065b5..059d9da 100644 --- a/components/optimization_guide/core/page_entities_model_executor_impl.cc +++ b/components/optimization_guide/core/page_entities_model_handler_impl.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "components/optimization_guide/core/page_entities_model_executor_impl.h" +#include "components/optimization_guide/core/page_entities_model_handler_impl.h" #include <algorithm> @@ -28,14 +28,14 @@ // know how much the model is expected to output. constexpr size_t kMaxPageEntities = 5; -PageEntitiesModelExecutorConfig& GetPageEntitiesModelExecutorConfigInternal() { - static base::NoDestructor<PageEntitiesModelExecutorConfig> s_config; +PageEntitiesModelHandlerConfig& GetPageEntitiesModelHandlerConfigInternal() { + static base::NoDestructor<PageEntitiesModelHandlerConfig> s_config; return *s_config; } } // namespace -PageEntitiesModelExecutorConfig::PageEntitiesModelExecutorConfig() { +PageEntitiesModelHandlerConfig::PageEntitiesModelHandlerConfig() { // Override any parameters that may be provided by Finch. should_reset_entity_annotator_on_shutdown = base::FeatureList::IsEnabled(features::kPageEntitiesModelResetOnShutdown); @@ -44,17 +44,17 @@ !base::FeatureList::IsEnabled(features::kPageEntitiesModelBypassFilters); } -PageEntitiesModelExecutorConfig::PageEntitiesModelExecutorConfig( - const PageEntitiesModelExecutorConfig& other) = default; -PageEntitiesModelExecutorConfig::~PageEntitiesModelExecutorConfig() = default; +PageEntitiesModelHandlerConfig::PageEntitiesModelHandlerConfig( + const PageEntitiesModelHandlerConfig& other) = default; +PageEntitiesModelHandlerConfig::~PageEntitiesModelHandlerConfig() = default; -void SetPageEntitiesModelExecutorConfigForTesting( - const PageEntitiesModelExecutorConfig& config) { - GetPageEntitiesModelExecutorConfigInternal() = config; +void SetPageEntitiesModelHandlerConfigForTesting( + const PageEntitiesModelHandlerConfig& config) { + GetPageEntitiesModelHandlerConfigInternal() = config; } -const PageEntitiesModelExecutorConfig& GetPageEntitiesModelExecutorConfig() { - return GetPageEntitiesModelExecutorConfigInternal(); +const PageEntitiesModelHandlerConfig& GetPageEntitiesModelHandlerConfig() { + return GetPageEntitiesModelHandlerConfigInternal(); } EntityAnnotatorHolder::EntityAnnotatorHolder( @@ -131,7 +131,7 @@ entity_annotator_ = entity_annotator_native_library_->CreateEntityAnnotator(model_info); base::UmaHistogramBoolean( - "OptimizationGuide.PageEntitiesModelExecutor.CreatedSuccessfully", + "OptimizationGuide.PageEntitiesModelHandler.CreatedSuccessfully", entity_annotator_ != nullptr); } @@ -178,7 +178,7 @@ void EntityAnnotatorHolder::GetMetadataForEntityIdOnBackgroundThread( const std::string& entity_id, - PageEntitiesModelExecutor::PageEntitiesModelEntityMetadataRetrievedCallback + PageEntitiesModelHandler::PageEntitiesModelEntityMetadataRetrievedCallback callback) { DCHECK(background_task_runner_->RunsTasksInCurrentSequence()); @@ -199,14 +199,14 @@ return background_weak_ptr_factory_.GetWeakPtr(); } -PageEntitiesModelExecutorImpl::PageEntitiesModelExecutorImpl( +PageEntitiesModelHandlerImpl::PageEntitiesModelHandlerImpl( OptimizationGuideModelProvider* optimization_guide_model_provider, scoped_refptr<base::SequencedTaskRunner> background_task_runner) : background_task_runner_(background_task_runner), entity_annotator_holder_(std::make_unique<EntityAnnotatorHolder>( background_task_runner_, base::SequencedTaskRunner::GetCurrentDefault(), - GetPageEntitiesModelExecutorConfig() + GetPageEntitiesModelHandlerConfig() .should_reset_entity_annotator_on_shutdown)) { background_task_runner_->PostTask( FROM_HERE, @@ -214,14 +214,14 @@ &EntityAnnotatorHolder:: InitializeEntityAnnotatorNativeLibraryOnBackgroundThread, entity_annotator_holder_->GetBackgroundWeakPtr(), - GetPageEntitiesModelExecutorConfig().should_provide_filter_path, - base::BindOnce(&PageEntitiesModelExecutorImpl:: + GetPageEntitiesModelHandlerConfig().should_provide_filter_path, + base::BindOnce(&PageEntitiesModelHandlerImpl:: OnEntityAnnotatorLibraryInitialized, weak_ptr_factory_.GetWeakPtr(), optimization_guide_model_provider))); } -void PageEntitiesModelExecutorImpl::OnEntityAnnotatorLibraryInitialized( +void PageEntitiesModelHandlerImpl::OnEntityAnnotatorLibraryInitialized( OptimizationGuideModelProvider* optimization_guide_model_provider, int32_t max_model_format_feature_flag) { if (max_model_format_feature_flag <= 0) { @@ -239,14 +239,14 @@ any_metadata, this); } -PageEntitiesModelExecutorImpl::~PageEntitiesModelExecutorImpl() { +PageEntitiesModelHandlerImpl::~PageEntitiesModelHandlerImpl() { // |entity_annotator_holder_|'s WeakPtrs are used on the background thread, // so that is also where the class must be destroyed. background_task_runner_->DeleteSoon(FROM_HERE, std::move(entity_annotator_holder_)); } -void PageEntitiesModelExecutorImpl::AddOnModelUpdatedCallback( +void PageEntitiesModelHandlerImpl::AddOnModelUpdatedCallback( base::OnceClosure callback) { if (model_info_) { std::move(callback).Run(); @@ -257,7 +257,7 @@ on_model_updated_callbacks_.AddUnsafe(std::move(callback)); } -void PageEntitiesModelExecutorImpl::OnModelUpdated( +void PageEntitiesModelHandlerImpl::OnModelUpdated( proto::OptimizationTarget optimization_target, const ModelInfo& model_info) { if (optimization_target != proto::OPTIMIZATION_TARGET_PAGE_ENTITIES) @@ -277,11 +277,11 @@ on_model_updated_callbacks_.Notify(); } -absl::optional<ModelInfo> PageEntitiesModelExecutorImpl::GetModelInfo() const { +absl::optional<ModelInfo> PageEntitiesModelHandlerImpl::GetModelInfo() const { return model_info_; } -void PageEntitiesModelExecutorImpl::ExecuteModelWithInput( +void PageEntitiesModelHandlerImpl::ExecuteModelWithInput( const std::string& text, PageEntitiesMetadataModelExecutedCallback callback) { if (text.empty()) { @@ -297,7 +297,7 @@ std::move(callback))); } -void PageEntitiesModelExecutorImpl::GetMetadataForEntityId( +void PageEntitiesModelHandlerImpl::GetMetadataForEntityId( const std::string& entity_id, PageEntitiesModelEntityMetadataRetrievedCallback callback) { background_task_runner_->PostTask(
diff --git a/components/optimization_guide/core/page_entities_model_executor_impl.h b/components/optimization_guide/core/page_entities_model_handler_impl.h similarity index 79% rename from components/optimization_guide/core/page_entities_model_executor_impl.h rename to components/optimization_guide/core/page_entities_model_handler_impl.h index 6fe96337..351e569 100644 --- a/components/optimization_guide/core/page_entities_model_executor_impl.h +++ b/components/optimization_guide/core/page_entities_model_handler_impl.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef COMPONENTS_OPTIMIZATION_GUIDE_CORE_PAGE_ENTITIES_MODEL_EXECUTOR_IMPL_H_ -#define COMPONENTS_OPTIMIZATION_GUIDE_CORE_PAGE_ENTITIES_MODEL_EXECUTOR_IMPL_H_ +#ifndef COMPONENTS_OPTIMIZATION_GUIDE_CORE_PAGE_ENTITIES_MODEL_HANDLER_IMPL_H_ +#define COMPONENTS_OPTIMIZATION_GUIDE_CORE_PAGE_ENTITIES_MODEL_HANDLER_IMPL_H_ #include "base/callback_list.h" #include "base/memory/raw_ptr.h" @@ -12,7 +12,7 @@ #include "base/task/thread_pool.h" #include "components/optimization_guide/core/entity_metadata.h" #include "components/optimization_guide/core/optimization_target_model_observer.h" -#include "components/optimization_guide/core/page_entities_model_executor.h" +#include "components/optimization_guide/core/page_entities_model_handler.h" namespace optimization_guide { @@ -20,8 +20,8 @@ class OptimizationGuideModelProvider; // A configuration that manages the necessary feature params required by the -// PageEntitiesModelExecutor. -struct PageEntitiesModelExecutorConfig { +// PageEntitiesModelHandler. +struct PageEntitiesModelHandlerConfig { // Whether the page entities model should be reset on shutdown. bool should_reset_entity_annotator_on_shutdown = false; @@ -29,17 +29,17 @@ // model. bool should_provide_filter_path = true; - PageEntitiesModelExecutorConfig(); - PageEntitiesModelExecutorConfig(const PageEntitiesModelExecutorConfig& other); - ~PageEntitiesModelExecutorConfig(); + PageEntitiesModelHandlerConfig(); + PageEntitiesModelHandlerConfig(const PageEntitiesModelHandlerConfig& other); + ~PageEntitiesModelHandlerConfig(); }; // Gets the current configuration. -const PageEntitiesModelExecutorConfig& GetPageEntitiesModelExecutorConfig(); +const PageEntitiesModelHandlerConfig& GetPageEntitiesModelHandlerConfig(); -// Overrides the config returned by |GetPageEntitiesModelExecutorConfig()|. -void SetPageEntitiesModelExecutorConfigForTesting( - const PageEntitiesModelExecutorConfig& config); +// Overrides the config returned by |GetPageEntitiesModelHandlerConfig()|. +void SetPageEntitiesModelHandlerConfigForTesting( + const PageEntitiesModelHandlerConfig& config); // An object used to hold an entity annotator on a background thread. class EntityAnnotatorHolder { @@ -75,8 +75,8 @@ // Should be invoked on |background_task_runner_|. void GetMetadataForEntityIdOnBackgroundThread( const std::string& entity_id, - PageEntitiesModelExecutor:: - PageEntitiesModelEntityMetadataRetrievedCallback callback); + PageEntitiesModelHandler::PageEntitiesModelEntityMetadataRetrievedCallback + callback); // Gets the weak ptr to |this| on the background thread. base::WeakPtr<EntityAnnotatorHolder> GetBackgroundWeakPtr(); @@ -99,18 +99,18 @@ }; // Manages the loading and execution of the page entities model. -class PageEntitiesModelExecutorImpl : public OptimizationTargetModelObserver, - public PageEntitiesModelExecutor { +class PageEntitiesModelHandlerImpl : public OptimizationTargetModelObserver, + public PageEntitiesModelHandler { public: - PageEntitiesModelExecutorImpl( + PageEntitiesModelHandlerImpl( OptimizationGuideModelProvider* model_provider, scoped_refptr<base::SequencedTaskRunner> background_task_runner); - ~PageEntitiesModelExecutorImpl() override; - PageEntitiesModelExecutorImpl(const PageEntitiesModelExecutorImpl&) = delete; - PageEntitiesModelExecutorImpl& operator=( - const PageEntitiesModelExecutorImpl&) = delete; + ~PageEntitiesModelHandlerImpl() override; + PageEntitiesModelHandlerImpl(const PageEntitiesModelHandlerImpl&) = delete; + PageEntitiesModelHandlerImpl& operator=(const PageEntitiesModelHandlerImpl&) = + delete; - // PageEntitiesModelExecutor: + // PageEntitiesModelHandler: void GetMetadataForEntityId( const std::string& entity_id, PageEntitiesModelEntityMetadataRetrievedCallback callback) override; @@ -143,9 +143,9 @@ // model file is available, then is notified when |OnModelUpdated| is called. base::OnceClosureList on_model_updated_callbacks_; - base::WeakPtrFactory<PageEntitiesModelExecutorImpl> weak_ptr_factory_{this}; + base::WeakPtrFactory<PageEntitiesModelHandlerImpl> weak_ptr_factory_{this}; }; } // namespace optimization_guide -#endif // COMPONENTS_OPTIMIZATION_GUIDE_CORE_PAGE_ENTITIES_MODEL_EXECUTOR_IMPL_H_ +#endif // COMPONENTS_OPTIMIZATION_GUIDE_CORE_PAGE_ENTITIES_MODEL_HANDLER_IMPL_H_
diff --git a/components/optimization_guide/core/page_entities_model_executor_impl_unittest.cc b/components/optimization_guide/core/page_entities_model_handler_impl_unittest.cc similarity index 87% rename from components/optimization_guide/core/page_entities_model_executor_impl_unittest.cc rename to components/optimization_guide/core/page_entities_model_handler_impl_unittest.cc index d575196f..914b1c43 100644 --- a/components/optimization_guide/core/page_entities_model_executor_impl_unittest.cc +++ b/components/optimization_guide/core/page_entities_model_handler_impl_unittest.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "components/optimization_guide/core/page_entities_model_executor_impl.h" +#include "components/optimization_guide/core/page_entities_model_handler_impl.h" #include "base/observer_list.h" #include "base/path_service.h" @@ -62,24 +62,24 @@ base::ObserverList<OptimizationTargetModelObserver> registered_observers_; }; -class PageEntitiesModelExecutorImplTest : public testing::Test { +class PageEntitiesModelHandlerImplTest : public testing::Test { public: - PageEntitiesModelExecutorImplTest() { - PageEntitiesModelExecutorConfig config; + PageEntitiesModelHandlerImplTest() { + PageEntitiesModelHandlerConfig config; // The false variation is tested in a src-internal test. config.should_provide_filter_path = true; - SetPageEntitiesModelExecutorConfigForTesting(config); + SetPageEntitiesModelHandlerConfigForTesting(config); } void SetUp() override { model_observer_tracker_ = std::make_unique<ModelObserverTracker>(); - model_executor_ = std::make_unique<PageEntitiesModelExecutorImpl>( + model_executor_ = std::make_unique<PageEntitiesModelHandlerImpl>( model_observer_tracker_.get(), base::ThreadPool::CreateSequencedTaskRunner( {base::MayBlock(), base::TaskPriority::BEST_EFFORT})); - // Wait for PageEntitiesModelExecutor to set everything up. + // Wait for PageEntitiesModelHandler to set everything up. task_environment_.RunUntilIdle(); } @@ -87,7 +87,7 @@ model_executor_.reset(); model_observer_tracker_.reset(); - // Wait for PageEntitiesModelExecutor to clean everything up. + // Wait for PageEntitiesModelHandler to clean everything up. task_environment_.RunUntilIdle(); } @@ -132,7 +132,7 @@ return entity_metadata; } - PageEntitiesModelExecutor* model_executor() { return model_executor_.get(); } + PageEntitiesModelHandler* model_executor() { return model_executor_.get(); } ModelObserverTracker* model_observer_tracker() const { return model_observer_tracker_.get(); @@ -155,10 +155,10 @@ private: base::test::TaskEnvironment task_environment_; std::unique_ptr<ModelObserverTracker> model_observer_tracker_; - std::unique_ptr<PageEntitiesModelExecutorImpl> model_executor_; + std::unique_ptr<PageEntitiesModelHandlerImpl> model_executor_; }; -TEST_F(PageEntitiesModelExecutorImplTest, CreateNoMetadata) { +TEST_F(PageEntitiesModelHandlerImplTest, CreateNoMetadata) { base::HistogramTester histogram_tester; std::unique_ptr<ModelInfo> model_info = TestModelInfoBuilder().Build(); @@ -170,14 +170,14 @@ EXPECT_EQ(ExecuteModel("Taylor Swift singer"), absl::nullopt); histogram_tester.ExpectUniqueSample( - "OptimizationGuide.PageEntitiesModelExecutor.CreatedSuccessfully", false, + "OptimizationGuide.PageEntitiesModelHandler.CreatedSuccessfully", false, 1); histogram_tester.ExpectUniqueSample( - "OptimizationGuide.PageEntitiesModelExecutor.CreationStatus", + "OptimizationGuide.PageEntitiesModelHandler.CreationStatus", EntityAnnotatorCreationStatus::kMissingModelMetadata, 1); } -TEST_F(PageEntitiesModelExecutorImplTest, CreateMetadataWrongType) { +TEST_F(PageEntitiesModelHandlerImplTest, CreateMetadataWrongType) { base::HistogramTester histogram_tester; proto::Any any; @@ -199,14 +199,14 @@ EXPECT_EQ(ExecuteModel("Taylor Swift singer"), absl::nullopt); histogram_tester.ExpectUniqueSample( - "OptimizationGuide.PageEntitiesModelExecutor.CreatedSuccessfully", false, + "OptimizationGuide.PageEntitiesModelHandler.CreatedSuccessfully", false, 1); histogram_tester.ExpectUniqueSample( - "OptimizationGuide.PageEntitiesModelExecutor.CreationStatus", + "OptimizationGuide.PageEntitiesModelHandler.CreationStatus", EntityAnnotatorCreationStatus::kMissingEntitiesModelMetadata, 1); } -TEST_F(PageEntitiesModelExecutorImplTest, CreateNoSlices) { +TEST_F(PageEntitiesModelHandlerImplTest, CreateNoSlices) { base::HistogramTester histogram_tester; proto::Any any; @@ -228,16 +228,16 @@ EXPECT_EQ(ExecuteModel("Taylor Swift singer"), absl::nullopt); histogram_tester.ExpectUniqueSample( - "OptimizationGuide.PageEntitiesModelExecutor.CreatedSuccessfully", false, + "OptimizationGuide.PageEntitiesModelHandler.CreatedSuccessfully", false, 1); histogram_tester.ExpectUniqueSample( - "OptimizationGuide.PageEntitiesModelExecutor.CreationStatus", + "OptimizationGuide.PageEntitiesModelHandler.CreationStatus", EntityAnnotatorCreationStatus:: kMissingEntitiesModelMetadataSliceSpecification, 1); } -TEST_F(PageEntitiesModelExecutorImplTest, ModelInfoUpdated) { +TEST_F(PageEntitiesModelHandlerImplTest, ModelInfoUpdated) { bool callback_run = false; model_executor()->AddOnModelUpdatedCallback( base::BindOnce([](bool* flag) { *flag = true; }, &callback_run)); @@ -266,7 +266,7 @@ EXPECT_TRUE(immediate_callback_run); } -TEST_F(PageEntitiesModelExecutorImplTest, CreateMissingFiles) { +TEST_F(PageEntitiesModelHandlerImplTest, CreateMissingFiles) { proto::Any any; proto::PageEntitiesModelMetadata metadata; metadata.add_slice("global"); @@ -319,24 +319,24 @@ EXPECT_EQ(ExecuteModel("Taylor Swift singer"), absl::nullopt); histogram_tester.ExpectUniqueSample( - "OptimizationGuide.PageEntitiesModelExecutor.CreatedSuccessfully", - false, 1); + "OptimizationGuide.PageEntitiesModelHandler.CreatedSuccessfully", false, + 1); histogram_tester.ExpectUniqueSample( - "OptimizationGuide.PageEntitiesModelExecutor.CreationStatus", + "OptimizationGuide.PageEntitiesModelHandler.CreationStatus", missing_file_and_status.second, 1); } } -TEST_F(PageEntitiesModelExecutorImplTest, GetMetadataForEntityIdNoModel) { +TEST_F(PageEntitiesModelHandlerImplTest, GetMetadataForEntityIdNoModel) { EXPECT_EQ(GetMetadataForEntityId("/m/0dl567"), absl::nullopt); } -TEST_F(PageEntitiesModelExecutorImplTest, ExecuteModelNoModel) { +TEST_F(PageEntitiesModelHandlerImplTest, ExecuteModelNoModel) { EXPECT_EQ(ExecuteModel("Taylor Swift singer"), absl::nullopt); } -TEST_F(PageEntitiesModelExecutorImplTest, +TEST_F(PageEntitiesModelHandlerImplTest, SetsUpModelCorrectlyBasedOnFeatureParams) { absl::optional<proto::Any> registered_model_metadata; EXPECT_TRUE(model_observer_tracker()->DidRegisterForTarget(
diff --git a/components/optimization_guide/core/page_topics_model_executor.cc b/components/optimization_guide/core/page_topics_model_handler.cc similarity index 93% rename from components/optimization_guide/core/page_topics_model_executor.cc rename to components/optimization_guide/core/page_topics_model_handler.cc index bc522092..237547b 100644 --- a/components/optimization_guide/core/page_topics_model_executor.cc +++ b/components/optimization_guide/core/page_topics_model_handler.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "components/optimization_guide/core/page_topics_model_executor.h" +#include "components/optimization_guide/core/page_topics_model_handler.h" #include <ctype.h> @@ -139,7 +139,7 @@ } // namespace -PageTopicsModelExecutor::PageTopicsModelExecutor( +PageTopicsModelHandler::PageTopicsModelHandler( OptimizationGuideModelProvider* model_provider, scoped_refptr<base::SequencedTaskRunner> background_task_runner, const absl::optional<proto::Any>& model_metadata) @@ -150,9 +150,9 @@ background_task_runner_(background_task_runner) { SetShouldUnloadModelOnComplete(false); } -PageTopicsModelExecutor::~PageTopicsModelExecutor() = default; +PageTopicsModelHandler::~PageTopicsModelHandler() = default; -void PageTopicsModelExecutor::ExecuteJob( +void PageTopicsModelHandler::ExecuteJob( base::OnceClosure on_job_complete_callback, std::unique_ptr<PageContentAnnotationJob> job) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); @@ -163,7 +163,7 @@ background_task_runner_->PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce(&LoadOverrideListFromFile, *override_list_file_path_), - base::BindOnce(&PageTopicsModelExecutor::OnOverrideListLoadAttemptDone, + base::BindOnce(&PageTopicsModelHandler::OnOverrideListLoadAttemptDone, weak_ptr_factory_.GetWeakPtr(), std::move(on_job_complete_callback), std::move(job))); return; @@ -173,7 +173,7 @@ std::move(on_job_complete_callback), std::move(job)); } -std::string PageTopicsModelExecutor::PreprocessHost( +std::string PageTopicsModelHandler::PreprocessHost( const std::string& host) const { std::string output = base::ToLowerASCII(host); @@ -199,7 +199,7 @@ return output; } -void PageTopicsModelExecutor::ExecuteOnSingleInput( +void PageTopicsModelHandler::ExecuteOnSingleInput( AnnotationType annotation_type, const std::string& raw_input, base::OnceCallback<void(const BatchAnnotationResult&)> callback) { @@ -227,14 +227,14 @@ } ExecuteModelWithInput( - base::BindOnce(&PageTopicsModelExecutor:: - PostprocessCategoriesToBatchAnnotationResult, - weak_ptr_factory_.GetWeakPtr(), std::move(callback), - annotation_type, raw_input), + base::BindOnce( + &PageTopicsModelHandler::PostprocessCategoriesToBatchAnnotationResult, + weak_ptr_factory_.GetWeakPtr(), std::move(callback), annotation_type, + raw_input), processed_input); } -void PageTopicsModelExecutor::OnOverrideListLoadAttemptDone( +void PageTopicsModelHandler::OnOverrideListLoadAttemptDone( base::OnceClosure on_job_complete_callback, std::unique_ptr<PageContentAnnotationJob> job, absl::optional< @@ -253,7 +253,7 @@ std::move(on_job_complete_callback), std::move(job)); } -void PageTopicsModelExecutor::PostprocessCategoriesToBatchAnnotationResult( +void PageTopicsModelHandler::PostprocessCategoriesToBatchAnnotationResult( base::OnceCallback<void(const BatchAnnotationResult&)> callback, AnnotationType annotation_type, const std::string& raw_input, @@ -270,7 +270,7 @@ } absl::optional<std::vector<WeightedIdentifier>> -PageTopicsModelExecutor::ExtractCategoriesFromModelOutput( +PageTopicsModelHandler::ExtractCategoriesFromModelOutput( const std::vector<tflite::task::core::Category>& model_output) const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); @@ -394,14 +394,14 @@ return final_categories; } -void PageTopicsModelExecutor::UnloadModel() { +void PageTopicsModelHandler::UnloadModel() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); BertModelHandler::UnloadModel(); override_list_ = absl::nullopt; } -void PageTopicsModelExecutor::OnModelUpdated( +void PageTopicsModelHandler::OnModelUpdated( proto::OptimizationTarget optimization_target, const ModelInfo& model_info) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
diff --git a/components/optimization_guide/core/page_topics_model_executor.h b/components/optimization_guide/core/page_topics_model_handler.h similarity index 89% rename from components/optimization_guide/core/page_topics_model_executor.h rename to components/optimization_guide/core/page_topics_model_handler.h index 31881133..5bdb5c4 100644 --- a/components/optimization_guide/core/page_topics_model_executor.h +++ b/components/optimization_guide/core/page_topics_model_handler.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef COMPONENTS_OPTIMIZATION_GUIDE_CORE_PAGE_TOPICS_MODEL_EXECUTOR_H_ -#define COMPONENTS_OPTIMIZATION_GUIDE_CORE_PAGE_TOPICS_MODEL_EXECUTOR_H_ +#ifndef COMPONENTS_OPTIMIZATION_GUIDE_CORE_PAGE_TOPICS_MODEL_HANDLER_H_ +#define COMPONENTS_OPTIMIZATION_GUIDE_CORE_PAGE_TOPICS_MODEL_HANDLER_H_ #include <string> #include <unordered_map> @@ -24,14 +24,14 @@ // A BERT-based mode executor for page topics annotations. All the derived // functionality of this class is exclusive to the UI thread, but may post // things to the background task runner. -class PageTopicsModelExecutor : public PageContentAnnotationJobExecutor, - public BertModelHandler { +class PageTopicsModelHandler : public PageContentAnnotationJobExecutor, + public BertModelHandler { public: - PageTopicsModelExecutor( + PageTopicsModelHandler( OptimizationGuideModelProvider* model_provider, scoped_refptr<base::SequencedTaskRunner> background_task_runner, const absl::optional<proto::Any>& model_metadata); - ~PageTopicsModelExecutor() override; + ~PageTopicsModelHandler() override; // PageContentAnnotationJobExecutor: void ExecuteJob(base::OnceClosure on_job_complete_callback, @@ -95,9 +95,9 @@ SEQUENCE_CHECKER(sequence_checker_); - base::WeakPtrFactory<PageTopicsModelExecutor> weak_ptr_factory_{this}; + base::WeakPtrFactory<PageTopicsModelHandler> weak_ptr_factory_{this}; }; } // namespace optimization_guide -#endif // COMPONENTS_OPTIMIZATION_GUIDE_CORE_PAGE_TOPICS_MODEL_EXECUTOR_H_ +#endif // COMPONENTS_OPTIMIZATION_GUIDE_CORE_PAGE_TOPICS_MODEL_HANDLER_H_
diff --git a/components/optimization_guide/core/page_topics_model_executor_unittest.cc b/components/optimization_guide/core/page_topics_model_handler_unittest.cc similarity index 93% rename from components/optimization_guide/core/page_topics_model_executor_unittest.cc rename to components/optimization_guide/core/page_topics_model_handler_unittest.cc index 7f70b16..710977d 100644 --- a/components/optimization_guide/core/page_topics_model_executor_unittest.cc +++ b/components/optimization_guide/core/page_topics_model_handler_unittest.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "components/optimization_guide/core/page_topics_model_executor.h" +#include "components/optimization_guide/core/page_topics_model_handler.h" #include "base/containers/flat_map.h" #include "base/files/file_util.h" @@ -14,7 +14,7 @@ #include "base/test/task_environment.h" #include "components/optimization_guide/core/optimization_guide_features.h" #include "components/optimization_guide/core/optimization_guide_model_provider.h" -#include "components/optimization_guide/core/page_entities_model_executor.h" +#include "components/optimization_guide/core/page_entities_model_handler.h" #include "components/optimization_guide/core/test_model_info_builder.h" #include "components/optimization_guide/core/test_optimization_guide_model_provider.h" #include "components/optimization_guide/proto/models.pb.h" @@ -56,16 +56,16 @@ registered_model_metadata_; }; -class TestPageTopicsModelExecutor : public PageTopicsModelExecutor { +class TestPageTopicsModelHandler : public PageTopicsModelHandler { public: - TestPageTopicsModelExecutor( + TestPageTopicsModelHandler( OptimizationGuideModelProvider* model_provider, scoped_refptr<base::SequencedTaskRunner> background_task_runner, const absl::optional<proto::Any>& model_metadata) - : PageTopicsModelExecutor(model_provider, - background_task_runner, - model_metadata) {} - ~TestPageTopicsModelExecutor() override = default; + : PageTopicsModelHandler(model_provider, + background_task_runner, + model_metadata) {} + ~TestPageTopicsModelHandler() override = default; void ExecuteModelWithInput(ExecutionCallback callback, const std::string& input) override { @@ -79,18 +79,18 @@ std::vector<std::string> inputs_; }; -class PageTopicsModelExecutorTest : public testing::Test { +class PageTopicsModelHandlerTest : public testing::Test { public: - PageTopicsModelExecutorTest() { + PageTopicsModelHandlerTest() { scoped_feature_list_.InitWithFeatures( {features::kPageContentAnnotations}, {features::kPreventLongRunningPredictionModels}); } - ~PageTopicsModelExecutorTest() override = default; + ~PageTopicsModelHandlerTest() override = default; void SetUp() override { model_observer_tracker_ = std::make_unique<ModelObserverTracker>(); - model_executor_ = std::make_unique<TestPageTopicsModelExecutor>( + model_executor_ = std::make_unique<TestPageTopicsModelHandler>( model_observer_tracker_.get(), base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()}), /*model_metadata=*/absl::nullopt); @@ -126,7 +126,7 @@ return model_observer_tracker_.get(); } - TestPageTopicsModelExecutor* model_executor() const { + TestPageTopicsModelHandler* model_executor() const { return model_executor_.get(); } @@ -136,11 +136,11 @@ base::test::TaskEnvironment task_environment_; base::test::ScopedFeatureList scoped_feature_list_; std::unique_ptr<ModelObserverTracker> model_observer_tracker_; - std::unique_ptr<TestPageTopicsModelExecutor> model_executor_; + std::unique_ptr<TestPageTopicsModelHandler> model_executor_; }; TEST_F( - PageTopicsModelExecutorTest, + PageTopicsModelHandlerTest, GetContentModelAnnotationsFromOutputNonNumericAndLowWeightCategoriesPruned) { proto::PageTopicsModelMetadata model_metadata; model_metadata.set_version(123); @@ -170,7 +170,7 @@ WeightedIdentifier(3, 0.3))); } -TEST_F(PageTopicsModelExecutorTest, +TEST_F(PageTopicsModelHandlerTest, GetContentModelAnnotationsFromOutputNoneWeightTooStrong) { proto::PageTopicsModelMetadata model_metadata; model_metadata.set_version(123); @@ -198,7 +198,7 @@ EXPECT_FALSE(categories); } -TEST_F(PageTopicsModelExecutorTest, +TEST_F(PageTopicsModelHandlerTest, GetContentModelAnnotationsFromOutputNoneInTopButNotStrongSoPruned) { proto::PageTopicsModelMetadata model_metadata; model_metadata.set_version(123); @@ -228,7 +228,7 @@ WeightedIdentifier(2, 0.4))); } -TEST_F(PageTopicsModelExecutorTest, +TEST_F(PageTopicsModelHandlerTest, GetContentModelAnnotationsFromOutputPrunedAfterNormalization) { proto::PageTopicsModelMetadata model_metadata; model_metadata.set_version(123); @@ -261,7 +261,7 @@ WeightedIdentifier(2, 0.4))); } -TEST_F(PageTopicsModelExecutorTest, +TEST_F(PageTopicsModelHandlerTest, PostprocessCategoriesToBatchAnnotationResult) { proto::PageTopicsModelMetadata model_metadata; model_metadata.set_version(123); @@ -304,7 +304,7 @@ } // Regression test for crbug.com/1303304. -TEST_F(PageTopicsModelExecutorTest, NoneCategoryBelowMinWeight) { +TEST_F(PageTopicsModelHandlerTest, NoneCategoryBelowMinWeight) { proto::PageTopicsModelMetadata model_metadata; model_metadata.set_version(123); auto* category_params = model_metadata.mutable_output_postprocessing_params() @@ -341,7 +341,7 @@ })); } -TEST_F(PageTopicsModelExecutorTest, +TEST_F(PageTopicsModelHandlerTest, NullPostprocessCategoriesToBatchAnnotationResult) { proto::PageTopicsModelMetadata model_metadata; model_metadata.set_version(123); @@ -366,7 +366,7 @@ BatchAnnotationResult::CreatePageTopicsResult("", absl::nullopt)); } -TEST_F(PageTopicsModelExecutorTest, HostPreprocessingV1) { +TEST_F(PageTopicsModelHandlerTest, HostPreprocessingV1) { std::vector<std::pair<std::string, std::string>> tests = { {"www.chromium.org", "chromium org"}, {"foo-bar.com", "foo bar com"}, @@ -400,7 +400,7 @@ } } -TEST_F(PageTopicsModelExecutorTest, HostPreprocessingV2) { +TEST_F(PageTopicsModelHandlerTest, HostPreprocessingV2) { std::vector<std::pair<std::string, std::string>> tests = { {"www.chromium.org", "chromium org"}, {"foo-bar.com", "foo bar com"}, @@ -454,7 +454,7 @@ } } -TEST_F(PageTopicsModelExecutorTest, PreprocessingNewVersion) { +TEST_F(PageTopicsModelHandlerTest, PreprocessingNewVersion) { std::vector<std::pair<std::string, std::string>> tests = { {"www.chromium.org", "chromium org"}, {"foo-bar.com", "foo bar com"}, @@ -508,14 +508,14 @@ } } -class PageTopicsModelExecutorOverrideListTest - : public PageTopicsModelExecutorTest { +class PageTopicsModelHandlerOverrideListTest + : public PageTopicsModelHandlerTest { public: - PageTopicsModelExecutorOverrideListTest() = default; - ~PageTopicsModelExecutorOverrideListTest() override = default; + PageTopicsModelHandlerOverrideListTest() = default; + ~PageTopicsModelHandlerOverrideListTest() override = default; void SetUp() override { - PageTopicsModelExecutorTest::SetUp(); + PageTopicsModelHandlerTest::SetUp(); ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); } @@ -569,7 +569,7 @@ base::ScopedTempDir temp_dir_; }; -TEST_F(PageTopicsModelExecutorOverrideListTest, NoAdditionalFiles) { +TEST_F(PageTopicsModelHandlerOverrideListTest, NoAdditionalFiles) { base::HistogramTester histogram_tester; SendModelWithAdditionalFilesToExecutor({}); @@ -577,7 +577,7 @@ "OptimizationGuide.PageTopicsOverrideList.GotFile", false, 1); } -TEST_F(PageTopicsModelExecutorOverrideListTest, WrongAdditionalFileName) { +TEST_F(PageTopicsModelHandlerOverrideListTest, WrongAdditionalFileName) { base::HistogramTester histogram_tester; base::FilePath add_file = @@ -588,7 +588,7 @@ "OptimizationGuide.PageTopicsOverrideList.GotFile", false, 1); } -TEST_F(PageTopicsModelExecutorOverrideListTest, FileDoesntExist) { +TEST_F(PageTopicsModelHandlerOverrideListTest, FileDoesntExist) { base::HistogramTester histogram_tester; base::FilePath doesnt_exist = temp_file_path().Append( @@ -612,7 +612,7 @@ "OptimizationGuide.PageTopicsOverrideList.UsedOverride", 0); } -TEST_F(PageTopicsModelExecutorOverrideListTest, BadGzip) { +TEST_F(PageTopicsModelHandlerOverrideListTest, BadGzip) { base::HistogramTester histogram_tester; base::FilePath add_file = @@ -636,7 +636,7 @@ "OptimizationGuide.PageTopicsOverrideList.UsedOverride", 0); } -TEST_F(PageTopicsModelExecutorOverrideListTest, BadProto) { +TEST_F(PageTopicsModelHandlerOverrideListTest, BadProto) { base::HistogramTester histogram_tester; base::FilePath add_file = @@ -660,7 +660,7 @@ "OptimizationGuide.PageTopicsOverrideList.UsedOverride", 0); } -TEST_F(PageTopicsModelExecutorOverrideListTest, SuccessCase) { +TEST_F(PageTopicsModelHandlerOverrideListTest, SuccessCase) { base::HistogramTester histogram_tester; proto::PageTopicsOverrideList override_list; @@ -701,7 +701,7 @@ "OptimizationGuide.PageTopicsOverrideList.UsedOverride", true, 1); } -TEST_F(PageTopicsModelExecutorOverrideListTest, InputNotInOverride) { +TEST_F(PageTopicsModelHandlerOverrideListTest, InputNotInOverride) { base::HistogramTester histogram_tester; proto::PageTopicsOverrideList override_list; @@ -741,7 +741,7 @@ } // Regression test for crbug.com/1321808. -TEST_F(PageTopicsModelExecutorOverrideListTest, KeepsOrdering) { +TEST_F(PageTopicsModelHandlerOverrideListTest, KeepsOrdering) { base::HistogramTester histogram_tester; proto::PageTopicsOverrideList override_list; @@ -782,7 +782,7 @@ "OptimizationGuide.PageTopicsOverrideList.GotFile", true, 1); } -TEST_F(PageTopicsModelExecutorOverrideListTest, ModelUnloadsOverrideList) { +TEST_F(PageTopicsModelHandlerOverrideListTest, ModelUnloadsOverrideList) { base::HistogramTester histogram_tester; proto::PageTopicsOverrideList override_list; @@ -836,7 +836,7 @@ "OptimizationGuide.PageTopicsOverrideList.GotFile", true, 1); } -TEST_F(PageTopicsModelExecutorOverrideListTest, NewModelUnloadsOverrideList) { +TEST_F(PageTopicsModelHandlerOverrideListTest, NewModelUnloadsOverrideList) { base::HistogramTester histogram_tester; {
diff --git a/components/policy/resources/templates/policy_definitions/Accessibility/ShowAccessibilityOptionsInSystemTrayMenu.yaml b/components/policy/resources/templates/policy_definitions/Accessibility/ShowAccessibilityOptionsInSystemTrayMenu.yaml index ecdf7bd..7746b20 100644 --- a/components/policy/resources/templates/policy_definitions/Accessibility/ShowAccessibilityOptionsInSystemTrayMenu.yaml +++ b/components/policy/resources/templates/policy_definitions/Accessibility/ShowAccessibilityOptionsInSystemTrayMenu.yaml
@@ -19,7 +19,7 @@ - caption: Allow the user to decide value: null owners: -- josiahk@google.com +- katie@chromium.org - file://ui/accessibility/OWNERS schema: type: boolean
diff --git a/components/policy/resources/templates/policy_definitions/Miscellaneous/SafeBrowsingForTrustedSourcesEnabled.yaml b/components/policy/resources/templates/policy_definitions/Miscellaneous/SafeBrowsingForTrustedSourcesEnabled.yaml index cbb5a31b..bac8094 100644 --- a/components/policy/resources/templates/policy_definitions/Miscellaneous/SafeBrowsingForTrustedSourcesEnabled.yaml +++ b/components/policy/resources/templates/policy_definitions/Miscellaneous/SafeBrowsingForTrustedSourcesEnabled.yaml
@@ -3,11 +3,11 @@ desc: |- Setting the policy to Enabled or leaving it unset means downloaded files are sent to be analyzed by Safe Browsing, even when it's from a trusted source. - Setting the policy to Disabled means downloaded files won't be sent to be analyzed by Safe Browsing when it's from a trusted source. + Setting the policy to Disabled means downloaded files won't be sent to be analyzed by Safe Browsing when it's from a trusted source. - These restrictions apply to downloads triggered from webpage content, as well as the Download link menu option. These restrictions don't apply to the save or download of the currently displayed page or to saving as PDF from the printing options. + These restrictions apply to downloads triggered from webpage content, as well as the Download link menu option. These restrictions don't apply to the save or download of the currently displayed page or to saving as PDF from the printing options. - On <ph name="MS_WIN_NAME">Microsoft® Windows®</ph>, this functionality is only available on instances that are joined to a <ph name="MS_AD_NAME">Microsoft® Active Directory®</ph> domain, running on Windows 10 Pro, or enrolled in <ph name="CHROME_BROWSER_CLOUD_MANAGEMENT_NAME">Chrome Browser Cloud Management</ph>. On <ph name="MAC_OS_NAME">macOS</ph>, this functionality is only available on instances that are managed via MDM, or joined to a domain via MCX. + On <ph name="MS_WIN_NAME">Microsoft® Windows®</ph>, this functionality is only available on instances that are joined to a <ph name="MS_AD_NAME">Microsoft® Active Directory®</ph> domain, running on Windows 10 Pro, or enrolled in <ph name="CHROME_BROWSER_CLOUD_MANAGEMENT_NAME">Chrome Browser Cloud Management</ph>. example_value: false features: can_be_recommended: true
diff --git a/components/sessions/core/session_id_generator.cc b/components/sessions/core/session_id_generator.cc index 283f110f..1d7d459 100644 --- a/components/sessions/core/session_id_generator.cc +++ b/components/sessions/core/session_id_generator.cc
@@ -4,6 +4,8 @@ #include "components/sessions/core/session_id_generator.h" +#include <ostream> + #include "base/bind.h" #include "base/rand_util.h" #include "components/prefs/pref_registry_simple.h"
diff --git a/components/sync/trusted_vault/trusted_vault_degraded_recoverability_handler.cc b/components/sync/trusted_vault/trusted_vault_degraded_recoverability_handler.cc index de0e2d2..316217b 100644 --- a/components/sync/trusted_vault/trusted_vault_degraded_recoverability_handler.cc +++ b/components/sync/trusted_vault/trusted_vault_degraded_recoverability_handler.cc
@@ -59,11 +59,6 @@ : connection_(connection), delegate_(delegate), account_info_(account_info) { - long_degraded_recoverability_refresh_period_ = - kSyncTrustedVaultLongPeriodDegradedRecoverabilityPolling.Get(); - short_degraded_recoverability_refresh_period_ = - kSyncTrustedVaultShortPeriodDegradedRecoverabilityPolling.Get(); - current_refresh_period_ = long_degraded_recoverability_refresh_period_; degraded_recoverability_value_ = degraded_recoverability_state.degraded_recoverability_value(); base::UmaHistogramExactLinear("Sync.TrustedVaultDegradedRecoverabilityValue", @@ -74,11 +69,17 @@ base::Time last_refresh_time = ProtoTimeToTime(degraded_recoverability_state .last_refresh_time_millis_since_unix_epoch()); - if (base::Time::Now() > last_refresh_time) { + if (base::Time::Now() >= last_refresh_time) { last_refresh_time_ = base::TimeTicks::Now() - (base::Time::Now() - last_refresh_time); } } + + long_degraded_recoverability_refresh_period_ = + kSyncTrustedVaultLongPeriodDegradedRecoverabilityPolling.Get(); + short_degraded_recoverability_refresh_period_ = + kSyncTrustedVaultShortPeriodDegradedRecoverabilityPolling.Get(); + UpdateCurrentRefreshPeriod(); } TrustedVaultDegradedRecoverabilityHandler:: @@ -91,16 +92,6 @@ RefreshImmediately(); } -void TrustedVaultDegradedRecoverabilityHandler::StartLongIntervalRefreshing() { - current_refresh_period_ = long_degraded_recoverability_refresh_period_; - Start(); -} - -void TrustedVaultDegradedRecoverabilityHandler::StartShortIntervalRefreshing() { - current_refresh_period_ = short_degraded_recoverability_refresh_period_; - Start(); -} - void TrustedVaultDegradedRecoverabilityHandler::RefreshImmediately() { if (!next_refresh_timer_.IsRunning()) { return; @@ -121,6 +112,15 @@ } } +void TrustedVaultDegradedRecoverabilityHandler::UpdateCurrentRefreshPeriod() { + if (degraded_recoverability_value_ == + sync_pb::DegradedRecoverabilityValue::kDegraded) { + current_refresh_period_ = short_degraded_recoverability_refresh_period_; + return; + } + current_refresh_period_ = long_degraded_recoverability_refresh_period_; +} + void TrustedVaultDegradedRecoverabilityHandler::Start() { next_refresh_timer_.Start( FROM_HERE, @@ -167,6 +167,7 @@ } if (degraded_recoverability_value_ != old_degraded_recoverability_value) { delegate_->OnDegradedRecoverabilityChanged(); + UpdateCurrentRefreshPeriod(); } last_refresh_time_ = base::TimeTicks::Now(); delegate_->WriteDegradedRecoverabilityState(MakeDegradedRecoverabilityState(
diff --git a/components/sync/trusted_vault/trusted_vault_degraded_recoverability_handler.h b/components/sync/trusted_vault/trusted_vault_degraded_recoverability_handler.h index 0bf8a9c..5c987ab 100644 --- a/components/sync/trusted_vault/trusted_vault_degraded_recoverability_handler.h +++ b/components/sync/trusted_vault/trusted_vault_degraded_recoverability_handler.h
@@ -56,13 +56,12 @@ // GetIsRecoverabilityDegraded(). void GetIsRecoverabilityDegraded(base::OnceCallback<void(bool)> cb); - // TODO(crbug.com/1247990): The accessibility of the following three functions - // should be changed to be private. - void StartLongIntervalRefreshing(); - void StartShortIntervalRefreshing(); + // TODO(crbug.com/1247990): Should be inlined inside + // HintDegradedRecoverabilityChanged(). void RefreshImmediately(); private: + void UpdateCurrentRefreshPeriod(); void Start(); void Refresh(); void OnRecoverabilityIsDegradedDownloaded(
diff --git a/components/sync/trusted_vault/trusted_vault_degraded_recoverability_handler_unittest.cc b/components/sync/trusted_vault/trusted_vault_degraded_recoverability_handler_unittest.cc index 6564c3cd..e4b5828 100644 --- a/components/sync/trusted_vault/trusted_vault_degraded_recoverability_handler_unittest.cc +++ b/components/sync/trusted_vault/trusted_vault_degraded_recoverability_handler_unittest.cc
@@ -93,41 +93,11 @@ TrustedVaultDegradedRecoverabilityHandlerTest() = default; ~TrustedVaultDegradedRecoverabilityHandlerTest() override = default; - void SetUp() override { - ON_CALL(connection_, DownloadIsRecoverabilityDegraded( - Eq(MakeAccountInfoWithGaiaId("user")), _)) - .WillByDefault( - [&](const CoreAccountInfo&, - MockTrustedVaultConnection::IsRecoverabilityDegradedCallback - callback) { - std::move(callback).Run( - TrustedVaultRecoverabilityStatus::kDegraded); - return std::make_unique<TrustedVaultConnection::Request>(); - }); - scheduler_ = std::make_unique<TrustedVaultDegradedRecoverabilityHandler>( - &connection_, &delegate_, MakeAccountInfoWithGaiaId("user"), - sync_pb::LocalTrustedVaultDegradedRecoverabilityState()); - - // Start the scheduler. - scheduler_->GetIsRecoverabilityDegraded(base::DoNothing()); - - // Moving the time forward by one millisecond to make sure that the first - // refresh had called. - task_environment().FastForwardBy(base::Milliseconds(1)); - } - - TrustedVaultDegradedRecoverabilityHandler& scheduler() { - return *scheduler_.get(); - } - base::test::SingleThreadTaskEnvironment& task_environment() { return task_environment_; } protected: - testing::NiceMock<MockTrustedVaultConnection> connection_; - testing::NiceMock<MockDelegate> delegate_; - std::unique_ptr<TrustedVaultDegradedRecoverabilityHandler> scheduler_; base::test::SingleThreadTaskEnvironment task_environment_{ base::test::TaskEnvironment::TimeSource::MOCK_TIME}; }; @@ -135,17 +105,8 @@ TEST_F(TrustedVaultDegradedRecoverabilityHandlerTest, ShouldPendTheCallbackUntilTheFirstRefreshIsCalled) { testing::NiceMock<MockTrustedVaultConnection> connection; - ON_CALL(connection, DownloadIsRecoverabilityDegraded( - Eq(MakeAccountInfoWithGaiaId("user")), _)) - .WillByDefault( - [&](const CoreAccountInfo&, - MockTrustedVaultConnection::IsRecoverabilityDegradedCallback - callback) { - std::move(callback).Run( - TrustedVaultRecoverabilityStatus::kDegraded); - return std::make_unique<TrustedVaultConnection::Request>(); - }); testing::NiceMock<MockDelegate> delegate; + // Passing empty LocalDegradedRecoverability state indicates that this is the // first initialization and new state needs to be fetched immediately. std::unique_ptr<TrustedVaultDegradedRecoverabilityHandler> scheduler = @@ -154,9 +115,15 @@ sync_pb::LocalTrustedVaultDegradedRecoverabilityState()); base::MockCallback<base::OnceCallback<void(bool)>> completion_callback; - EXPECT_CALL(connection, DownloadIsRecoverabilityDegraded); + EXPECT_CALL(connection, DownloadIsRecoverabilityDegraded( + Eq(MakeAccountInfoWithGaiaId("user")), _)) + .WillOnce([&](const CoreAccountInfo&, + MockTrustedVaultConnection::IsRecoverabilityDegradedCallback + callback) { + std::move(callback).Run(TrustedVaultRecoverabilityStatus::kDegraded); + return std::make_unique<TrustedVaultConnection::Request>(); + }); EXPECT_CALL(completion_callback, Run(true)); - scheduler->GetIsRecoverabilityDegraded(completion_callback.Get()); task_environment().FastForwardBy(base::Milliseconds(1)); } @@ -172,7 +139,8 @@ degraded_recoverability_state.set_degraded_recoverability_value( sync_pb::DegradedRecoverabilityValue::kNotDegraded); degraded_recoverability_state.set_last_refresh_time_millis_since_unix_epoch( - TimeToProtoTime(base::Time::Now() - base::Seconds(1))); + TimeToProtoTime(base::Time::Now())); + std::unique_ptr<TrustedVaultDegradedRecoverabilityHandler> scheduler = std::make_unique<TrustedVaultDegradedRecoverabilityHandler>( &connection, &delegate, MakeAccountInfoWithGaiaId("user"), @@ -181,28 +149,123 @@ EXPECT_CALL(connection, DownloadIsRecoverabilityDegraded).Times(0); EXPECT_CALL(completion_callback, Run(false)); - scheduler->GetIsRecoverabilityDegraded(completion_callback.Get()); } TEST_F(TrustedVaultDegradedRecoverabilityHandlerTest, ShouldRefreshImmediately) { - EXPECT_CALL(connection_, DownloadIsRecoverabilityDegraded); - scheduler().RefreshImmediately(); + testing::NiceMock<MockTrustedVaultConnection> connection; + ON_CALL(connection, DownloadIsRecoverabilityDegraded( + Eq(MakeAccountInfoWithGaiaId("user")), _)) + .WillByDefault( + [&](const CoreAccountInfo&, + MockTrustedVaultConnection::IsRecoverabilityDegradedCallback + callback) { + std::move(callback).Run( + TrustedVaultRecoverabilityStatus::kNotDegraded); + return std::make_unique<TrustedVaultConnection::Request>(); + }); + testing::NiceMock<MockDelegate> delegate; + + // Passing empty LocalDegradedRecoverability state indicates that this is the + // first initialization and new state needs to be fetched immediately. + std::unique_ptr<TrustedVaultDegradedRecoverabilityHandler> scheduler = + std::make_unique<TrustedVaultDegradedRecoverabilityHandler>( + &connection, &delegate, MakeAccountInfoWithGaiaId("user"), + sync_pb::LocalTrustedVaultDegradedRecoverabilityState()); + // Start the scheduler. + scheduler->GetIsRecoverabilityDegraded(base::DoNothing()); + // Moving the time forward by one millisecond to make sure that the first + // refresh had called. + task_environment().FastForwardBy(base::Milliseconds(1)); + + EXPECT_CALL(connection, DownloadIsRecoverabilityDegraded); + scheduler->RefreshImmediately(); } TEST_F(TrustedVaultDegradedRecoverabilityHandlerTest, - ShouldRefreshOncePerLongPeriod) { - EXPECT_CALL(connection_, DownloadIsRecoverabilityDegraded); + ShouldRefreshOncePerShortPeriod) { + testing::NiceMock<MockTrustedVaultConnection> connection; + testing::NiceMock<MockDelegate> delegate; + sync_pb::LocalTrustedVaultDegradedRecoverabilityState + degraded_recoverability_state; + degraded_recoverability_state.set_degraded_recoverability_value( + sync_pb::DegradedRecoverabilityValue::kDegraded); + degraded_recoverability_state.set_last_refresh_time_millis_since_unix_epoch( + TimeToProtoTime(base::Time::Now())); + + std::unique_ptr<TrustedVaultDegradedRecoverabilityHandler> scheduler = + std::make_unique<TrustedVaultDegradedRecoverabilityHandler>( + &connection, &delegate, MakeAccountInfoWithGaiaId("user"), + degraded_recoverability_state); + // Start the scheduler. + scheduler->GetIsRecoverabilityDegraded(base::DoNothing()); + + EXPECT_CALL(connection, DownloadIsRecoverabilityDegraded); task_environment().FastForwardBy( - kSyncTrustedVaultLongPeriodDegradedRecoverabilityPolling.Get() + + kSyncTrustedVaultShortPeriodDegradedRecoverabilityPolling.Get() + base::Milliseconds(1)); } TEST_F(TrustedVaultDegradedRecoverabilityHandlerTest, + ShouldRefreshOncePerLongPeriod) { + testing::NiceMock<MockTrustedVaultConnection> connection; + testing::NiceMock<MockDelegate> delegate; + sync_pb::LocalTrustedVaultDegradedRecoverabilityState + degraded_recoverability_state; + degraded_recoverability_state.set_degraded_recoverability_value( + sync_pb::DegradedRecoverabilityValue::kNotDegraded); + degraded_recoverability_state.set_last_refresh_time_millis_since_unix_epoch( + TimeToProtoTime(base::Time::Now())); + + std::unique_ptr<TrustedVaultDegradedRecoverabilityHandler> scheduler = + std::make_unique<TrustedVaultDegradedRecoverabilityHandler>( + &connection, &delegate, MakeAccountInfoWithGaiaId("user"), + degraded_recoverability_state); + // Start the scheduler. + scheduler->GetIsRecoverabilityDegraded(base::DoNothing()); + + EXPECT_CALL(connection, DownloadIsRecoverabilityDegraded).Times(0); + task_environment().FastForwardBy( + kSyncTrustedVaultShortPeriodDegradedRecoverabilityPolling.Get() + + base::Milliseconds(1)); + testing::Mock::VerifyAndClearExpectations(&connection); + + EXPECT_CALL(connection, DownloadIsRecoverabilityDegraded); + task_environment().FastForwardBy( + kSyncTrustedVaultLongPeriodDegradedRecoverabilityPolling.Get() - + kSyncTrustedVaultShortPeriodDegradedRecoverabilityPolling.Get()); +} + +TEST_F(TrustedVaultDegradedRecoverabilityHandlerTest, ShouldSwitchToShortPeriod) { - scheduler().StartShortIntervalRefreshing(); - EXPECT_CALL(connection_, DownloadIsRecoverabilityDegraded); + testing::NiceMock<MockTrustedVaultConnection> connection; + testing::NiceMock<MockDelegate> delegate; + + // Passing empty LocalDegradedRecoverability state indicates that this is the + // first initialization and new state needs to be fetched immediately. + std::unique_ptr<TrustedVaultDegradedRecoverabilityHandler> scheduler = + std::make_unique<TrustedVaultDegradedRecoverabilityHandler>( + &connection, &delegate, MakeAccountInfoWithGaiaId("user"), + sync_pb::LocalTrustedVaultDegradedRecoverabilityState()); + + // Make handler aware about degraded recoverability. + EXPECT_CALL(connection, DownloadIsRecoverabilityDegraded( + Eq(MakeAccountInfoWithGaiaId("user")), _)) + .WillOnce([&](const CoreAccountInfo&, + MockTrustedVaultConnection::IsRecoverabilityDegradedCallback + callback) { + std::move(callback).Run(TrustedVaultRecoverabilityStatus::kDegraded); + return std::make_unique<TrustedVaultConnection::Request>(); + }); + EXPECT_CALL(delegate, OnDegradedRecoverabilityChanged); + // Start the scheduler. + scheduler->GetIsRecoverabilityDegraded(base::DoNothing()); + task_environment().FastForwardBy(base::Milliseconds(1)); + testing::Mock::VerifyAndClearExpectations(&connection); + + // Verify that handler switches to short polling period. + EXPECT_CALL(connection, DownloadIsRecoverabilityDegraded); task_environment().FastForwardBy( kSyncTrustedVaultShortPeriodDegradedRecoverabilityPolling.Get() + base::Milliseconds(1)); @@ -210,40 +273,78 @@ TEST_F(TrustedVaultDegradedRecoverabilityHandlerTest, ShouldSwitchToLongPeriod) { - scheduler().StartShortIntervalRefreshing(); - scheduler().StartLongIntervalRefreshing(); - EXPECT_CALL(connection_, DownloadIsRecoverabilityDegraded).Times(0); + testing::NiceMock<MockTrustedVaultConnection> connection; + testing::NiceMock<MockDelegate> delegate; + sync_pb::LocalTrustedVaultDegradedRecoverabilityState + degraded_recoverability_state; + degraded_recoverability_state.set_degraded_recoverability_value( + sync_pb::DegradedRecoverabilityValue::kDegraded); + degraded_recoverability_state.set_last_refresh_time_millis_since_unix_epoch( + TimeToProtoTime(base::Time::Now())); + + std::unique_ptr<TrustedVaultDegradedRecoverabilityHandler> scheduler = + std::make_unique<TrustedVaultDegradedRecoverabilityHandler>( + &connection, &delegate, MakeAccountInfoWithGaiaId("user"), + degraded_recoverability_state); + // Start the scheduler. + scheduler->GetIsRecoverabilityDegraded(base::DoNothing()); + + // Make handler aware about degraded recoverability. + EXPECT_CALL(connection, DownloadIsRecoverabilityDegraded( + Eq(MakeAccountInfoWithGaiaId("user")), _)) + .WillOnce([&](const CoreAccountInfo&, + MockTrustedVaultConnection::IsRecoverabilityDegradedCallback + callback) { + std::move(callback).Run(TrustedVaultRecoverabilityStatus::kNotDegraded); + return std::make_unique<TrustedVaultConnection::Request>(); + }); + EXPECT_CALL(delegate, OnDegradedRecoverabilityChanged); task_environment().FastForwardBy( kSyncTrustedVaultShortPeriodDegradedRecoverabilityPolling.Get() + base::Milliseconds(1)); - EXPECT_CALL(connection_, DownloadIsRecoverabilityDegraded); - task_environment().FastForwardBy( - kSyncTrustedVaultLongPeriodDegradedRecoverabilityPolling.Get() + - base::Milliseconds(1)); -} + testing::Mock::VerifyAndClearExpectations(&connection); -TEST_F(TrustedVaultDegradedRecoverabilityHandlerTest, - ShouldSwitchToShortPeriodAndAccountForTimePassed) { - task_environment().FastForwardBy( - kSyncTrustedVaultShortPeriodDegradedRecoverabilityPolling.Get() - - base::Seconds(1)); - scheduler().StartShortIntervalRefreshing(); - EXPECT_CALL(connection_, DownloadIsRecoverabilityDegraded); - task_environment().FastForwardBy(base::Seconds(1) + base::Milliseconds(1)); -} + // Verify that handler switches to long polling period. -TEST_F(TrustedVaultDegradedRecoverabilityHandlerTest, - ShouldSwitchToShortPeriodAndRefreshImmediately) { + EXPECT_CALL(connection, DownloadIsRecoverabilityDegraded).Times(0); task_environment().FastForwardBy( kSyncTrustedVaultShortPeriodDegradedRecoverabilityPolling.Get() + - base::Seconds(1)); - EXPECT_CALL(connection_, DownloadIsRecoverabilityDegraded); - scheduler().StartShortIntervalRefreshing(); - task_environment().FastForwardBy(base::Milliseconds(1)); + base::Milliseconds(1)); + testing::Mock::VerifyAndClearExpectations(&connection); + + EXPECT_CALL(connection, DownloadIsRecoverabilityDegraded); + task_environment().FastForwardBy( + kSyncTrustedVaultLongPeriodDegradedRecoverabilityPolling.Get() - + kSyncTrustedVaultShortPeriodDegradedRecoverabilityPolling.Get()); } TEST_F(TrustedVaultDegradedRecoverabilityHandlerTest, ShouldWriteTheStateImmediatelyWithRecoverabilityDegradedAndCurrentTime) { + testing::NiceMock<MockTrustedVaultConnection> connection; + ON_CALL(connection, DownloadIsRecoverabilityDegraded( + Eq(MakeAccountInfoWithGaiaId("user")), _)) + .WillByDefault( + [&](const CoreAccountInfo&, + MockTrustedVaultConnection::IsRecoverabilityDegradedCallback + callback) { + std::move(callback).Run( + TrustedVaultRecoverabilityStatus::kNotDegraded); + return std::make_unique<TrustedVaultConnection::Request>(); + }); + testing::NiceMock<MockDelegate> delegate; + + // Passing empty LocalDegradedRecoverability state indicates that this is the + // first initialization and new state needs to be fetched immediately. + std::unique_ptr<TrustedVaultDegradedRecoverabilityHandler> scheduler = + std::make_unique<TrustedVaultDegradedRecoverabilityHandler>( + &connection, &delegate, MakeAccountInfoWithGaiaId("user"), + sync_pb::LocalTrustedVaultDegradedRecoverabilityState()); + // Start the scheduler. + scheduler->GetIsRecoverabilityDegraded(base::DoNothing()); + // Moving the time forward by one millisecond to make sure that the first + // refresh had called. + task_environment().FastForwardBy(base::Milliseconds(1)); + sync_pb::LocalTrustedVaultDegradedRecoverabilityState degraded_recoverability_state; degraded_recoverability_state.set_degraded_recoverability_value( @@ -252,24 +353,49 @@ // written. degraded_recoverability_state.set_last_refresh_time_millis_since_unix_epoch( TimeToProtoTime(base::Time::Now())); - EXPECT_CALL(connection_, DownloadIsRecoverabilityDegraded( - Eq(MakeAccountInfoWithGaiaId("user")), _)) + + EXPECT_CALL(connection, DownloadIsRecoverabilityDegraded( + Eq(MakeAccountInfoWithGaiaId("user")), _)) .WillOnce([&](const CoreAccountInfo&, MockTrustedVaultConnection::IsRecoverabilityDegradedCallback callback) { std::move(callback).Run(TrustedVaultRecoverabilityStatus::kDegraded); return std::make_unique<TrustedVaultConnection::Request>(); }); - EXPECT_CALL(delegate_, OnDegradedRecoverabilityChanged).Times(0); - EXPECT_CALL(delegate_, + EXPECT_CALL(delegate, WriteDegradedRecoverabilityState(DegradedRecoverabilityStateEq( degraded_recoverability_state))); - scheduler().RefreshImmediately(); + scheduler->RefreshImmediately(); } TEST_F( TrustedVaultDegradedRecoverabilityHandlerTest, ShouldWriteTheStateImmediatelyWithRecoverabilityNotDegradedAndCurrentTime) { + testing::NiceMock<MockTrustedVaultConnection> connection; + ON_CALL(connection, DownloadIsRecoverabilityDegraded( + Eq(MakeAccountInfoWithGaiaId("user")), _)) + .WillByDefault( + [&](const CoreAccountInfo&, + MockTrustedVaultConnection::IsRecoverabilityDegradedCallback + callback) { + std::move(callback).Run( + TrustedVaultRecoverabilityStatus::kDegraded); + return std::make_unique<TrustedVaultConnection::Request>(); + }); + testing::NiceMock<MockDelegate> delegate; + + // Passing empty LocalDegradedRecoverability state indicates that this is the + // first initialization and new state needs to be fetched immediately. + std::unique_ptr<TrustedVaultDegradedRecoverabilityHandler> scheduler = + std::make_unique<TrustedVaultDegradedRecoverabilityHandler>( + &connection, &delegate, MakeAccountInfoWithGaiaId("user"), + sync_pb::LocalTrustedVaultDegradedRecoverabilityState()); + // Start the scheduler. + scheduler->GetIsRecoverabilityDegraded(base::DoNothing()); + // Moving the time forward by one millisecond to make sure that the first + // refresh had called. + task_environment().FastForwardBy(base::Milliseconds(1)); + sync_pb::LocalTrustedVaultDegradedRecoverabilityState degraded_recoverability_state; degraded_recoverability_state.set_degraded_recoverability_value( @@ -278,19 +404,19 @@ // written. degraded_recoverability_state.set_last_refresh_time_millis_since_unix_epoch( TimeToProtoTime(base::Time::Now())); - EXPECT_CALL(connection_, DownloadIsRecoverabilityDegraded( - Eq(MakeAccountInfoWithGaiaId("user")), _)) + + EXPECT_CALL(connection, DownloadIsRecoverabilityDegraded( + Eq(MakeAccountInfoWithGaiaId("user")), _)) .WillOnce([&](const CoreAccountInfo&, MockTrustedVaultConnection::IsRecoverabilityDegradedCallback callback) { std::move(callback).Run(TrustedVaultRecoverabilityStatus::kNotDegraded); return std::make_unique<TrustedVaultConnection::Request>(); }); - EXPECT_CALL(delegate_, OnDegradedRecoverabilityChanged); - EXPECT_CALL(delegate_, + EXPECT_CALL(delegate, WriteDegradedRecoverabilityState(DegradedRecoverabilityStateEq( degraded_recoverability_state))); - scheduler().RefreshImmediately(); + scheduler->RefreshImmediately(); } TEST_F(TrustedVaultDegradedRecoverabilityHandlerTest, @@ -300,7 +426,7 @@ sync_pb::LocalTrustedVaultDegradedRecoverabilityState degraded_recoverability_state; degraded_recoverability_state.set_last_refresh_time_millis_since_unix_epoch( - TimeToProtoTime(base::Time::Now() - base::Days(4))); + TimeToProtoTime(base::Time::Now() - base::Minutes(1))); EXPECT_CALL(connection, DownloadIsRecoverabilityDegraded); std::unique_ptr<TrustedVaultDegradedRecoverabilityHandler> scheduler = @@ -309,7 +435,9 @@ degraded_recoverability_state); // Start the scheduler. scheduler->GetIsRecoverabilityDegraded(base::DoNothing()); - task_environment().FastForwardBy(base::Days(3) + base::Milliseconds(1)); + task_environment().FastForwardBy( + kSyncTrustedVaultLongPeriodDegradedRecoverabilityPolling.Get() - + base::Minutes(1) + base::Milliseconds(1)); } } // namespace
diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn index 5153bc29c..e48cde4 100644 --- a/content/browser/BUILD.gn +++ b/content/browser/BUILD.gn
@@ -2431,15 +2431,15 @@ "font_access/font_enumeration_data_source_fuchsia.cc", "font_access/font_enumeration_data_source_fuchsia.h", "memory/swap_metrics_driver_impl_fuchsia.cc", + "renderer_host/media/fuchsia_media_cdm_provider_impl.cc", + "renderer_host/media/fuchsia_media_cdm_provider_impl.h", "renderer_host/media/fuchsia_media_codec_provider_impl.cc", "renderer_host/media/fuchsia_media_codec_provider_impl.h", - "renderer_host/media/media_resource_provider_fuchsia.cc", - "renderer_host/media/media_resource_provider_fuchsia.h", "speech/tts_fuchsia.cc", ] deps += [ "//media/fuchsia/cdm/service", - "//media/fuchsia/mojom:fuchsia_media_resource_provider", + "//media/fuchsia/mojom:fuchsia_media", "//third_party/abseil-cpp:absl", "//third_party/fuchsia-sdk/sdk/fidl/fuchsia.accessibility.semantics", "//third_party/fuchsia-sdk/sdk/fidl/fuchsia.mediacodec", @@ -3042,6 +3042,8 @@ "//third_party/blink/public/mojom:mojom_platform_blink", "//third_party/icu", "//ui/accessibility:ax_assistant", + "//ui/accessibility:ax_base_android", + "//ui/accessibility:ax_base_java", "//ui/accessibility/mojom", "//ui/accessibility/mojom:ax_assistant_mojom", "//ui/android",
diff --git a/content/browser/accessibility/browser_accessibility_state_impl_android.cc b/content/browser/accessibility/browser_accessibility_state_impl_android.cc index f8bdf324..82cea149 100644 --- a/content/browser/accessibility/browser_accessibility_state_impl_android.cc +++ b/content/browser/accessibility/browser_accessibility_state_impl_android.cc
@@ -4,19 +4,14 @@ #include "content/browser/accessibility/browser_accessibility_state_impl_android.h" -#include "base/android/jni_android.h" -#include "base/android/jni_string.h" #include "base/containers/contains.h" #include "base/metrics/histogram_macros.h" #include "base/no_destructor.h" #include "content/browser/web_contents/web_contents_impl.h" -#include "content/public/android/content_jni_headers/BrowserAccessibilityState_jni.h" #include "content/public/browser/browser_thread.h" +#include "ui/accessibility/android/accessibility_state.h" #include "ui/gfx/animation/animation.h" -using base::android::AttachCurrentThread; -using base::android::ScopedJavaLocalRef; - namespace content { namespace { @@ -253,40 +248,35 @@ } // namespace BrowserAccessibilityStateImplAndroid::BrowserAccessibilityStateImplAndroid() { - // Setup the listeners for accessibility state changes, so we can - // inform the renderer about changes. - JNIEnv* env = AttachCurrentThread(); - Java_BrowserAccessibilityState_registerObservers(env); + ui::AccessibilityState::RegisterObservers(); + ui::AccessibilityState::RegisterAnimatorDurationScaleDelegate(this); +} + +BrowserAccessibilityStateImplAndroid::~BrowserAccessibilityStateImplAndroid() { + ui::AccessibilityState::UnregisterAnimatorDurationScaleDelegate(this); } void BrowserAccessibilityStateImplAndroid::CollectAccessibilityServiceStats() { - JNIEnv* env = AttachCurrentThread(); int event_type_mask = - Java_BrowserAccessibilityState_getAccessibilityServiceEventTypeMask(env); - + ui::AccessibilityState::GetAccessibilityServiceEventTypeMask(); int feedback_type_mask = - Java_BrowserAccessibilityState_getAccessibilityServiceFeedbackTypeMask( - env); + ui::AccessibilityState::GetAccessibilityServiceFeedbackTypeMask(); - int flags_mask = - Java_BrowserAccessibilityState_getAccessibilityServiceFlagsMask(env); + int flags_mask = ui::AccessibilityState::GetAccessibilityServiceFlagsMask(); int capabilities_mask = - Java_BrowserAccessibilityState_getAccessibilityServiceCapabilitiesMask( - env); + ui::AccessibilityState::GetAccessibilityServiceCapabilitiesMask(); - auto service_ids = - Java_BrowserAccessibilityState_getAccessibilityServiceIds(env); + std::vector<std::string> service_ids = + ui::AccessibilityState::GetAccessibilityServiceIds(); - jsize len = env->GetArrayLength(service_ids.obj()); + int len = service_ids.size(); bool has_assistive_tech = false; bool has_password_manager = false; bool has_unknown = false; - for (jsize i = 0; i < len; ++i) { - auto* id = env->GetObjectArrayElement(service_ids.obj(), i); - std::string service_id = - base::android::ConvertJavaStringToUTF8(env, static_cast<jstring>(id)); + for (int i = 0; i < len; ++i) { + std::string service_id = service_ids[i]; std::string service_package = service_id.erase(service_id.find("/")); uint32_t service_hash = base::PersistentHash(service_package); @@ -403,6 +393,18 @@ CAPABILITY_TYPE_HISTOGRAM(capabilities_mask, CAN_TAKE_SCREENSHOT, histogram); } +void BrowserAccessibilityStateImplAndroid::OnAnimatorDurationScaleChanged() { + // We need to call into gfx::Animation and WebContentsImpl on the UI thread, + // so ensure that we setup the notification on the correct thread. + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + + gfx::Animation::UpdatePrefersReducedMotion(); + for (content::WebContentsImpl* wc : + content::WebContentsImpl::GetAllWebContents()) { + wc->OnWebPreferencesChanged(); + } +} + void BrowserAccessibilityStateImplAndroid::UpdateHistogramsOnOtherThread() { BrowserAccessibilityStateImpl::UpdateHistogramsOnOtherThread(); @@ -441,23 +443,6 @@ } } -bool BrowserAccessibilityStateImplAndroid::HasSpokenFeedbackServicePresent() { - JNIEnv* env = AttachCurrentThread(); - return Java_BrowserAccessibilityState_hasSpokenFeedbackServicePresent(env); -} - -// static -void JNI_BrowserAccessibilityState_OnAnimatorDurationScaleChanged(JNIEnv* env) { - // We need to call into gfx::Animation and WebContentsImpl on the UI thread, - // so ensure that we setup the notification on the correct thread. - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - gfx::Animation::UpdatePrefersReducedMotion(); - for (WebContentsImpl* wc : WebContentsImpl::GetAllWebContents()) { - wc->OnWebPreferencesChanged(); - } -} - // // BrowserAccessibilityStateImpl::GetInstance implementation that constructs // this class instead of the base class.
diff --git a/content/browser/accessibility/browser_accessibility_state_impl_android.h b/content/browser/accessibility/browser_accessibility_state_impl_android.h index 6cd1ab7..321e295d 100644 --- a/content/browser/accessibility/browser_accessibility_state_impl_android.h +++ b/content/browser/accessibility/browser_accessibility_state_impl_android.h
@@ -6,16 +6,18 @@ #define CONTENT_BROWSER_ACCESSIBILITY_BROWSER_ACCESSIBILITY_STATE_IMPL_ANDROID_H_ #include "content/browser/accessibility/browser_accessibility_state_impl.h" +#include "ui/accessibility/android/accessibility_state.h" namespace content { class BrowserContext; class BrowserAccessibilityStateImplAndroid - : public BrowserAccessibilityStateImpl { + : public BrowserAccessibilityStateImpl, + public ui::AccessibilityState::Delegate { public: BrowserAccessibilityStateImplAndroid(); - ~BrowserAccessibilityStateImplAndroid() override = default; + ~BrowserAccessibilityStateImplAndroid() override; void CollectAccessibilityServiceStats(); void RecordAccessibilityServiceStatsHistogram(int event_type_mask, @@ -24,7 +26,8 @@ int capabilities_mask, std::string histogram); - bool HasSpokenFeedbackServicePresent() override; + // ui::AccessibilityState::Delegate overrides + void OnAnimatorDurationScaleChanged() override; protected: void UpdateHistogramsOnOtherThread() override;
diff --git a/content/browser/browser_interface_binders.cc b/content/browser/browser_interface_binders.cc index cb3c2db..13a62c7 100644 --- a/content/browser/browser_interface_binders.cc +++ b/content/browser/browser_interface_binders.cc
@@ -210,8 +210,8 @@ #endif #if BUILDFLAG(IS_FUCHSIA) -#include "content/browser/renderer_host/media/media_resource_provider_fuchsia.h" -#include "media/fuchsia/mojom/fuchsia_media_resource_provider.mojom.h" +#include "content/browser/renderer_host/media/fuchsia_media_cdm_provider_impl.h" +#include "media/fuchsia/mojom/fuchsia_media.mojom.h" #endif namespace blink { @@ -1105,8 +1105,8 @@ #endif #if BUILDFLAG(IS_FUCHSIA) - map->Add<media::mojom::FuchsiaMediaResourceProvider>( - base::BindRepeating(&MediaResourceProviderFuchsia::Bind)); + map->Add<media::mojom::FuchsiaMediaCdmProvider>( + base::BindRepeating(&FuchsiaMediaCdmProviderImpl::Bind)); #endif }
diff --git a/content/browser/renderer_host/frame_tree_node.cc b/content/browser/renderer_host/frame_tree_node.cc index e264e93..20e72b6 100644 --- a/content/browser/renderer_host/frame_tree_node.cc +++ b/content/browser/renderer_host/frame_tree_node.cc
@@ -694,7 +694,7 @@ for (RenderFrameHostImpl* rfh = current_frame_host(); rfh; rfh = rfh->GetParent()) { rfh->DidReceiveUserActivation(); - rfh->frame_tree_node()->user_activation_state_.Activate(notification_type); + rfh->ActivateUserActivation(notification_type); } current_frame_host()->browsing_context_state()->set_has_active_user_gesture( @@ -709,7 +709,7 @@ for (FrameTreeNode* node : frame_tree()->Nodes()) { if (node->current_frame_host()->GetLastCommittedOrigin().IsSameOriginWith( current_origin)) { - node->user_activation_state_.Activate(notification_type); + node->current_frame_host()->ActivateUserActivation(notification_type); } } } @@ -721,9 +721,9 @@ } bool FrameTreeNode::ConsumeTransientUserActivation() { - bool was_active = user_activation_state_.IsActive(); + bool was_active = current_frame_host()->IsActiveUserActivation(); for (FrameTreeNode* node : frame_tree()->Nodes()) { - node->user_activation_state_.ConsumeIfActive(); + node->current_frame_host()->ConsumeTransientUserActivation(); } current_frame_host()->browsing_context_state()->set_has_active_user_gesture( false); @@ -732,7 +732,7 @@ bool FrameTreeNode::ClearUserActivation() { for (FrameTreeNode* node : frame_tree()->SubtreeNodes(this)) - node->user_activation_state_.Clear(); + node->current_frame_host()->ClearUserActivation(); current_frame_host()->browsing_context_state()->set_has_active_user_gesture( false); return true;
diff --git a/content/browser/renderer_host/frame_tree_node.h b/content/browser/renderer_host/frame_tree_node.h index 512fff9..8a3ba8a 100644 --- a/content/browser/renderer_host/frame_tree_node.h +++ b/content/browser/renderer_host/frame_tree_node.h
@@ -26,7 +26,6 @@ #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/public/common/frame/frame_owner_element_type.h" #include "third_party/blink/public/common/frame/frame_policy.h" -#include "third_party/blink/public/common/frame/user_activation_state.h" #include "third_party/blink/public/mojom/frame/frame_owner_properties.mojom.h" #include "third_party/blink/public/mojom/frame/frame_replication_state.mojom-forward.h" #include "third_party/blink/public/mojom/frame/tree_scope_type.mojom.h" @@ -365,18 +364,6 @@ // FrameTreeNode. void BeforeUnloadCanceled(); - // Updates the user activation state in the browser frame tree and in the - // frame trees in all renderer processes except the renderer for this node - // (which initiated the update). Returns |false| if the update tries to - // consume an already consumed/expired transient state, |true| otherwise. See - // the comment on user_activation_state_ below. - // - // The |notification_type| parameter is used for histograms, only for the case - // |update_state == kNotifyActivation|. - bool UpdateUserActivationState( - blink::mojom::UserActivationUpdateType update_type, - blink::mojom::UserActivationNotificationType notification_type); - // Returns the sandbox flags currently in effect for this frame. This includes // flags inherited from parent frames, the currently active flags from the // <iframe> element hosting this frame, as well as any flags set from a @@ -405,16 +392,18 @@ void set_was_discarded() { was_discarded_ = true; } bool was_discarded() const { return was_discarded_; } + // Deprecated. Use directly HasStickyUserActivation in RFHI. // Returns the sticky bit of the User Activation v2 state of the // |FrameTreeNode|. bool HasStickyUserActivation() const { - return user_activation_state_.HasBeenActive(); + return current_frame_host()->HasStickyUserActivation(); } + // Deprecated. Use directly HasStickyUserActivation in RFHI. // Returns the transient bit of the User Activation v2 state of the // |FrameTreeNode|. bool HasTransientUserActivation() { - return user_activation_state_.IsActive(); + return current_frame_host()->HasTransientUserActivation(); } // Remove history entries for all frames created by script in this frame's @@ -604,6 +593,18 @@ Navigator& GetCurrentNavigator() override; void SetFocusedFrame(SiteInstanceGroup* source) override; + // Updates the user activation state in the browser frame tree and in the + // frame trees in all renderer processes except the renderer for this node + // (which initiated the update). Returns |false| if the update tries to + // consume an already consumed/expired transient state, |true| otherwise. See + // the comment on `user_activation_state_` in RenderFrameHostImpl. + // + // The |notification_type| parameter is used for histograms, only for the case + // |update_state == kNotifyActivation|. + bool UpdateUserActivationState( + blink::mojom::UserActivationUpdateType update_type, + blink::mojom::UserActivationNotificationType notification_type) override; + private: friend class CSPEmbeddedEnforcementUnitTest; FRIEND_TEST_ALL_PREFIXES(SitePerProcessPermissionsPolicyBrowserTest, @@ -750,10 +751,6 @@ bool was_discarded_ = false; - // The user activation state of the current frame. See |UserActivationState| - // for details on how this state is maintained. - blink::UserActivationState user_activation_state_; - const FencedFrameStatus fenced_frame_status_ = FencedFrameStatus::kNotNestedInFencedFrame;
diff --git a/content/browser/renderer_host/media/media_resource_provider_fuchsia.cc b/content/browser/renderer_host/media/fuchsia_media_cdm_provider_impl.cc similarity index 66% rename from content/browser/renderer_host/media/media_resource_provider_fuchsia.cc rename to content/browser/renderer_host/media/fuchsia_media_cdm_provider_impl.cc index 9f60a19..4dd00ba 100644 --- a/content/browser/renderer_host/media/media_resource_provider_fuchsia.cc +++ b/content/browser/renderer_host/media/fuchsia_media_cdm_provider_impl.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "content/browser/renderer_host/media/media_resource_provider_fuchsia.h" +#include "content/browser/renderer_host/media/fuchsia_media_cdm_provider_impl.h" #include <fuchsia/mediacodec/cpp/fidl.h> #include <lib/sys/cpp/component_context.h> @@ -16,22 +16,21 @@ namespace content { // static -void MediaResourceProviderFuchsia::Bind( - content::RenderFrameHost* frame_host, - mojo::PendingReceiver<media::mojom::FuchsiaMediaResourceProvider> - receiver) { +void FuchsiaMediaCdmProviderImpl::Bind( + RenderFrameHost* frame_host, + mojo::PendingReceiver<media::mojom::FuchsiaMediaCdmProvider> receiver) { CHECK(frame_host); // The object will delete itself when connection to the frame is broken. - new MediaResourceProviderFuchsia(*frame_host, std::move(receiver)); + new FuchsiaMediaCdmProviderImpl(*frame_host, std::move(receiver)); } -MediaResourceProviderFuchsia::MediaResourceProviderFuchsia( - content::RenderFrameHost& render_frame_host, - mojo::PendingReceiver<media::mojom::FuchsiaMediaResourceProvider> receiver) +FuchsiaMediaCdmProviderImpl::FuchsiaMediaCdmProviderImpl( + RenderFrameHost& render_frame_host, + mojo::PendingReceiver<media::mojom::FuchsiaMediaCdmProvider> receiver) : DocumentService(render_frame_host, std::move(receiver)) {} -MediaResourceProviderFuchsia::~MediaResourceProviderFuchsia() = default; +FuchsiaMediaCdmProviderImpl::~FuchsiaMediaCdmProviderImpl() = default; -void MediaResourceProviderFuchsia::CreateCdm( +void FuchsiaMediaCdmProviderImpl::CreateCdm( const std::string& key_system, fidl::InterfaceRequest<fuchsia::media::drm::ContentDecryptionModule> request) { @@ -48,7 +47,7 @@ ->GetURLLoaderFactoryForBrowserProcess(); media::CreateFetcherCB create_fetcher_cb = base::BindRepeating( - &content::CreateProvisionFetcher, std::move(url_loader_factory)); + &CreateProvisionFetcher, std::move(url_loader_factory)); cdm_manager->CreateAndProvision( key_system, origin(), std::move(create_fetcher_cb), std::move(request)); }
diff --git a/content/browser/renderer_host/media/fuchsia_media_cdm_provider_impl.h b/content/browser/renderer_host/media/fuchsia_media_cdm_provider_impl.h new file mode 100644 index 0000000..092c521 --- /dev/null +++ b/content/browser/renderer_host/media/fuchsia_media_cdm_provider_impl.h
@@ -0,0 +1,45 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_BROWSER_RENDERER_HOST_MEDIA_FUCHSIA_MEDIA_CDM_PROVIDER_IMPL_H_ +#define CONTENT_BROWSER_RENDERER_HOST_MEDIA_FUCHSIA_MEDIA_CDM_PROVIDER_IMPL_H_ + +#include "content/public/browser/document_service.h" +#include "media/fuchsia/mojom/fuchsia_media.mojom.h" + +namespace content { + +// Implements media::mojom::FuchsiaMediaCdmProvider by calling out to the +// fuchsia::media::drm::ContentDecryptionModule APIs. +// +// It helps renderer frame to create CDM. +class FuchsiaMediaCdmProviderImpl final + : public DocumentService<media::mojom::FuchsiaMediaCdmProvider> { + public: + ~FuchsiaMediaCdmProviderImpl() override; + + FuchsiaMediaCdmProviderImpl(const FuchsiaMediaCdmProviderImpl&) = delete; + FuchsiaMediaCdmProviderImpl& operator=(const FuchsiaMediaCdmProviderImpl&) = + delete; + + // Used to make this service available in the BinderMap. + static void Bind( + RenderFrameHost* frame_host, + mojo::PendingReceiver<media::mojom::FuchsiaMediaCdmProvider> receiver); + + private: + FuchsiaMediaCdmProviderImpl( + RenderFrameHost& render_frame_host, + mojo::PendingReceiver<media::mojom::FuchsiaMediaCdmProvider> receiver); + + // media::mojom::FuchsiaMediaCdmProvider implementation. + void CreateCdm( + const std::string& key_system, + fidl::InterfaceRequest<fuchsia::media::drm::ContentDecryptionModule> + request) override; +}; + +} // namespace content + +#endif // CONTENT_BROWSER_RENDERER_HOST_MEDIA_FUCHSIA_MEDIA_CDM_PROVIDER_IMPL_H_
diff --git a/content/browser/renderer_host/media/fuchsia_media_codec_provider_impl.h b/content/browser/renderer_host/media/fuchsia_media_codec_provider_impl.h index c728ed3a..e9456e1 100644 --- a/content/browser/renderer_host/media/fuchsia_media_codec_provider_impl.h +++ b/content/browser/renderer_host/media/fuchsia_media_codec_provider_impl.h
@@ -9,7 +9,7 @@ #include "base/threading/thread_checker.h" #include "content/common/content_export.h" -#include "media/fuchsia/mojom/fuchsia_media_resource_provider.mojom.h" +#include "media/fuchsia/mojom/fuchsia_media.mojom.h" #include "mojo/public/cpp/bindings/receiver_set.h" #include "third_party/abseil-cpp/absl/types/optional.h"
diff --git a/content/browser/renderer_host/media/media_resource_provider_fuchsia.h b/content/browser/renderer_host/media/media_resource_provider_fuchsia.h deleted file mode 100644 index 55bd4c7..0000000 --- a/content/browser/renderer_host/media/media_resource_provider_fuchsia.h +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_BROWSER_RENDERER_HOST_MEDIA_MEDIA_RESOURCE_PROVIDER_FUCHSIA_H_ -#define CONTENT_BROWSER_RENDERER_HOST_MEDIA_MEDIA_RESOURCE_PROVIDER_FUCHSIA_H_ - -#include "content/public/browser/document_service.h" -#include "media/fuchsia/mojom/fuchsia_media_resource_provider.mojom.h" - -namespace content { - -class MediaResourceProviderFuchsia final - : public content::DocumentService< - media::mojom::FuchsiaMediaResourceProvider> { - public: - ~MediaResourceProviderFuchsia() final; - - MediaResourceProviderFuchsia(const MediaResourceProviderFuchsia&) = delete; - MediaResourceProviderFuchsia& operator=(const MediaResourceProviderFuchsia&) = - delete; - - static void Bind( - content::RenderFrameHost* frame_host, - mojo::PendingReceiver<media::mojom::FuchsiaMediaResourceProvider> - receiver); - - private: - MediaResourceProviderFuchsia( - content::RenderFrameHost& render_frame_host, - mojo::PendingReceiver<media::mojom::FuchsiaMediaResourceProvider> - receiver); - - // media::mojom::FuchsiaMediaResourceProvider implementation. - void CreateCdm( - const std::string& key_system, - fidl::InterfaceRequest<fuchsia::media::drm::ContentDecryptionModule> - request) final; -}; - -} // namespace content - -#endif // CONTENT_BROWSER_RENDERER_HOST_MEDIA_MEDIA_RESOURCE_PROVIDER_FUCHSIA_H_
diff --git a/content/browser/renderer_host/navigator.cc b/content/browser/renderer_host/navigator.cc index 2afb5010..327cec2 100644 --- a/content/browser/renderer_host/navigator.cc +++ b/content/browser/renderer_host/navigator.cc
@@ -483,6 +483,11 @@ base::WeakPtr<RenderFrameHostImpl> old_frame_host = frame_tree_node->render_manager()->current_frame_host()->GetWeakPtr(); + // Save the activation status of the previous page here before it gets reset + // in FrameTreeNode::ResetForNavigation. + bool previous_document_was_activated = + frame_tree->root()->HasStickyUserActivation(); + if (auto& old_page_info = navigation_request->commit_params().old_page_info) { // This is a same-site main-frame navigation where we did a proactive // BrowsingInstance swap but we're reusing the old page's process, and we @@ -528,11 +533,6 @@ render_frame_host->browsing_context_state()->SetInsecureNavigationsSet( params.insecure_navigations_set); - // Save the activation status of the previous page here before it gets reset - // in FrameTreeNode::ResetForNavigation. - bool previous_document_was_activated = - frame_tree->root()->HasStickyUserActivation(); - if (!was_within_same_document) { // Navigating to a new location means a new, fresh set of http headers // and/or <meta> elements - we need to reset Permissions Policy.
diff --git a/content/browser/renderer_host/render_frame_host_impl.cc b/content/browser/renderer_host/render_frame_host_impl.cc index 99f13a94..c230790e 100644 --- a/content/browser/renderer_host/render_frame_host_impl.cc +++ b/content/browser/renderer_host/render_frame_host_impl.cc
@@ -1054,7 +1054,7 @@ // User activation is required, because fenced frames use the sandbox // flag `allow-top-navigation-by-user-activation`. // It would be better to instead check - // `render_frame_host->frame_tree_node()->HasTransientUserActivation()`, + // `render_frame_host->HasTransientUserActivation()`, // but it has already been consumed at this point. // TODO(crbug.com/848778): use the browser's source of truth for user // activation here (and elsewhere in this file) rather than trust the @@ -2566,11 +2566,11 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); AssertNonSpeculativeFrame(); - if (has_user_gesture) { + if (has_user_gesture && owner_) { // TODO(mustaq): The render-to-browser state update caused by the below // JavaScriptExecuteRequestsForTests call is redundant with this update. We // should determine if the redundancy can be removed. - frame_tree_node()->UpdateUserActivationState( + owner_->UpdateUserActivationState( blink::mojom::UserActivationUpdateType::kNotifyActivation, blink::mojom::UserActivationNotificationType::kTest); } @@ -5763,7 +5763,7 @@ } bool RenderFrameHostImpl::HasTransientUserActivation() { - return frame_tree_node_->HasTransientUserActivation(); + return user_activation_state_.IsActive(); } void RenderFrameHostImpl::NotifyUserActivation( @@ -6456,6 +6456,13 @@ EnterFullscreenCallback callback) { const bool had_fullscreen_token = fullscreen_request_token_.IsActive(); + // Frames (possibly a subframe) that are not active nor belonging to a primary + // page should not enter fullscreen. + if (!IsActive() || !GetPage().IsPrimary()) { + std::move(callback).Run(/*granted=*/false); + return; + } + // Entering fullscreen requires a transient user activation, a fullscreen // capability delegation token, a user-generated screen orientation change, or // another feature-specific transient allowance. @@ -6470,10 +6477,10 @@ // Reject requests made without transient user activation or a token. // TODO(lanwei): Investigate whether we can terminate the renderer when // transient user activation and the delegated token are both inactive. - const bool consumed_activation = - frame_tree_node_->UpdateUserActivationState( - blink::mojom::UserActivationUpdateType::kConsumeTransientActivation, - blink::mojom::UserActivationNotificationType::kNone); + CHECK(owner_); + const bool consumed_activation = owner_->UpdateUserActivationState( + blink::mojom::UserActivationUpdateType::kConsumeTransientActivation, + blink::mojom::UserActivationNotificationType::kNone); const bool consumed_token = fullscreen_request_token_.ConsumeIfActive(); if (!consumed_activation && !consumed_token) { DLOG(ERROR) << "Cannot enter fullscreen because there is no transient " @@ -6484,10 +6491,7 @@ } } - // Frames (possibly a subframe) that are not active nor belonging to a primary - // page should not enter fullscreen. - if (!IsActive() || !GetPage().IsPrimary() || - !delegate_->CanEnterFullscreenMode(this, *options)) { + if (!delegate_->CanEnterFullscreenMode(this, *options)) { std::move(callback).Run(/*granted=*/false); return; } @@ -6705,7 +6709,8 @@ if (lifecycle_state() != LifecycleStateImpl::kActive) return; - frame_tree_node_->UpdateUserActivationState(update_type, notification_type); + CHECK(owner_); + owner_->UpdateUserActivationState(update_type, notification_type); } void RenderFrameHostImpl::HadStickyUserActivationBeforeNavigationChanged( @@ -7241,7 +7246,7 @@ GetProcess()->FilterURL(false, ¶ms->target_url); bool effective_transient_activation_state = - params->allow_popup || frame_tree_node_->HasTransientUserActivation() || + params->allow_popup || HasTransientUserActivation() || (transient_allow_popup_.IsActive() && params->disposition == WindowOpenDisposition::NEW_POPUP); @@ -7271,7 +7276,8 @@ // NB: This call will consume activations in the browser and the remote frame // proxies for this frame. The initiating renderer will consume its view of // the activations after we return. - bool was_consumed = frame_tree_node_->UpdateUserActivationState( + CHECK(owner_); + bool was_consumed = owner_->UpdateUserActivationState( blink::mojom::UserActivationUpdateType::kConsumeTransientActivation, blink::mojom::UserActivationNotificationType::kNone); @@ -11683,14 +11689,9 @@ // early post-crash CommitPending() call. committed_speculative_rfh_before_navigation_commit_ = false; - // TODO(arthursonzogni): Updating this flag for same-document, bfcache, or - // prerender navigation doesn't seem right. This should likely be executed in - // DidCommitNewDocument(). - if (IsBackForwardCacheEnabled() || blink::features::IsPrerender2Enabled()) { - // Store the Commit params so they can be reused if the page is ever - // restored from the BackForwardCache. - last_commit_params_ = std::move(params); - } + // Store the Commit params so they can be reused if the page is ever + // restored from the BackForwardCache or a Prerender2 page is activated. + last_commit_params_ = std::move(params); return true; }
diff --git a/content/browser/renderer_host/render_frame_host_impl.h b/content/browser/renderer_host/render_frame_host_impl.h index 340c9e0..c5310b10 100644 --- a/content/browser/renderer_host/render_frame_host_impl.h +++ b/content/browser/renderer_host/render_frame_host_impl.h
@@ -108,6 +108,7 @@ #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" #include "third_party/blink/public/common/frame/frame_owner_element_type.h" #include "third_party/blink/public/common/frame/fullscreen_request_token.h" +#include "third_party/blink/public/common/frame/user_activation_state.h" #include "third_party/blink/public/common/permissions_policy/permissions_policy.h" #include "third_party/blink/public/common/permissions_policy/permissions_policy_declaration.h" #include "third_party/blink/public/common/scheduler/web_scheduler_tracked_feature.h" @@ -2742,6 +2743,26 @@ RenderFrameHostImplPpapiSupport& GetPpapiSupport(); #endif + // Returns the sticky bit of the User Activation v2 state of this document. + bool HasStickyUserActivation() const { + return user_activation_state_.HasBeenActive(); + } + + bool IsActiveUserActivation() const { + return user_activation_state_.IsActive(); + } + + void ClearUserActivation() { user_activation_state_.Clear(); } + + void ConsumeTransientUserActivation() { + user_activation_state_.ConsumeIfActive(); + } + + void ActivateUserActivation( + blink::mojom::UserActivationNotificationType notification_type) { + user_activation_state_.Activate(notification_type); + } + protected: friend class RenderFrameHostFactory; @@ -3847,7 +3868,7 @@ // `has_user_gesture` is true or not. Note that this is just the cached value // of what happened during the last navigation, and does not reflect the // user activation state of this RenderFrameHost. To get the current/live user - // activation state, get the value from FrameTreeNode's + // activation state, get the value from RenderFrameHostImpl's // HasStickyUserActivation() or HasTransientUserActivation() instead. bool last_navigation_started_with_transient_activation_ = false; @@ -4618,6 +4639,10 @@ // Manages a transient affordance for this frame to request fullscreen. blink::FullscreenRequestToken fullscreen_request_token_; + // The user activation state of this document. See |UserActivationState| for + // details on how this state is maintained. + blink::UserActivationState user_activation_state_; + // Used to avoid sending AXTreeData to the renderer if the renderer has not // been told root ID yet. See UpdateAXTreeData() for more details. bool needs_ax_root_id_ = true;
diff --git a/content/browser/renderer_host/render_frame_host_owner.h b/content/browser/renderer_host/render_frame_host_owner.h index 5278952..cc69d172 100644 --- a/content/browser/renderer_host/render_frame_host_owner.h +++ b/content/browser/renderer_host/render_frame_host_owner.h
@@ -5,6 +5,8 @@ #ifndef CONTENT_BROWSER_RENDERER_HOST_RENDER_FRAME_HOST_OWNER_H_ #define CONTENT_BROWSER_RENDERER_HOST_RENDER_FRAME_HOST_OWNER_H_ +#include "third_party/blink/public/mojom/frame/user_activation_update_types.mojom-forward.h" + namespace content { class NavigationRequest; @@ -33,6 +35,10 @@ virtual Navigator& GetCurrentNavigator() = 0; virtual void SetFocusedFrame(SiteInstanceGroup* source) = 0; + + virtual bool UpdateUserActivationState( + blink::mojom::UserActivationUpdateType update_type, + blink::mojom::UserActivationNotificationType notification_type) = 0; }; } // namespace content
diff --git a/content/browser/resources/media/client_renderer.js b/content/browser/resources/media/client_renderer.js index 44f459e..9e0acaaa 100644 --- a/content/browser/resources/media/client_renderer.js +++ b/content/browser/resources/media/client_renderer.js
@@ -2,7 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import {$} from 'chrome://resources/js/util.js'; +import {$} from 'chrome://resources/js/util_ts.js'; + import {millisecondsToString} from './util.js'; /**
diff --git a/content/browser/resources/media/manager.js b/content/browser/resources/media/manager.js index fbd72e7b..8c50866 100644 --- a/content/browser/resources/media/manager.js +++ b/content/browser/resources/media/manager.js
@@ -2,7 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import {$} from 'chrome://resources/js/util.js'; +import {$} from 'chrome://resources/js/util_ts.js'; + import {PlayerInfo} from './player_info.js'; import {objectForEach} from './util.js';
diff --git a/content/browser/resources/net/network_errors_listing.js b/content/browser/resources/net/network_errors_listing.js index 83768e42..77d9b56 100644 --- a/content/browser/resources/net/network_errors_listing.js +++ b/content/browser/resources/net/network_errors_listing.js
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import {$} from 'chrome://resources/js/util.js'; +import {$} from 'chrome://resources/js/util_ts.js'; /** * Generate the page content.
diff --git a/content/browser/resources/service_worker/serviceworker_internals.js b/content/browser/resources/service_worker/serviceworker_internals.js index 2b4b1cb..ab98a1d 100644 --- a/content/browser/resources/service_worker/serviceworker_internals.js +++ b/content/browser/resources/service_worker/serviceworker_internals.js
@@ -5,7 +5,7 @@ import 'chrome://resources/js/jstemplate_compiled.js'; import {addWebUiListener, sendWithPromise} from 'chrome://resources/js/cr.js'; -import {$} from 'chrome://resources/js/util.js'; +import {$} from 'chrome://resources/js/util_ts.js'; function initialize() { addWebUiListener('partition-data', onPartitionData);
diff --git a/content/browser/tracing/startup_tracing_browsertest.cc b/content/browser/tracing/startup_tracing_browsertest.cc index eebb529..bec57f0 100644 --- a/content/browser/tracing/startup_tracing_browsertest.cc +++ b/content/browser/tracing/startup_tracing_browsertest.cc
@@ -322,7 +322,7 @@ OutputLocation::kDirectoryWithDefaultBasename, OutputLocation::kDirectoryWithBasenameUpdatedBeforeStop))); -IN_PROC_BROWSER_TEST_P(StartupTracingTest, TestEnableTracing) { +IN_PROC_BROWSER_TEST_P(StartupTracingTest, DISABLED_TestEnableTracing) { EXPECT_TRUE(NavigateToURL(shell(), GetTestUrl("", "title1.html"))); if (GetOutputLocation() == @@ -354,14 +354,14 @@ testing::Values(OutputType::kJSON, OutputType::kProto), testing::Values(OutputLocation::kDirectoryWithDefaultBasename))); -IN_PROC_BROWSER_TEST_P(EmergencyStopTracingTest, StopOnUIThread) { +IN_PROC_BROWSER_TEST_P(EmergencyStopTracingTest, DISABLED_StopOnUIThread) { EXPECT_TRUE(NavigateToURL(shell(), GetTestUrl("", "title1.html"))); StartupTracingController::EmergencyStop(); CheckOutput(GetExpectedPath(), GetOutputType()); } -IN_PROC_BROWSER_TEST_P(EmergencyStopTracingTest, StopOnThreadPool) { +IN_PROC_BROWSER_TEST_P(EmergencyStopTracingTest, DISABLED_StopOnThreadPool) { EXPECT_TRUE(NavigateToURL(shell(), GetTestUrl("", "title1.html"))); auto expected_path = GetExpectedPath(); @@ -378,7 +378,8 @@ run_loop.Run(); } -IN_PROC_BROWSER_TEST_P(EmergencyStopTracingTest, StopOnThreadPoolTwice) { +IN_PROC_BROWSER_TEST_P(EmergencyStopTracingTest, + DISABLED_StopOnThreadPoolTwice) { EXPECT_TRUE(NavigateToURL(shell(), GetTestUrl("", "title1.html"))); auto expected_path = GetExpectedPath();
diff --git a/content/public/android/BUILD.gn b/content/public/android/BUILD.gn index 91b876e..0e185dc 100644 --- a/content/public/android/BUILD.gn +++ b/content/public/android/BUILD.gn
@@ -180,6 +180,7 @@ "//third_party/blink/public/mojom:android_mojo_bindings_java", "//third_party/blink/public/mojom:mojom_core_java", "//third_party/blink/public/mojom:mojom_platform_java", + "//ui/accessibility:ax_base_java", "//ui/android:ui_no_recycler_view_java", "//ui/android:ui_utils_java", "//ui/base/ime/mojom:mojom_java", @@ -243,7 +244,6 @@ "java/src/org/chromium/content/browser/accessibility/AccessibilityEventDispatcher.java", "java/src/org/chromium/content/browser/accessibility/AccessibilityHistogramRecorder.java", "java/src/org/chromium/content/browser/accessibility/AccessibilityNodeInfoUtils.java", - "java/src/org/chromium/content/browser/accessibility/BrowserAccessibilityState.java", "java/src/org/chromium/content/browser/accessibility/OViewStructureBuilder.java", "java/src/org/chromium/content/browser/accessibility/ViewStructureBuilder.java", "java/src/org/chromium/content/browser/accessibility/WebContentsAccessibilityDelegate.java", @@ -450,7 +450,6 @@ "java/src/org/chromium/content/browser/SyntheticGestureTarget.java", "java/src/org/chromium/content/browser/TracingControllerAndroidImpl.java", "java/src/org/chromium/content/browser/TtsPlatformImpl.java", - "java/src/org/chromium/content/browser/accessibility/BrowserAccessibilityState.java", "java/src/org/chromium/content/browser/accessibility/ViewStructureBuilder.java", "java/src/org/chromium/content/browser/accessibility/WebContentsAccessibilityImpl.java", "java/src/org/chromium/content/browser/accessibility/captioning/CaptioningController.java",
diff --git a/content/public/android/java/src/org/chromium/content/browser/accessibility/AccessibilityAutofillHelper.java b/content/public/android/java/src/org/chromium/content/browser/accessibility/AccessibilityAutofillHelper.java index a380ba7..00ceb46 100644 --- a/content/public/android/java/src/org/chromium/content/browser/accessibility/AccessibilityAutofillHelper.java +++ b/content/public/android/java/src/org/chromium/content/browser/accessibility/AccessibilityAutofillHelper.java
@@ -6,6 +6,8 @@ import android.os.Build; +import org.chromium.ui.accessibility.AccessibilityState; + /** * Helper class for Autofill state and password preferences for accessibility related code. */ @@ -36,10 +38,10 @@ // When additional services are running besides Autofill, we fall back to checking the // user's system preference. The preference to check varies by OS version. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - return BrowserAccessibilityState.hasEnabledTextShowPassword(); + return AccessibilityState.hasEnabledTextShowPassword(); } - return BrowserAccessibilityState.hasEnabledAccessibilitySpeakPassword(); + return AccessibilityState.hasEnabledAccessibilitySpeakPassword(); } public static boolean isAutofillOnlyPossibleAccessibilityConsumer() { @@ -57,7 +59,7 @@ // // https://cs.android.com/android/platform/superproject/+/HEAD:frameworks/base/core/java/android/view/autofill/AutofillManager.java;l=2817;drc=dd7d52f9632a0dbb8b14b69520c5ea31e0b3b4a2 - // Use the BrowserAccessibilityState to verify if >= 1 service(s) is/are running. - return !BrowserAccessibilityState.hasAnyAccessibilityServiceEnabled(); + // Use the AccessibilityState to verify if >= 1 service(s) is/are running. + return !AccessibilityState.hasAnyAccessibilityServiceEnabled(); } } \ No newline at end of file
diff --git a/content/public/android/java/src/org/chromium/content/browser/accessibility/AccessibilityHistogramRecorder.java b/content/public/android/java/src/org/chromium/content/browser/accessibility/AccessibilityHistogramRecorder.java index 9af1042..8548e8b 100644 --- a/content/public/android/java/src/org/chromium/content/browser/accessibility/AccessibilityHistogramRecorder.java +++ b/content/public/android/java/src/org/chromium/content/browser/accessibility/AccessibilityHistogramRecorder.java
@@ -8,6 +8,7 @@ import org.chromium.base.metrics.RecordHistogram; import org.chromium.content_public.browser.ContentFeatureList; +import org.chromium.ui.accessibility.AccessibilityState; /** * Helper class for recording UMA histograms of accessibility events @@ -123,7 +124,7 @@ boolean isComputeAXModeEnabled = ContentFeatureList.isEnabled(ContentFeatureList.COMPUTE_AX_MODE); // There are only 2 AXModes, kAXModeComplete is used when a screenreader is active. - boolean isAXModeComplete = BrowserAccessibilityState.screenReaderMode(); + boolean isAXModeComplete = AccessibilityState.screenReaderMode(); // If we did not enqueue any events, we can ignore the data as a trivial case. if (mTotalEnqueuedEvents > 0) {
diff --git a/content/public/android/java/src/org/chromium/content/browser/accessibility/WebContentsAccessibilityImpl.java b/content/public/android/java/src/org/chromium/content/browser/accessibility/WebContentsAccessibilityImpl.java index 1256a97..749d295b 100644 --- a/content/public/android/java/src/org/chromium/content/browser/accessibility/WebContentsAccessibilityImpl.java +++ b/content/public/android/java/src/org/chromium/content/browser/accessibility/WebContentsAccessibilityImpl.java
@@ -95,6 +95,7 @@ import org.chromium.content_public.browser.ContentFeatureList; import org.chromium.content_public.browser.WebContents; import org.chromium.content_public.browser.WebContentsAccessibility; +import org.chromium.ui.accessibility.AccessibilityState; import org.chromium.ui.base.ViewAndroidDelegate; import org.chromium.ui.base.WindowAndroid; @@ -120,11 +121,9 @@ @JNINamespace("content") public class WebContentsAccessibilityImpl extends AccessibilityNodeProviderCompat implements AccessibilityStateChangeListener, WebContentsAccessibility, WindowEventObserver, - UserData, BrowserAccessibilityState.Listener, + UserData, AccessibilityState.Listener, ViewAndroidDelegate.ContainerViewObserver { - // Public catch-all TAG for logging in the accessibility component. - public static final String TAG = "ClankAccessibility"; - + private static final String TAG = "A11yImpl"; // The following constants have been hard coded so we can support actions newer than our // minimum SDK without having to break methods into a series of subclasses. // TODO(mschillaci): Remove these once they are added to the AccessibilityNodeInfoCompat class. @@ -306,7 +305,7 @@ moveAccessibilityFocusToIdAndRefocusIfNeeded(mAccessibilityFocusId); }); - BrowserAccessibilityState.addListener(this); + AccessibilityState.addListener(this); // Define our delays on a per event type basis. Map<Integer, Integer> eventThrottleDelays = new HashMap<Integer, Integer>(); @@ -422,8 +421,7 @@ // Define a set of relevant AccessibilityEvents if the OnDemand feature is enabled. if (ContentFeatureList.isEnabled(ContentFeatureList.ON_DEMAND_ACCESSIBILITY_EVENTS)) { Runnable serviceMaskRunnable = () -> { - int serviceEventMask = - BrowserAccessibilityState.getAccessibilityServiceEventTypeMask(); + int serviceEventMask = AccessibilityState.getAccessibilityServiceEventTypeMask(); mEventDispatcher.updateRelevantEventTypes( convertMaskToEventTypes(serviceEventMask)); mEventDispatcher.setOnDemandEnabled(true); @@ -460,7 +458,7 @@ @VisibleForTesting @Override public void setBrowserAccessibilityStateForTesting() { - BrowserAccessibilityState.setEventTypeMaskForTesting(); + AccessibilityState.setEventTypeMaskForTesting(); } @VisibleForTesting @@ -504,12 +502,12 @@ @VisibleForTesting public void setEventTypeMaskEmptyForTesting() { - BrowserAccessibilityState.setEventTypeMaskEmptyForTesting(); + AccessibilityState.setEventTypeMaskEmptyForTesting(); } @VisibleForTesting public void setScreenReaderModeForTesting(boolean enabled) { - BrowserAccessibilityState.setScreenReaderModeForTesting(enabled); + AccessibilityState.setScreenReaderModeForTesting(enabled); } @CalledByNative @@ -622,7 +620,7 @@ // Update the AXMode based on screen reader status. WebContentsAccessibilityImplJni.get().setAXMode(mNativeObj, - BrowserAccessibilityState.screenReaderMode(), + AccessibilityState.screenReaderMode(), /* isAccessibilityEnabled= */ true); // Update the state of how passwords are exposed based on user settings. @@ -633,7 +631,7 @@ // Update the state of enabling/disabling the image descriptions feature. To enable the // feature, this instance must be a candidate and a screen reader must be enabled. WebContentsAccessibilityImplJni.get().setAllowImageDescriptions(mNativeObj, - mIsImageDescriptionsCandidate && BrowserAccessibilityState.screenReaderMode()); + mIsImageDescriptionsCandidate && AccessibilityState.screenReaderMode()); } } @@ -670,7 +668,7 @@ onNativeInit(); } if (!isEnabled()) { - boolean screenReaderMode = BrowserAccessibilityState.screenReaderMode(); + boolean screenReaderMode = AccessibilityState.screenReaderMode(); WebContentsAccessibilityImplJni.get().enable(mNativeObj, screenReaderMode); return null; } @@ -824,7 +822,7 @@ if (isNativeInitialized() && ContentFeatureList.isEnabled( ContentFeatureList.ON_DEMAND_ACCESSIBILITY_EVENTS)) { - int serviceEventMask = BrowserAccessibilityState.getAccessibilityServiceEventTypeMask(); + int serviceEventMask = AccessibilityState.getAccessibilityServiceEventTypeMask(); mEventDispatcher.updateRelevantEventTypes(convertMaskToEventTypes(serviceEventMask)); } } @@ -1124,7 +1122,7 @@ if (!isNativeInitialized()) return; // Update the AXMode based on screen reader status. WebContentsAccessibilityImplJni.get().setAXMode( - mNativeObj, BrowserAccessibilityState.screenReaderMode(), isAccessibilityEnabled()); + mNativeObj, AccessibilityState.screenReaderMode(), isAccessibilityEnabled()); } // Returns true if the hover event is to be consumed by accessibility feature.
diff --git a/content/public/browser/BUILD.gn b/content/public/browser/BUILD.gn index f2beaef..02d2c384 100644 --- a/content/public/browser/BUILD.gn +++ b/content/public/browser/BUILD.gn
@@ -598,7 +598,7 @@ if (is_fuchsia) { sources += [ "ax_inspect_factory_fuchsia.cc" ] - deps += [ "//media/fuchsia/mojom:fuchsia_media_resource_provider" ] + deps += [ "//media/fuchsia/mojom:fuchsia_media" ] } if (is_win) {
diff --git a/content/public/browser/render_process_host.h b/content/public/browser/render_process_host.h index d23c5cc..3d00d0c0 100644 --- a/content/public/browser/render_process_host.h +++ b/content/public/browser/render_process_host.h
@@ -59,7 +59,7 @@ #endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) #if BUILDFLAG(IS_FUCHSIA) -#include "media/fuchsia/mojom/fuchsia_media_resource_provider.mojom-forward.h" +#include "media/fuchsia/mojom/fuchsia_media.mojom-forward.h" #endif class GURL;
diff --git a/dbus/values_util.cc b/dbus/values_util.cc index 47e4a20..b34595e8 100644 --- a/dbus/values_util.cc +++ b/dbus/values_util.cc
@@ -24,21 +24,19 @@ } // Pops values from |reader| and appends them to |list_value|. -bool PopListElements(MessageReader* reader, base::Value* list_value) { - DCHECK(list_value->is_list()); +bool PopListElements(MessageReader* reader, base::Value::List& list_value) { while (reader->HasMoreData()) { base::Value element_value = PopDataAsValue(reader); if (element_value.is_none()) return false; - list_value->Append(std::move(element_value)); + list_value.Append(std::move(element_value)); } return true; } // Pops dict-entries from |reader| and sets them to |dictionary_value| bool PopDictionaryEntries(MessageReader* reader, - base::Value* dictionary_value) { - DCHECK(dictionary_value->is_dict()); + base::Value::Dict& dictionary_value) { while (reader->HasMoreData()) { DCHECK_EQ(Message::DICT_ENTRY, reader->GetDataType()); MessageReader entry_reader(nullptr); @@ -62,7 +60,7 @@ base::Value value = PopDataAsValue(&entry_reader); if (value.is_none()) return false; - dictionary_value->SetKey(key_string, std::move(value)); + dictionary_value.Set(key_string, std::move(value)); } return true; } @@ -185,13 +183,13 @@ // Value with type base::Value::Type::DICTIONARY, otherwise create a // Value with type base::Value::Type::LIST. if (sub_reader.GetDataType() == Message::DICT_ENTRY) { - auto dictionary_value = base::Value(base::Value::Type::DICTIONARY); - if (PopDictionaryEntries(&sub_reader, &dictionary_value)) - result = std::move(dictionary_value); + base::Value::Dict dictionary_value; + if (PopDictionaryEntries(&sub_reader, dictionary_value)) + result = base::Value(std::move(dictionary_value)); } else { - auto list_value = base::Value(base::Value::Type::LIST); - if (PopListElements(&sub_reader, &list_value)) - result = std::move(list_value); + base::Value::List list_value; + if (PopListElements(&sub_reader, list_value)) + result = base::Value(std::move(list_value)); } } break; @@ -199,9 +197,9 @@ case Message::STRUCT: { MessageReader sub_reader(nullptr); if (reader->PopStruct(&sub_reader)) { - auto list_value = base::Value(base::Value::Type::LIST); - if (PopListElements(&sub_reader, &list_value)) - result = std::move(list_value); + base::Value::List list_value; + if (PopListElements(&sub_reader, list_value)) + result = base::Value(std::move(list_value)); } break; }
diff --git a/dbus/values_util_unittest.cc b/dbus/values_util_unittest.cc index 120f124..a94b7d2 100644 --- a/dbus/values_util_unittest.cc +++ b/dbus/values_util_unittest.cc
@@ -175,7 +175,7 @@ writer.CloseContainer(&sub_writer); // Create the expected value. - base::Value list_value(base::Value::Type::LIST); + base::Value::List list_value; for (size_t i = 0; i != data.size(); ++i) list_value.Append(data[i]); @@ -198,7 +198,7 @@ writer.AppendArrayOfStrings(data); // Create the expected value. - base::Value list_value(base::Value::Type::LIST); + base::Value::List list_value; for (size_t i = 0; i != data.size(); ++i) list_value.Append(data[i]); @@ -226,7 +226,7 @@ writer.CloseContainer(&sub_writer); // Create the expected value. - base::Value list_value(base::Value::Type::LIST); + base::Value::List list_value; list_value.Append(kBoolValue); list_value.Append(kInt32Value); list_value.Append(kDoubleValue); @@ -273,11 +273,11 @@ writer.CloseContainer(&sub_writer); // Create the expected value. - base::Value dictionary_value(base::Value::Type::DICTIONARY); - dictionary_value.SetBoolKey(kKey1, kBoolValue); - dictionary_value.SetIntKey(kKey2, kInt32Value); - dictionary_value.SetDoubleKey(kKey3, kDoubleValue); - dictionary_value.SetStringKey(kKey4, kStringValue); + base::Value::Dict dictionary_value; + dictionary_value.Set(kKey1, kBoolValue); + dictionary_value.Set(kKey2, kInt32Value); + dictionary_value.Set(kKey3, kDoubleValue); + dictionary_value.Set(kKey4, kStringValue); // Pop a dictinoary. MessageReader reader(response.get()); @@ -314,10 +314,10 @@ writer.CloseContainer(&sub_writer); // Create the expected value. - base::Value dictionary_value(base::Value::Type::DICTIONARY); - dictionary_value.SetKey(kKey1, base::Value(kBoolValue)); - dictionary_value.SetKey(kKey2, base::Value(kInt32Value)); - dictionary_value.SetKey(kKey3, base::Value(kDoubleValue)); + base::Value::Dict dictionary_value; + dictionary_value.Set(kKey1, kBoolValue); + dictionary_value.Set(kKey2, kInt32Value); + dictionary_value.Set(kKey3, kDoubleValue); // Pop a dictinoary. MessageReader reader(response.get()); @@ -349,11 +349,11 @@ writer.CloseContainer(&sub_writer); // Create the expected value. - base::Value dictionary_value(base::Value::Type::DICTIONARY); + base::Value::Dict dictionary_value; for (size_t i = 0; i != values.size(); ++i) { std::string key_string; base::JSONWriter::Write(base::Value(keys[i]), &key_string); - dictionary_value.SetKey(key_string, base::Value(values[i])); + dictionary_value.Set(key_string, values[i]); } // Pop a dictionary. @@ -493,21 +493,21 @@ const double kDoubleValue = 4.9; const std::string kStringValue = "fifty"; - base::Value list_value(base::Value::Type::LIST); + base::Value::List list_value; list_value.Append(kBoolValue); list_value.Append(kInt32Value); - base::Value dictionary_value(base::Value::Type::DICTIONARY); - dictionary_value.SetBoolKey(kKey1, kBoolValue); - dictionary_value.SetIntKey(kKey2, kDoubleValue); + base::Value::Dict dictionary_value; + dictionary_value.Set(kKey1, kBoolValue); + dictionary_value.Set(kKey2, kDoubleValue); - base::Value test_dictionary(base::Value::Type::DICTIONARY); - test_dictionary.SetBoolKey(kKey1, kBoolValue); - test_dictionary.SetIntKey(kKey2, kInt32Value); - test_dictionary.SetDoubleKey(kKey3, kDoubleValue); - test_dictionary.SetStringKey(kKey4, kStringValue); - test_dictionary.SetKey(kKey5, std::move(list_value)); - test_dictionary.SetKey(kKey6, std::move(dictionary_value)); + base::Value::Dict test_dictionary; + test_dictionary.Set(kKey1, kBoolValue); + test_dictionary.Set(kKey2, kInt32Value); + test_dictionary.Set(kKey3, kDoubleValue); + test_dictionary.Set(kKey4, kStringValue); + test_dictionary.Set(kKey5, std::move(list_value)); + test_dictionary.Set(kKey6, std::move(dictionary_value)); std::unique_ptr<Response> response(Response::CreateEmpty()); MessageWriter writer(response.get()); @@ -540,21 +540,21 @@ const double kDoubleValue = 4.9; const std::string kStringValue = "fifty"; - base::Value list_value(base::Value::Type::LIST); + base::Value::List list_value; list_value.Append(kBoolValue); list_value.Append(kInt32Value); - base::Value dictionary_value(base::Value::Type::DICTIONARY); - dictionary_value.SetBoolKey(kKey1, kBoolValue); - dictionary_value.SetIntKey(kKey2, kDoubleValue); + base::Value::Dict dictionary_value; + dictionary_value.Set(kKey1, kBoolValue); + dictionary_value.Set(kKey2, kDoubleValue); - base::Value test_dictionary(base::Value::Type::DICTIONARY); - test_dictionary.SetBoolKey(kKey1, kBoolValue); - test_dictionary.SetIntKey(kKey2, kInt32Value); - test_dictionary.SetDoubleKey(kKey3, kDoubleValue); - test_dictionary.SetStringKey(kKey4, kStringValue); - test_dictionary.SetKey(kKey5, std::move(list_value)); - test_dictionary.SetKey(kKey6, std::move(dictionary_value)); + base::Value::Dict test_dictionary; + test_dictionary.Set(kKey1, kBoolValue); + test_dictionary.Set(kKey2, kInt32Value); + test_dictionary.Set(kKey3, kDoubleValue); + test_dictionary.Set(kKey4, kStringValue); + test_dictionary.Set(kKey5, std::move(list_value)); + test_dictionary.Set(kKey6, std::move(dictionary_value)); std::unique_ptr<Response> response(Response::CreateEmpty()); MessageWriter writer(response.get()); @@ -583,15 +583,15 @@ const double kDoubleValue = 4.9; const std::string kStringValue = "fifty"; - base::Value list_value(base::Value::Type::LIST); + base::Value::List list_value; list_value.Append(kBoolValue); list_value.Append(kInt32Value); - base::Value dictionary_value(base::Value::Type::DICTIONARY); - dictionary_value.SetBoolPath(kKey1, kBoolValue); - dictionary_value.SetIntPath(kKey2, kDoubleValue); + base::Value::Dict dictionary_value; + dictionary_value.Set(kKey1, kBoolValue); + dictionary_value.Set(kKey2, kDoubleValue); - base::Value test_list(base::Value::Type::LIST); + base::Value::List test_list; test_list.Append(kBoolValue); test_list.Append(kInt32Value); test_list.Append(kDoubleValue); @@ -626,15 +626,15 @@ const double kDoubleValue = 4.9; const std::string kStringValue = "fifty"; - base::Value list_value(base::Value::Type::LIST); + base::Value::List list_value; list_value.Append(kBoolValue); list_value.Append(kInt32Value); - base::Value dictionary_value(base::Value::Type::DICTIONARY); - dictionary_value.SetBoolPath(kKey1, kBoolValue); - dictionary_value.SetIntPath(kKey2, kDoubleValue); + base::Value::Dict dictionary_value; + dictionary_value.Set(kKey1, kBoolValue); + dictionary_value.Set(kKey2, kDoubleValue); - base::Value test_list(base::Value::Type::LIST); + base::Value::List test_list; test_list.Append(kBoolValue); test_list.Append(kInt32Value); test_list.Append(kDoubleValue);
diff --git a/gpu/command_buffer/tests/webgpu_mailbox_unittest.cc b/gpu/command_buffer/tests/webgpu_mailbox_unittest.cc index b667058..921c36e 100644 --- a/gpu/command_buffer/tests/webgpu_mailbox_unittest.cc +++ b/gpu/command_buffer/tests/webgpu_mailbox_unittest.cc
@@ -14,11 +14,6 @@ #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/color_space.h" - -#if BUILDFLAG(IS_MAC) -#include "gpu/command_buffer/tests/gl_manager.h" -#endif // BUILDFLAG(IS_MAC) - #include "ui/gl/gl_context.h" #include "ui/gl/gl_utils.h" #include "ui/gl/init/gl_factory.h" @@ -132,18 +127,6 @@ protected: void SetUp() override { -#if BUILDFLAG(IS_MAC) - // Crashing on Mac M1. Currently missing stack trace. crbug.com/1271926 - // This must be checked before WebGPUTest::Initialize otherwise context - // switched is locked and we cannot temporarily have this GLContext. - GLManager gl_manager; - gl_manager.Initialize(GLManager::Options()); - std::string renderer(gl_manager.context()->GetGLRenderer()); - if (renderer.find("Apple M1") != std::string::npos) - mac_m1_ = true; - gl_manager.Destroy(); -#endif - SKIP_TEST_IF(!WebGPUSupported()); SKIP_TEST_IF(!WebGPUSharedImageSupported()); WebGPUTest::SetUp(); @@ -246,9 +229,6 @@ queue.Submit(1, &commands); } -#if BUILDFLAG(IS_MAC) - bool mac_m1_ = false; -#endif wgpu::Device device_; }; @@ -810,11 +790,6 @@ // devices tried to create shared images with the same (id, generation) (which // is possible because they can be on different Dawn wires) they would conflict. TEST_P(WebGPUMailboxTest, AssociateOnTwoDevicesAtTheSameTime) { -#if BUILDFLAG(IS_MAC) - // Crashing on Mac M1. Currently missing stack trace. crbug.com/1271926 - SKIP_TEST_IF(mac_m1_); -#endif - // Create a the shared images. SharedImageInterface* sii = GetSharedImageInterface(); Mailbox mailbox_a = sii->CreateSharedImage(
diff --git a/gpu/command_buffer/tests/webgpu_test.cc b/gpu/command_buffer/tests/webgpu_test.cc index 93e9c4b..ec2e5c1 100644 --- a/gpu/command_buffer/tests/webgpu_test.cc +++ b/gpu/command_buffer/tests/webgpu_test.cc
@@ -26,11 +26,6 @@ #include "testing/gmock/include/gmock/gmock-matchers.h" #include "testing/gtest/include/gtest/gtest.h" -#if BUILDFLAG(IS_MAC) -#include "gpu/command_buffer/tests/gl_manager.h" -#include "ui/gl/gl_context.h" -#endif - namespace gpu { namespace { @@ -349,21 +344,7 @@ EXPECT_TRUE(called); } -TEST_F(WebGPUTest, RequestDeviceWitUnsupportedFeature) { -#if BUILDFLAG(IS_MAC) - // Crashing on Mac M1. Currently missing stack trace. crbug.com/1271926 - // This must be checked before WebGPUTest::Initialize otherwise context - // switched is locked and we cannot temporarily have this GLContext. - GLManager gl_manager; - gl_manager.Initialize(GLManager::Options()); - std::string renderer(gl_manager.context()->GetGLRenderer()); - if (renderer.find("Apple M1") != std::string::npos) { - gl_manager.Destroy(); - GTEST_SKIP() << "Skipped due to crbug.com/1271926."; - } - gl_manager.Destroy(); -#endif - +TEST_F(WebGPUTest, RequestDeviceWithUnsupportedFeature) { Initialize(WebGPUTest::Options()); // Create device with unsupported features, expect to fail to create and
diff --git a/gpu/config/gpu_finch_features.cc b/gpu/config/gpu_finch_features.cc index e898eb1..885cb5c 100644 --- a/gpu/config/gpu_finch_features.cc +++ b/gpu/config/gpu_finch_features.cc
@@ -288,7 +288,7 @@ const base::FeatureParam<std::string> kDrDcBlockListByDevice{ &kEnableDrDc, "BlockListByDevice", "LF9810_2GB|amber|chopin|secret|a03|SO-51B|on7xelte|j7xelte|F41B|doha|" - "rk322x_box|a20s"}; + "rk322x_box|a20s|HWMAR|HWSTK-HF|HWPOT-H"}; // crbug.com/1340059, crbug.com/1340064 const base::FeatureParam<std::string> kDrDcBlockListByModel{
diff --git a/ios/chrome/browser/follow/follow_java_script_feature.mm b/ios/chrome/browser/follow/follow_java_script_feature.mm index a9620910..5df80fb 100644 --- a/ios/chrome/browser/follow/follow_java_script_feature.mm +++ b/ios/chrome/browser/follow/follow_java_script_feature.mm
@@ -61,7 +61,7 @@ const base::Value* response) { NSMutableArray<NSURL*>* rss_urls = nil; if (response && response->is_list()) { - for (const auto& link : response->GetListDeprecated()) { + for (const auto& link : response->GetList()) { if (link.is_string()) { NSURL* nsurl = net::NSURLWithGURL(GURL(link.GetString())); if (nsurl) {
diff --git a/ios/chrome/browser/signin/pattern_account_restriction.mm b/ios/chrome/browser/signin/pattern_account_restriction.mm index eede5a2e..d31faa99 100644 --- a/ios/chrome/browser/signin/pattern_account_restriction.mm +++ b/ios/chrome/browser/signin/pattern_account_restriction.mm
@@ -82,7 +82,7 @@ if (!value->is_list()) return false; - for (const base::Value& item : value->GetListDeprecated()) { + for (const base::Value& item : value->GetList()) { if (!item.is_string()) return false; auto maybe_pattern = PatternFromString(item.GetString());
diff --git a/ios/chrome/browser/ui/autofill/manual_fill/address_view_controller_egtest.mm b/ios/chrome/browser/ui/autofill/manual_fill/address_view_controller_egtest.mm index 5621b7b..5b733948 100644 --- a/ios/chrome/browser/ui/autofill/manual_fill/address_view_controller_egtest.mm +++ b/ios/chrome/browser/ui/autofill/manual_fill/address_view_controller_egtest.mm
@@ -96,14 +96,7 @@ // Tests that the addresses view controller contains the "Manage Addresses..." // action. // TODO(crbug.com/1116043): Flaky on ios simulator. -#if TARGET_IPHONE_SIMULATOR -#define MAYBE_testAddressesViewControllerContainsManageAddressesAction \ - DISABLED_testAddressesViewControllerContainsManageAddressesAction -#else -#define MAYBE_testAddressesViewControllerContainsManageAddressesAction \ - testAddressesViewControllerContainsManageAddressesAction -#endif -- (void)MAYBE_testAddressesViewControllerContainsManageAddressesAction { +- (void)DISABLED_testAddressesViewControllerContainsManageAddressesAction { // Bring up the keyboard. [[EarlGrey selectElementWithMatcher:chrome_test_util::WebViewMatcher()] performAction:chrome_test_util::TapWebElementWithId(kFormElementName)];
diff --git a/ios/chrome/browser/ui/link_to_text/link_to_text_egtest.mm b/ios/chrome/browser/ui/link_to_text/link_to_text_egtest.mm index 70a0828..658ebc9f 100644 --- a/ios/chrome/browser/ui/link_to_text/link_to_text_egtest.mm +++ b/ios/chrome/browser/ui/link_to_text/link_to_text_egtest.mm
@@ -101,7 +101,7 @@ GREYAssertTrue(result.is_list(), @"Result is not iterable."); NSMutableArray<NSString*>* marked_texts = [NSMutableArray array]; - for (const auto& element : result.GetListDeprecated()) { + for (const auto& element : result.GetList()) { if (element.is_string()) { NSString* ns_element = base::SysUTF8ToNSString(element.GetString()); [marked_texts addObject:ns_element];
diff --git a/ios/chrome/browser/ui/start_surface/start_surface_features.mm b/ios/chrome/browser/ui/start_surface/start_surface_features.mm index 268d7f5..8d87645 100644 --- a/ios/chrome/browser/ui/start_surface/start_surface_features.mm +++ b/ios/chrome/browser/ui/start_surface/start_surface_features.mm
@@ -25,7 +25,7 @@ double GetReturnToStartSurfaceDuration() { return base::GetFieldTrialParamByFeatureAsDouble( kStartSurface, kReturnToStartSurfaceInactiveDurationInSeconds, - 60 * 60 * 12 /*default to 12 hour*/); + 60 * 60 * 6 /*default to 6 hour*/); } bool ShouldHideShortcutsForStartSurface() {
diff --git a/ios/chrome/test/earl_grey/chrome_earl_grey.mm b/ios/chrome/test/earl_grey/chrome_earl_grey.mm index aecd8b52..e37cacf 100644 --- a/ios/chrome/test/earl_grey/chrome_earl_grey.mm +++ b/ios/chrome/test/earl_grey/chrome_earl_grey.mm
@@ -502,7 +502,7 @@ @"The script response is not iterable."); NSMutableDictionary* cookies = [NSMutableDictionary dictionary]; - for (const auto& option : result.GetListDeprecated()) { + for (const auto& option : result.GetList()) { if (option.is_string()) { NSString* nameValuePair = base::SysUTF8ToNSString(option.GetString()); NSMutableArray* cookieNameValue =
diff --git a/ios/google_internal/frameworks/ChromeInternal.framework.dSYM.ios.zip.sha1 b/ios/google_internal/frameworks/ChromeInternal.framework.dSYM.ios.zip.sha1 index a07cba9..8a90c49c 100644 --- a/ios/google_internal/frameworks/ChromeInternal.framework.dSYM.ios.zip.sha1 +++ b/ios/google_internal/frameworks/ChromeInternal.framework.dSYM.ios.zip.sha1
@@ -1 +1 @@ -2d14d0d4ce9591d466d76309ac0770d32af6ea58 \ No newline at end of file +61290bccddc9336c7a1aa08b92a98d606964d0a1 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/ChromeSSOInternal.framework.dSYM.ios.zip.sha1 b/ios/google_internal/frameworks/ChromeSSOInternal.framework.dSYM.ios.zip.sha1 index b2cadeb9..967cbe8 100644 --- a/ios/google_internal/frameworks/ChromeSSOInternal.framework.dSYM.ios.zip.sha1 +++ b/ios/google_internal/frameworks/ChromeSSOInternal.framework.dSYM.ios.zip.sha1
@@ -1 +1 @@ -92ea37c18faa44f354fdedbcc90d0d023ffadb23 \ No newline at end of file +17c705848ab1e7c9419f11e96e9d4a1fdb3556c1 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/chrome_internal_dynamic_framework.ios.zip.sha1 b/ios/google_internal/frameworks/chrome_internal_dynamic_framework.ios.zip.sha1 index 592ee03..0bf6304 100644 --- a/ios/google_internal/frameworks/chrome_internal_dynamic_framework.ios.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_internal_dynamic_framework.ios.zip.sha1
@@ -1 +1 @@ -cb2099bc15f74192fa01c1fbe44944f6e02845c9 \ No newline at end of file +fbf80bf78e23dd3a4fb3a846c411ad70fde63da9 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/chrome_internal_dynamic_framework.iossimulator.zip.sha1 b/ios/google_internal/frameworks/chrome_internal_dynamic_framework.iossimulator.zip.sha1 index 787caacf..51cea50 100644 --- a/ios/google_internal/frameworks/chrome_internal_dynamic_framework.iossimulator.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_internal_dynamic_framework.iossimulator.zip.sha1
@@ -1 +1 @@ -e4ab7e7b589e22a836d0f7bac49783d5a841b1a6 \ No newline at end of file +eb4c6ecdc5b866e7a9161578c28a5528c9bc9d36 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.ios.zip.sha1 b/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.ios.zip.sha1 index 082dd22..1554c88 100644 --- a/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.ios.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.ios.zip.sha1
@@ -1 +1 @@ -6148d36030991155525f216ee6a64ace7847b0e8 \ No newline at end of file +bfe14c3e55a8eebbb405a488d90c3e10b9a7fa03 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.iossimulator.zip.sha1 b/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.iossimulator.zip.sha1 index 41482b02..7429a726 100644 --- a/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.iossimulator.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.iossimulator.zip.sha1
@@ -1 +1 @@ -c90ff1bc575a62096b852cb9092c6e9d73d0f730 \ No newline at end of file +7a290c3ca595db4757d9d45a77ec207b0d0b57ac \ No newline at end of file
diff --git a/ios/google_internal/frameworks/chrome_test_internal_dynamic_framework.ios.zip.sha1 b/ios/google_internal/frameworks/chrome_test_internal_dynamic_framework.ios.zip.sha1 index 2f34826..ede3c4b 100644 --- a/ios/google_internal/frameworks/chrome_test_internal_dynamic_framework.ios.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_test_internal_dynamic_framework.ios.zip.sha1
@@ -1 +1 @@ -3d6de19090f4bec69f0ce6d64519787f579ddacf \ No newline at end of file +3002a3e9299db0700df9f51b66ef2f5c7ed99aef \ No newline at end of file
diff --git a/ios/google_internal/frameworks/chrome_test_internal_dynamic_framework.iossimulator.zip.sha1 b/ios/google_internal/frameworks/chrome_test_internal_dynamic_framework.iossimulator.zip.sha1 index 3ff6214..2c00533 100644 --- a/ios/google_internal/frameworks/chrome_test_internal_dynamic_framework.iossimulator.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_test_internal_dynamic_framework.iossimulator.zip.sha1
@@ -1 +1 @@ -62dc40eb1141f45d5d62037570b3e7d31c899efb \ No newline at end of file +16a8488a4c1889c3097bda1c0933e036b5e5464c \ No newline at end of file
diff --git a/ios/google_internal/frameworks/remoting_internal_dynamic_framework.ios.zip.sha1 b/ios/google_internal/frameworks/remoting_internal_dynamic_framework.ios.zip.sha1 index 34bf09a..a5403f1 100644 --- a/ios/google_internal/frameworks/remoting_internal_dynamic_framework.ios.zip.sha1 +++ b/ios/google_internal/frameworks/remoting_internal_dynamic_framework.ios.zip.sha1
@@ -1 +1 @@ -be6481907b31cad010f2c433b55df2be51305cee \ No newline at end of file +f39f9a580799e962a00cf8b7d37419fd79c2f110 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/remoting_internal_dynamic_framework.iossimulator.zip.sha1 b/ios/google_internal/frameworks/remoting_internal_dynamic_framework.iossimulator.zip.sha1 index ebacd70..4196ad1 100644 --- a/ios/google_internal/frameworks/remoting_internal_dynamic_framework.iossimulator.zip.sha1 +++ b/ios/google_internal/frameworks/remoting_internal_dynamic_framework.iossimulator.zip.sha1
@@ -1 +1 @@ -bf2029bebb2266af0b8f246e9cf062561a5af4a9 \ No newline at end of file +1a21db7c9dd8f34d58bb3adcd4520373bb7a7198 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.ios.zip.sha1 b/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.ios.zip.sha1 index f1c0f45a..f4b6be918 100644 --- a/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.ios.zip.sha1 +++ b/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.ios.zip.sha1
@@ -1 +1 @@ -7c9c957ca8696a3759569bf5931e30c2a45f14e6 \ No newline at end of file +611b8166f2b84b8454613c9be9a53a86020c9dd6 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.iossimulator.zip.sha1 b/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.iossimulator.zip.sha1 index 1904dcc2..4a946f8 100644 --- a/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.iossimulator.zip.sha1 +++ b/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.iossimulator.zip.sha1
@@ -1 +1 @@ -a395e836cb8b44eac6e457e9eb0af4f6ccf438df \ No newline at end of file +ccc3a759f0e7446bafc8b43be438760402c90cae \ No newline at end of file
diff --git a/ios/web/BUILD.gn b/ios/web/BUILD.gn index c99475f..365ee2b 100644 --- a/ios/web/BUILD.gn +++ b/ios/web/BUILD.gn
@@ -458,7 +458,6 @@ "//ios/web/test:test_constants", "//ios/web/test:test_support", "//ios/web/test/fakes", - "//ios/web/web_state/js", "//net:test_support", "//testing/gmock", "//testing/gtest", @@ -501,7 +500,6 @@ "//ios/web/test:test_support", "//ios/web/test/fakes:fakes", "//ios/web/web_state:web_state_impl_header", - "//ios/web/web_state/js", "//ios/web/web_state/ui", "//ios/web/web_state/ui:crw_context_menu_controller", "//net:test_support", @@ -632,7 +630,6 @@ "web_state/keep_render_process_alive_inttest.mm", "web_state/permissions_inttest.mm", "web_state/ui/crw_context_menu_element_fetcher_inttest.mm", - "web_state/web_state_impl_inttest.mm", "web_state/web_state_observer_inttest.mm", "webui/web_ui_inttest.mm", "webui/web_ui_mojo_inttest.mm",
diff --git a/ios/web/public/deprecated/BUILD.gn b/ios/web/public/deprecated/BUILD.gn index a254d698..642ff96b 100644 --- a/ios/web/public/deprecated/BUILD.gn +++ b/ios/web/public/deprecated/BUILD.gn
@@ -13,8 +13,6 @@ "//url", ] sources = [ - "crw_js_injection_evaluator.h", - "crw_js_injection_receiver.h", "global_web_state_observer.h", "url_verification_constants.h", ]
diff --git a/ios/web/public/deprecated/crw_js_injection_evaluator.h b/ios/web/public/deprecated/crw_js_injection_evaluator.h deleted file mode 100644 index ae792bb7..0000000 --- a/ios/web/public/deprecated/crw_js_injection_evaluator.h +++ /dev/null
@@ -1,26 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef IOS_WEB_PUBLIC_DEPRECATED_CRW_JS_INJECTION_EVALUATOR_H_ -#define IOS_WEB_PUBLIC_DEPRECATED_CRW_JS_INJECTION_EVALUATOR_H_ - -#import <Foundation/Foundation.h> - -@protocol CRWJSInjectionEvaluator - -// Executes the supplied JavaScript in the WebView. Calls `completionHandler` -// with results of the execution (which may be nil if the implementing object -// has no way to run the execution or the execution returns a nil value) -// or an NSError if there is an error. The `completionHandler` can be nil. -- (void)executeJavaScript:(NSString*)script - completionHandler:(void (^)(id, NSError*))completionHandler; - -// Asynchronously executes `javaScript` in the main frame's context, -// registering user interaction. For security reasons, some implementations may -// reject the request if the page has some elevated privileges. -- (void)executeUserJavaScript:(NSString*)script - completionHandler:(void (^)(id, NSError*))completionHandler; -@end - -#endif // IOS_WEB_PUBLIC_DEPRECATED_CRW_JS_INJECTION_EVALUATOR_H_
diff --git a/ios/web/public/deprecated/crw_js_injection_receiver.h b/ios/web/public/deprecated/crw_js_injection_receiver.h deleted file mode 100644 index b5906c5..0000000 --- a/ios/web/public/deprecated/crw_js_injection_receiver.h +++ /dev/null
@@ -1,20 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef IOS_WEB_PUBLIC_DEPRECATED_CRW_JS_INJECTION_RECEIVER_H_ -#define IOS_WEB_PUBLIC_DEPRECATED_CRW_JS_INJECTION_RECEIVER_H_ - -#import <UIKit/UIKit.h> - -#import "ios/web/public/deprecated/crw_js_injection_evaluator.h" - -// CRWJSInjectionReceiver injects JavaScript into a web view. -@interface CRWJSInjectionReceiver : NSObject <CRWJSInjectionEvaluator> - -// Init with JavaScript evaluator. -- (id)initWithEvaluator:(id<CRWJSInjectionEvaluator>)evaluator; - -@end - -#endif // IOS_WEB_PUBLIC_DEPRECATED_CRW_JS_INJECTION_RECEIVER_H_
diff --git a/ios/web/public/test/earl_grey/js_test_util.mm b/ios/web/public/test/earl_grey/js_test_util.mm index c40bb8d..bb678d4 100644 --- a/ios/web/public/test/earl_grey/js_test_util.mm +++ b/ios/web/public/test/earl_grey/js_test_util.mm
@@ -8,8 +8,8 @@ #import "base/test/ios/wait_util.h" #import "base/values.h" +#import "ios/web/public/test/web_view_interaction_test_util.h" #import "ios/web/public/web_state.h" -#import "ios/web/web_state/web_state_impl.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." @@ -20,36 +20,13 @@ namespace web { -// Executes `javascript` on the given `web_state`, and waits until execution is -// completed. If `out_error` is not nil, it is set to the error resulting from -// the execution, if one occurs. The return value is the result of the -// JavaScript execution, or nil if script execution timed out. -absl::optional<base::Value> ExecuteJavaScript( - WebState* web_state, - const std::u16string& javascript) { - __block bool did_complete = false; - __block absl::optional<base::Value> result; - - static_cast<WebStateImpl*>(web_state)->ExecuteJavaScript( - javascript, base::BindOnce(^(const base::Value* completion_result) { - result = completion_result->Clone(); - did_complete = true; - })); - - // Wait for completion. - BOOL succeeded = WaitUntilConditionOrTimeout(kWaitForJSCompletionTimeout, ^{ - return did_complete; - }); - - return succeeded ? std::move(result) : absl::nullopt; -} - bool WaitUntilWindowIdInjected(WebState* web_state) { // Keep polling until either the JavaScript execution returns with expected // value (indicating that Window ID is set), the timeout occurs, or an // unrecoverable error occurs. return WaitUntilConditionOrTimeout(kWaitForJSCompletionTimeout, ^{ - absl::optional<base::Value> result = ExecuteJavaScript(web_state, u"0"); + std::unique_ptr<base::Value> result = + test::ExecuteJavaScript(web_state, "0"); return result && result->is_double() && result->GetDouble() == 0.0; }); }
diff --git a/ios/web/public/test/fakes/fake_web_state.h b/ios/web/public/test/fakes/fake_web_state.h index 00a829802..f474172 100644 --- a/ios/web/public/test/fakes/fake_web_state.h +++ b/ios/web/public/test/fakes/fake_web_state.h
@@ -68,7 +68,6 @@ const override; SessionCertificatePolicyCache* GetSessionCertificatePolicyCache() override; CRWSessionStorage* BuildSessionStorage() override; - CRWJSInjectionReceiver* GetJSInjectionReceiver() const override; void LoadData(NSData* data, NSString* mime_type, const GURL& url) override; void ExecuteUserJavaScript(NSString* javaScript) override; NSString* GetStableIdentifier() const override;
diff --git a/ios/web/public/test/fakes/fake_web_state.mm b/ios/web/public/test/fakes/fake_web_state.mm index 0b6351cb..d3861150 100644 --- a/ios/web/public/test/fakes/fake_web_state.mm +++ b/ios/web/public/test/fakes/fake_web_state.mm
@@ -207,10 +207,6 @@ web_view_proxy_ = web_view_proxy; } -CRWJSInjectionReceiver* FakeWebState::GetJSInjectionReceiver() const { - return nullptr; -} - void FakeWebState::LoadData(NSData* data, NSString* mime_type, const GURL& url) {
diff --git a/ios/web/public/test/web_view_interaction_test_util.mm b/ios/web/public/test/web_view_interaction_test_util.mm index ae8f6b1..c651604 100644 --- a/ios/web/public/test/web_view_interaction_test_util.mm +++ b/ios/web/public/test/web_view_interaction_test_util.mm
@@ -13,6 +13,7 @@ #import "base/test/ios/wait_util.h" #import "ios/web/js_messaging/java_script_feature_manager.h" #import "ios/web/js_messaging/web_frame_impl.h" +#import "ios/web/js_messaging/web_view_js_utils.h" #import "ios/web/public/js_messaging/web_frame.h" #import "ios/web/public/js_messaging/web_frame_util.h" #import "ios/web/public/ui/crw_web_view_scroll_view_proxy.h" @@ -24,10 +25,11 @@ #error "This file requires ARC support." #endif -using web::NavigationManager; -using base::test::ios::WaitUntilConditionOrTimeout; -using base::test::ios::kWaitForUIElementTimeout; using base::test::ios::kWaitForJSCompletionTimeout; +using base::test::ios::kWaitForUIElementTimeout; +using base::test::ios::WaitUntilConditionOrTimeout; +using web::NavigationManager; +using web::ValueResultFromWKResult; namespace web { namespace test { @@ -41,14 +43,15 @@ std::unique_ptr<base::Value> ExecuteJavaScript(web::WebState* web_state, const std::string& script) { - __block std::unique_ptr<base::Value> result; + __block id result = nil; __block bool did_finish = false; - static_cast<WebStateImpl*>(web_state)->ExecuteJavaScript( - base::UTF8ToUTF16(script), base::BindOnce(^(const base::Value* value) { - if (value) - result = std::make_unique<base::Value>(value->Clone()); - did_finish = true; - })); + CRWWebController* web_controller = + static_cast<WebStateImpl*>(web_state)->GetWebController(); + [web_controller executeJavaScript:base::SysUTF8ToNSString(script) + completionHandler:^(id handler_result, NSError*) { + result = handler_result; + did_finish = true; + }]; bool completed = WaitUntilConditionOrTimeout(kWaitForJSCompletionTimeout, ^{ return did_finish; @@ -57,20 +60,7 @@ return nullptr; } - // As result is marked __block, this return call does a copy and not a move - // (marking the variable as __block mean it is allocated in the block object - // and not the stack). Use an explicit move to a local variable. - // - // Fixes the following compilation failures: - // ../web_view_interaction_test_util.mm:58:10: error: - // call to implicitly-deleted copy constructor of - // 'std::unique_ptr<base::Value>' - // - // ../web_view_interaction_test_util.mm:58:10: error: - // moving a local object in a return statement prevents copy elision - // [-Werror,-Wpessimizing-move] - std::unique_ptr<base::Value> stack_result = std::move(result); - return stack_result; + return ValueResultFromWKResult(result); } std::unique_ptr<base::Value> CallJavaScriptFunction(
diff --git a/ios/web/public/web_state.h b/ios/web/public/web_state.h index 09c01e7..2932645 100644 --- a/ios/web/public/web_state.h +++ b/ios/web/public/web_state.h
@@ -31,7 +31,6 @@ class GURL; -@class CRWJSInjectionReceiver; @class CRWSessionStorage; @protocol CRWScrollableContent; @protocol CRWWebViewDownload; @@ -305,9 +304,6 @@ // is autoreleased. virtual CRWSessionStorage* BuildSessionStorage() = 0; - // Gets the CRWJSInjectionReceiver associated with this WebState. - virtual CRWJSInjectionReceiver* GetJSInjectionReceiver() const = 0; - // Loads `data` of type `mime_type` and replaces last committed URL with the // given `url`. virtual void LoadData(NSData* data, NSString* mime_type, const GURL& url) = 0;
diff --git a/ios/web/web_state/js/BUILD.gn b/ios/web/web_state/js/BUILD.gn deleted file mode 100644 index 2a511b50..0000000 --- a/ios/web/web_state/js/BUILD.gn +++ /dev/null
@@ -1,18 +0,0 @@ -# Copyright 2017 The Chromium Authors -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -import("//ios/build/config.gni") - -source_set("js") { - deps = [ - "//base", - "//ios/web/js_messaging", - "//ios/web/public", - "//ios/web/public/deprecated", - ] - - sources = [ "crw_js_injection_receiver.mm" ] - - configs += [ "//build/config/compiler:enable_arc" ] -}
diff --git a/ios/web/web_state/js/crw_js_injection_receiver.mm b/ios/web/web_state/js/crw_js_injection_receiver.mm deleted file mode 100644 index 56568c2a..0000000 --- a/ios/web/web_state/js/crw_js_injection_receiver.mm +++ /dev/null
@@ -1,41 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#import "ios/web/public/deprecated/crw_js_injection_receiver.h" - -#import "base/check.h" -#import "ios/web/public/deprecated/crw_js_injection_evaluator.h" - -#if !defined(__has_feature) || !__has_feature(objc_arc) -#error "This file requires ARC support." -#endif - -@implementation CRWJSInjectionReceiver { - // Used to evaluate JavaScript. - __weak id<CRWJSInjectionEvaluator> _evaluator; -} - -- (id)initWithEvaluator:(id<CRWJSInjectionEvaluator>)evaluator { - DCHECK(evaluator); - self = [super init]; - if (self) { - _evaluator = evaluator; - } - return self; -} - -#pragma mark - -#pragma mark CRWJSInjectionEvaluatorMethods - -- (void)executeJavaScript:(NSString*)script - completionHandler:(void (^)(id, NSError*))completionHandler { - [_evaluator executeJavaScript:script completionHandler:completionHandler]; -} - -- (void)executeUserJavaScript:(NSString*)script - completionHandler:(void (^)(id, NSError*))completionHandler { - [_evaluator executeUserJavaScript:script completionHandler:completionHandler]; -} - -@end
diff --git a/ios/web/web_state/ui/BUILD.gn b/ios/web/web_state/ui/BUILD.gn index d6549e0..08fb3b1a 100644 --- a/ios/web/web_state/ui/BUILD.gn +++ b/ios/web/web_state/ui/BUILD.gn
@@ -48,7 +48,6 @@ "//ios/web/web_state:user_interaction", "//ios/web/web_state:web_state_impl_header", "//ios/web/web_state:web_view_internal_creation_util", - "//ios/web/web_state/js", "//ios/web/web_state/ui:wk_web_view_configuration_provider", "//ios/web/web_view:util", "//ios/web/webui:webui", @@ -158,7 +157,6 @@ "//ios/web/js_messaging:java_script_feature_util", "//ios/web/navigation:session_restore_feature", "//ios/web/public", - "//ios/web/web_state/js", "//ios/web/webui", ]
diff --git a/ios/web/web_state/ui/crw_web_controller.h b/ios/web/web_state/ui/crw_web_controller.h index 76b92e41..4d6619d 100644 --- a/ios/web/web_state/ui/crw_web_controller.h +++ b/ios/web/web_state/ui/crw_web_controller.h
@@ -25,7 +25,6 @@ } // namespace web @class CRWContextMenuItem; -@class CRWJSInjectionReceiver; @protocol CRWScrollableContent; @protocol CRWSwipeRecognizerProvider; @class CRWWebViewContentView; @@ -89,9 +88,6 @@ // back-forward list navigations. @property(nonatomic) BOOL allowsBackForwardNavigationGestures; -@property(strong, nonatomic, readonly) - CRWJSInjectionReceiver* jsInjectionReceiver; - // Whether the WebController should attempt to keep the render process alive. @property(nonatomic, assign, getter=shouldKeepRenderProcessAlive) BOOL keepsRenderProcessAlive; @@ -261,8 +257,6 @@ // Handles a navigation did replace state message for the current webpage. - (void)handleNavigationDidReplaceStateMessage:(base::Value*)message; -#pragma mark CRWJSInjectionEvaluator - // Do not use these executeJavaScript functions directly, prefer // WebFrame::CallJavaScriptFunction if possible, otherwise use // WebState::ExecuteJavaScript and WebState::ExecuteUserJavaScript.
diff --git a/ios/web/web_state/ui/crw_web_controller.mm b/ios/web/web_state/ui/crw_web_controller.mm index 33cf73b..35724ab 100644 --- a/ios/web/web_state/ui/crw_web_controller.mm +++ b/ios/web/web_state/ui/crw_web_controller.mm
@@ -43,8 +43,6 @@ #import "ios/web/navigation/wk_back_forward_list_item_holder.h" #import "ios/web/navigation/wk_navigation_util.h" #import "ios/web/public/browser_state.h" -#import "ios/web/public/deprecated/crw_js_injection_evaluator.h" -#import "ios/web/public/deprecated/crw_js_injection_receiver.h" #import "ios/web/public/js_messaging/web_frame_util.h" #import "ios/web/public/permissions/permissions.h" #import "ios/web/public/ui/crw_context_menu_item.h" @@ -95,7 +93,6 @@ @interface CRWWebController () <CRWWKNavigationHandlerDelegate, CRWInputViewProvider, - CRWJSInjectionEvaluator, CRWSSLStatusUpdaterDataSource, CRWSSLStatusUpdaterDelegate, CRWWebControllerContainerViewDelegate, @@ -220,8 +217,6 @@ // Script manager for setting the windowID. @property(nonatomic, strong) CRWJSWindowIDManager* windowIDJSManager; -@property(strong, nonatomic) CRWJSInjectionReceiver* jsInjectionReceiver; - // Returns the current URL of the web view, and sets `trustLevel` accordingly // based on the confidence in the verification. - (GURL)webURLWithTrustLevel:(web::URLVerificationTrustLevel*)trustLevel; @@ -286,8 +281,6 @@ DCHECK(_webStateImpl); // Content area is lazily instantiated. _defaultURL = GURL(url::kAboutBlankURL); - _jsInjectionReceiver = - [[CRWJSInjectionReceiver alloc] initWithEvaluator:self]; _requestController = [[CRWWebRequestController alloc] init]; _requestController.delegate = self; _webViewProxy = [[CRWWebViewProxyImpl alloc] initWithWebController:self];
diff --git a/ios/web/web_state/web_state_impl.h b/ios/web/web_state/web_state_impl.h index 3452d7d..ddd51963 100644 --- a/ios/web/web_state/web_state_impl.h +++ b/ios/web/web_state/web_state_impl.h
@@ -212,21 +212,6 @@ // Returns true if a javascript dialog is running. bool IsJavaScriptDialogRunning(); - // DISCOURAGED. Prefer using `WebFrame CallJavaScriptFunction` instead because - // it restricts JavaScript execution to functions within __gCrWeb and can also - // call those functions on any frame in the page. ExecuteJavaScript here can - // execute arbitrary JavaScript code, which is not as safe and is restricted - // to executing only on the main frame. - // Runs JavaScript in the main frame's context. If a callback is provided, it - // will be used to return the result, when the result is available or script - // execution has failed due to an error. - // NOTE: Integer values will be returned as Type::DOUBLE because of underlying - // library limitation. - typedef base::OnceCallback<void(const base::Value*)> JavaScriptResultCallback; - void ExecuteJavaScript(const std::u16string& javascript); - void ExecuteJavaScript(const std::u16string& javascript, - JavaScriptResultCallback callback); - // Instructs the delegate to create a new web state. Called when this WebState // wants to open a new window. `url` is the URL of the new window; // `opener_url` is the URL of the page which requested a window to be open; @@ -294,7 +279,6 @@ const final; SessionCertificatePolicyCache* GetSessionCertificatePolicyCache() final; CRWSessionStorage* BuildSessionStorage() final; - CRWJSInjectionReceiver* GetJSInjectionReceiver() const final; void LoadData(NSData* data, NSString* mime_type, const GURL& url) final; void ExecuteUserJavaScript(NSString* javaScript) final; NSString* GetStableIdentifier() const final;
diff --git a/ios/web/web_state/web_state_impl.mm b/ios/web/web_state/web_state_impl.mm index 6f55ca3d..d4c08df4 100644 --- a/ios/web/web_state/web_state_impl.mm +++ b/ios/web/web_state/web_state_impl.mm
@@ -472,25 +472,12 @@ : saved_->GetSessionStorage(); } -CRWJSInjectionReceiver* WebStateImpl::GetJSInjectionReceiver() const { - return LIKELY(pimpl_) ? pimpl_->GetJSInjectionReceiver() : nullptr; -} - void WebStateImpl::LoadData(NSData* data, NSString* mime_type, const GURL& url) { RealizedState()->LoadData(data, mime_type, url); } -void WebStateImpl::ExecuteJavaScript(const std::u16string& javascript) { - RealizedState()->ExecuteJavaScript(javascript); -} - -void WebStateImpl::ExecuteJavaScript(const std::u16string& javascript, - JavaScriptResultCallback callback) { - RealizedState()->ExecuteJavaScript(javascript, std::move(callback)); -} - void WebStateImpl::ExecuteUserJavaScript(NSString* javascript) { RealizedState()->ExecuteUserJavaScript(javascript); }
diff --git a/ios/web/web_state/web_state_impl_inttest.mm b/ios/web/web_state/web_state_impl_inttest.mm deleted file mode 100644 index 6cf2adf..0000000 --- a/ios/web/web_state/web_state_impl_inttest.mm +++ /dev/null
@@ -1,50 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#import "ios/web/web_state/web_state_impl.h" - -#import "base/bind.h" -#import "base/test/ios/wait_util.h" -#import "base/values.h" -#import "ios/web/public/test/web_test_with_web_state.h" -#import "ios/web/web_state/web_state_impl.h" - -#if !defined(__has_feature) || !__has_feature(objc_arc) -#error "This file requires ARC support." -#endif - -using base::test::ios::kWaitForJSCompletionTimeout; -using base::test::ios::WaitUntilConditionOrTimeout; - -namespace web { - -typedef WebTestWithWebState WebStateImplTest; - -// Tests script execution with and without callback. -TEST_F(WebStateImplTest, ScriptExecution) { - WebStateImpl* web_state_impl = static_cast<WebStateImpl*>(web_state()); - - ASSERT_TRUE(LoadHtml("<html></html>")); - - // Execute script without callback. - web_state_impl->ExecuteJavaScript(u"window.foo = 'bar'"); - - // Execute script with callback. - __block std::unique_ptr<base::Value> execution_result; - __block bool execution_complete = false; - web_state_impl->ExecuteJavaScript( - u"window.foo", base::BindOnce(^(const base::Value* value) { - execution_result = std::make_unique<base::Value>(value->Clone()); - execution_complete = true; - })); - ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForJSCompletionTimeout, ^{ - return execution_complete; - })); - - ASSERT_TRUE(execution_result); - ASSERT_TRUE(execution_result->is_string()); - EXPECT_EQ("bar", execution_result->GetString()); -} - -} // namespace web
diff --git a/ios/web/web_state/web_state_impl_realized_web_state.h b/ios/web/web_state/web_state_impl_realized_web_state.h index 2343ec0..a2bcc1d 100644 --- a/ios/web/web_state/web_state_impl_realized_web_state.h +++ b/ios/web/web_state/web_state_impl_realized_web_state.h
@@ -144,11 +144,7 @@ void OpenURL(const WebState::OpenURLParams& params); void Stop(); CRWSessionStorage* BuildSessionStorage(); - CRWJSInjectionReceiver* GetJSInjectionReceiver() const; void LoadData(NSData* data, NSString* mime_type, const GURL& url); - void ExecuteJavaScript(const std::u16string& javascript); - void ExecuteJavaScript(const std::u16string& javascript, - JavaScriptResultCallback callback); void ExecuteUserJavaScript(NSString* javaScript); const std::string& GetContentsMimeType() const; bool ContentIsHTML() const;
diff --git a/ios/web/web_state/web_state_impl_realized_web_state.mm b/ios/web/web_state/web_state_impl_realized_web_state.mm index 09d0383..14ed97c 100644 --- a/ios/web/web_state/web_state_impl_realized_web_state.mm +++ b/ios/web/web_state/web_state_impl_realized_web_state.mm
@@ -507,7 +507,8 @@ // This call must be sent to the webstate directly, because the result of this // call will create the WebFrames. (Thus, the WebFrames do not yet exist and // can not be used to call JavaScript.) - ExecuteJavaScript(u"__gCrWeb.message.getExistingFrames();"); + [web_controller_ executeJavaScript:@"__gCrWeb.message.getExistingFrames();" + completionHandler:nil]; } void WebStateImpl::RealizedWebState::RemoveAllWebFrames() { @@ -625,34 +626,12 @@ *certificate_policy_cache_); } -CRWJSInjectionReceiver* WebStateImpl::RealizedWebState::GetJSInjectionReceiver() - const { - return [web_controller_ jsInjectionReceiver]; -} - void WebStateImpl::RealizedWebState::LoadData(NSData* data, NSString* mime_type, const GURL& url) { [web_controller_ loadData:data MIMEType:mime_type forURL:url]; } -void WebStateImpl::RealizedWebState::ExecuteJavaScript( - const std::u16string& javascript) { - [web_controller_ executeJavaScript:base::SysUTF16ToNSString(javascript) - completionHandler:nil]; -} - -void WebStateImpl::RealizedWebState::ExecuteJavaScript( - const std::u16string& javascript, - JavaScriptResultCallback callback) { - __block JavaScriptResultCallback stack_callback = std::move(callback); - [web_controller_ - executeJavaScript:base::SysUTF16ToNSString(javascript) - completionHandler:^(id value, NSError* error) { - std::move(stack_callback).Run(ValueResultFromWKResult(value).get()); - }]; -} - void WebStateImpl::RealizedWebState::ExecuteUserJavaScript( NSString* javascript) { [web_controller_ executeUserJavaScript:javascript completionHandler:nil];
diff --git a/ios/web/web_state/web_state_unittest.mm b/ios/web/web_state/web_state_unittest.mm index bb4eb3d..91961c2 100644 --- a/ios/web/web_state/web_state_unittest.mm +++ b/ios/web/web_state/web_state_unittest.mm
@@ -32,6 +32,7 @@ #import "ios/web/public/web_client.h" #import "ios/web/public/web_state_observer.h" #import "ios/web/test/test_url_constants.h" +#import "ios/web/web_state/ui/crw_web_controller.h" #import "ios/web/web_state/web_state_impl.h" #import "net/test/embedded_test_server/default_handlers.h" #import "net/test/embedded_test_server/embedded_test_server.h" @@ -561,10 +562,12 @@ // Queue some javascript to wait for every handler to complete. // TODO(crbug.com/1244067): Remove this workaround. __block BOOL called = false; - static_cast<WebStateImpl*>(web_state.get()) - ->ExecuteJavaScript(u"0;", base::BindOnce(^(const base::Value* res) { - called = true; - })); + CRWWebController* web_controller = + static_cast<WebStateImpl*>(web_state.get())->GetWebController(); + [web_controller executeJavaScript:@"0;" + completionHandler:^(id, NSError*) { + called = true; + }]; EXPECT_TRUE(WaitUntilConditionOrTimeout(kWaitForPageLoadTimeout, ^{ return called; }));
diff --git a/ios/web_view/internal/cwv_web_view.mm b/ios/web_view/internal/cwv_web_view.mm index acb7ae08..e3f8f12d 100644 --- a/ios/web_view/internal/cwv_web_view.mm +++ b/ios/web_view/internal/cwv_web_view.mm
@@ -29,7 +29,6 @@ #import "ios/components/security_interstitials/safe_browsing/safe_browsing_query_manager.h" #import "ios/components/security_interstitials/safe_browsing/safe_browsing_tab_helper.h" #import "ios/components/security_interstitials/safe_browsing/safe_browsing_unsafe_resource_container.h" -#import "ios/web/public/deprecated/crw_js_injection_receiver.h" #include "ios/web/public/favicon/favicon_url.h" #include "ios/web/public/js_messaging/web_frame.h" #import "ios/web/public/js_messaging/web_frame_util.h"
diff --git a/media/base/decoder_buffer.h b/media/base/decoder_buffer.h index 6056e26..f1af93b 100644 --- a/media/base/decoder_buffer.h +++ b/media/base/decoder_buffer.h
@@ -9,6 +9,7 @@ #include <stdint.h> #include <memory> +#include <ostream> #include <string> #include <utility>
diff --git a/media/base/status_unittest.cc b/media/base/status_unittest.cc index e514047d..ed223b8 100644 --- a/media/base/status_unittest.cc +++ b/media/base/status_unittest.cc
@@ -260,85 +260,92 @@ TEST_F(StatusTest, SingleLayerError) { NormalStatus failed = FailEasily(); base::Value actual = MediaSerialize(failed); + const base::Value::Dict& actual_dict = actual.GetDict(); + ASSERT_EQ(actual_dict.size(), 5ul); + ASSERT_EQ(*actual_dict.FindString("message"), "Message"); + ASSERT_EQ(actual_dict.FindList("stack")->size(), 1ul); + ASSERT_EQ(actual_dict.Find("cause"), nullptr); + ASSERT_EQ(actual_dict.FindDict("data")->size(), 0ul); - ASSERT_EQ(actual.DictSize(), 5ul); - ASSERT_EQ(*actual.FindStringPath("message"), "Message"); - ASSERT_EQ(actual.FindListPath("stack")->GetListDeprecated().size(), 1ul); - ASSERT_EQ(actual.FindKey("cause"), nullptr); - ASSERT_EQ(actual.FindDictPath("data")->DictSize(), 0ul); - - const auto& stack = actual.FindListPath("stack")->GetListDeprecated(); - ASSERT_EQ(stack[0].DictSize(), 2ul); // line and file + const auto& stack = *actual_dict.FindList("stack"); + ASSERT_EQ(stack[0].GetDict().size(), 2ul); // line and file // This is a bit fragile, since it's dependent on the file layout. Just check // that it's somewhere in the `FailEasily`` function. - int line = stack[0].FindIntPath("line").value_or(-1); + int line = stack[0].GetDict().FindInt("line").value_or(-1); ASSERT_GT(line, lower_line_limit_); ASSERT_LT(line, upper_line_limit_); - ASSERT_THAT(*stack[0].FindStringPath("file"), + ASSERT_THAT(*stack[0].GetDict().FindString("file"), HasSubstr("status_unittest.cc")); } TEST_F(StatusTest, MultipleErrorLayer) { NormalStatus failed = FailRecursively(3); base::Value actual = MediaSerialize(failed); - ASSERT_EQ(actual.DictSize(), 5ul); - ASSERT_EQ(*actual.FindStringPath("message"), "Message"); - ASSERT_EQ(actual.FindListPath("stack")->GetListDeprecated().size(), 4ul); - ASSERT_EQ(actual.FindKey("cause"), nullptr); - ASSERT_EQ(actual.FindDictPath("data")->DictSize(), 0ul); + const base::Value::Dict& actual_dict = actual.GetDict(); + ASSERT_EQ(actual_dict.size(), 5ul); + ASSERT_EQ(*actual_dict.FindString("message"), "Message"); + ASSERT_EQ(actual_dict.FindList("stack")->size(), 4ul); + ASSERT_EQ(actual_dict.Find("cause"), nullptr); + ASSERT_EQ(actual_dict.FindDict("data")->size(), 0ul); - const auto& stack = actual.FindListPath("stack")->GetListDeprecated(); - ASSERT_EQ(stack[0].DictSize(), 2ul); // line and file + const auto& stack = *actual_dict.FindList("stack"); + ; + ASSERT_EQ(stack[0].GetDict().size(), 2ul); // line and file } TEST_F(StatusTest, CanHaveData) { NormalStatus failed = FailWithData("example", "data"); base::Value actual = MediaSerialize(failed); - ASSERT_EQ(actual.DictSize(), 5ul); - ASSERT_EQ(*actual.FindStringPath("message"), "Message"); - ASSERT_EQ(actual.FindListPath("stack")->GetListDeprecated().size(), 1ul); - ASSERT_EQ(actual.FindKey("cause"), nullptr); - ASSERT_EQ(actual.FindDictPath("data")->DictSize(), 1ul); + const base::Value::Dict& actual_dict = actual.GetDict(); + ASSERT_EQ(actual_dict.size(), 5ul); + ASSERT_EQ(*actual_dict.FindString("message"), "Message"); + ASSERT_EQ(actual_dict.FindList("stack")->size(), 1ul); + ASSERT_EQ(actual_dict.Find("cause"), nullptr); + ASSERT_EQ(actual_dict.FindDict("data")->size(), 1ul); - const auto& stack = actual.FindListPath("stack")->GetListDeprecated(); - ASSERT_EQ(stack[0].DictSize(), 2ul); // line and file + const auto& stack = *actual_dict.FindList("stack"); + ; + ASSERT_EQ(stack[0].GetDict().size(), 2ul); // line and file - ASSERT_EQ(*actual.FindDictPath("data")->FindStringPath("example"), "data"); + ASSERT_EQ(*actual_dict.FindDict("data")->FindString("example"), "data"); } TEST_F(StatusTest, CanUseCustomSerializer) { NormalStatus failed = FailWithData("example", UselessThingToBeSerialized("F")); base::Value actual = MediaSerialize(failed); - ASSERT_EQ(actual.DictSize(), 5ul); - ASSERT_EQ(*actual.FindStringPath("message"), "Message"); - ASSERT_EQ(actual.FindListPath("stack")->GetListDeprecated().size(), 1ul); - ASSERT_EQ(actual.FindKey("cause"), nullptr); - ASSERT_EQ(actual.FindDictPath("data")->DictSize(), 1ul); + const base::Value::Dict& actual_dict = actual.GetDict(); + ASSERT_EQ(actual_dict.size(), 5ul); + ASSERT_EQ(*actual_dict.FindString("message"), "Message"); + ASSERT_EQ(actual_dict.FindList("stack")->size(), 1ul); + ASSERT_EQ(actual_dict.Find("cause"), nullptr); + ASSERT_EQ(actual_dict.FindDict("data")->size(), 1ul); - const auto& stack = actual.FindListPath("stack")->GetListDeprecated(); - ASSERT_EQ(stack[0].DictSize(), 2ul); // line and file + const auto& stack = *actual_dict.FindList("stack"); + ; + ASSERT_EQ(stack[0].GetDict().size(), 2ul); // line and file - ASSERT_EQ(*actual.FindDictPath("data")->FindStringPath("example"), "F"); + ASSERT_EQ(*actual_dict.FindDict("data")->FindString("example"), "F"); } TEST_F(StatusTest, CausedByHasVector) { NormalStatus causal = FailWithCause(); base::Value actual = MediaSerialize(causal); - ASSERT_EQ(actual.DictSize(), 6ul); - ASSERT_EQ(*actual.FindStringPath("message"), "Message"); - ASSERT_EQ(actual.FindListPath("stack")->GetListDeprecated().size(), 1ul); - ASSERT_EQ(actual.FindDictPath("data")->DictSize(), 0ul); - ASSERT_NE(actual.FindKey("cause"), nullptr); + const base::Value::Dict& actual_dict = actual.GetDict(); + ASSERT_EQ(actual_dict.size(), 6ul); + ASSERT_EQ(*actual_dict.FindString("message"), "Message"); + ASSERT_EQ(actual_dict.FindList("stack")->size(), 1ul); + ASSERT_EQ(actual_dict.FindDict("data")->size(), 0ul); + ASSERT_NE(actual_dict.Find("cause"), nullptr); - base::Value* nested = actual.FindDictPath("cause"); + const base::Value::Dict* nested = actual_dict.FindDict("cause"); ASSERT_NE(nested, nullptr); - ASSERT_EQ(nested->DictSize(), 5ul); - ASSERT_EQ(*nested->FindStringPath("message"), "Message"); - ASSERT_EQ(nested->FindListPath("stack")->GetListDeprecated().size(), 1ul); - ASSERT_EQ(nested->FindKey("cause"), nullptr); - ASSERT_EQ(nested->FindDictPath("data")->DictSize(), 0ul); + ASSERT_EQ(nested->size(), 5ul); + ASSERT_EQ(*nested->FindString("message"), "Message"); + ASSERT_EQ(nested->FindList("stack")->size(), 1ul); + ASSERT_EQ(nested->Find("cause"), nullptr); + ASSERT_EQ(nested->FindDict("data")->size(), 0ul); } TEST_F(StatusTest, CausedByCanAssignCopy) { @@ -347,19 +354,20 @@ base::Value causal_serialized = MediaSerialize(causal); base::Value copy_causal_serialized = MediaSerialize(copy_causal); - base::Value* original = causal_serialized.FindDictPath("cause"); - ASSERT_EQ(original->DictSize(), 5ul); - ASSERT_EQ(*original->FindStringPath("message"), "Message"); - ASSERT_EQ(original->FindListPath("stack")->GetListDeprecated().size(), 1ul); - ASSERT_EQ(original->FindKey("cause"), nullptr); - ASSERT_EQ(original->FindDictPath("data")->DictSize(), 0ul); + base::Value::Dict* original = causal_serialized.GetDict().FindDict("cause"); + ASSERT_EQ(original->size(), 5ul); + ASSERT_EQ(*original->FindString("message"), "Message"); + ASSERT_EQ(original->FindList("stack")->size(), 1ul); + ASSERT_EQ(original->Find("cause"), nullptr); + ASSERT_EQ(original->FindDict("data")->size(), 0ul); - base::Value* copied = copy_causal_serialized.FindDictPath("cause"); - ASSERT_EQ(copied->DictSize(), 5ul); - ASSERT_EQ(*copied->FindStringPath("message"), "Message"); - ASSERT_EQ(copied->FindListPath("stack")->GetListDeprecated().size(), 1ul); - ASSERT_EQ(copied->FindKey("cause"), nullptr); - ASSERT_EQ(copied->FindDictPath("data")->DictSize(), 0ul); + base::Value::Dict* copied = + copy_causal_serialized.GetDict().FindDict("cause"); + ASSERT_EQ(copied->size(), 5ul); + ASSERT_EQ(*copied->FindString("message"), "Message"); + ASSERT_EQ(copied->FindList("stack")->size(), 1ul); + ASSERT_EQ(copied->Find("cause"), nullptr); + ASSERT_EQ(copied->FindDict("data")->size(), 0ul); } TEST_F(StatusTest, CanCopyEasily) { @@ -367,18 +375,19 @@ NormalStatus withData = DoSomethingGiveItBack(failed); base::Value actual = MediaSerialize(failed); - ASSERT_EQ(actual.DictSize(), 5ul); - ASSERT_EQ(*actual.FindStringPath("message"), "Message"); - ASSERT_EQ(actual.FindListPath("stack")->GetListDeprecated().size(), 1ul); - ASSERT_EQ(actual.FindKey("cause"), nullptr); - ASSERT_EQ(actual.FindDictPath("data")->DictSize(), 0ul); + const base::Value::Dict& actual_dict = actual.GetDict(); + ASSERT_EQ(actual_dict.size(), 5ul); + ASSERT_EQ(*actual_dict.FindString("message"), "Message"); + ASSERT_EQ(actual_dict.FindList("stack")->size(), 1ul); + ASSERT_EQ(actual_dict.Find("cause"), nullptr); + ASSERT_EQ(actual_dict.FindDict("data")->size(), 0ul); actual = MediaSerialize(withData); - ASSERT_EQ(actual.DictSize(), 5ul); - ASSERT_EQ(*actual.FindStringPath("message"), "Message"); - ASSERT_EQ(actual.FindListPath("stack")->GetListDeprecated().size(), 1ul); - ASSERT_EQ(actual.FindKey("cause"), nullptr); - ASSERT_EQ(actual.FindDictPath("data")->DictSize(), 1ul); + ASSERT_EQ(actual_dict.size(), 5ul); + ASSERT_EQ(*actual_dict.FindString("message"), "Message"); + ASSERT_EQ(actual_dict.FindList("stack")->size(), 1ul); + ASSERT_EQ(actual_dict.Find("cause"), nullptr); + ASSERT_EQ(actual_dict.FindDict("data")->size(), 1ul); } TEST_F(StatusTest, StatusOrTypicalUsage) {
diff --git a/media/base/test_data_util.cc b/media/base/test_data_util.cc index bdb5b3e..8f0aa3e5 100644 --- a/media/base/test_data_util.cc +++ b/media/base/test_data_util.cc
@@ -5,6 +5,7 @@ #include "media/base/test_data_util.h" #include <stdint.h> +#include <ostream> #include "base/check_op.h" #include "base/containers/flat_map.h"
diff --git a/media/cdm/cdm_host_files.cc b/media/cdm/cdm_host_files.cc index 54a3180e..a2cea641 100644 --- a/media/cdm/cdm_host_files.cc +++ b/media/cdm/cdm_host_files.cc
@@ -84,16 +84,16 @@ // Call |init_verification_func| on the CDM with |cdm_host_files|. Note that // the ownership of these files are transferred to the CDM, which will close // the files immediately after use. - DVLOG(1) << __func__ << ": Calling " << kInitVerificationFuncName - << "() with " << cdm_host_files.size() << " files."; + VLOG(1) << __func__ << ": Calling " << kInitVerificationFuncName << "() with " + << cdm_host_files.size() << " files."; for (const auto& host_file : cdm_host_files) { - DVLOG(1) << " - File Path: " << host_file.file_path; - DVLOG(1) << " - File: " << host_file.file; - DVLOG(1) << " - Sig File: " << host_file.sig_file; + VLOG(1) << " - File Path: " << host_file.file_path; + VLOG(1) << " - File: " << host_file.file; + VLOG(1) << " - Sig File: " << host_file.sig_file; } if (!init_verification_func(cdm_host_files_ptr, cdm_host_files.size())) { - DVLOG(1) << "Failed to verify CDM host."; + LOG(ERROR) << "Failed to verify CDM host."; CloseAllFiles(); return Status::kInitVerificationFailed; }
diff --git a/media/cdm/json_web_key.cc b/media/cdm/json_web_key.cc index cd5a045..e2e1784 100644 --- a/media/cdm/json_web_key.cc +++ b/media/cdm/json_web_key.cc
@@ -244,7 +244,7 @@ } // Locate the set from the dictionary. - const base::Value* list_val = root->FindListKey(kKeyIdsTag); + const base::Value::List* list_val = root->GetDict().FindList(kKeyIdsTag); if (!list_val) { error_message->assign("Missing '"); error_message->append(kKeyIdsTag); @@ -255,9 +255,8 @@ // Create a local list of key ids, so that |key_ids| only gets updated on // success. KeyIdList local_key_ids; - base::Value::ConstListView list_val_view = list_val->GetListDeprecated(); - for (size_t i = 0; i < list_val_view.size(); ++i) { - const std::string* encoded_key_id = list_val_view[i].GetIfString(); + for (size_t i = 0; i < list_val->size(); ++i) { + const std::string* encoded_key_id = (*list_val)[i].GetIfString(); if (!encoded_key_id) { error_message->assign("'"); error_message->append(kKeyIdsTag); @@ -393,20 +392,19 @@ } // Locate the set from the dictionary. - const base::Value* list_val = root->FindListKey(kKeyIdsTag); + const base::Value::List* list_val = root->GetDict().FindList(kKeyIdsTag); if (!list_val) { DVLOG(1) << "Missing '" << kKeyIdsTag << "' parameter or not a list"; return false; } // Get the first key. - if (list_val->GetListDeprecated().size() < 1) { + if (list_val->size() < 1) { DVLOG(1) << "Empty '" << kKeyIdsTag << "' list"; return false; } - const std::string* encoded_key = - list_val->GetListDeprecated()[0].GetIfString(); + const std::string* encoded_key = (*list_val)[0].GetIfString(); if (!encoded_key) { DVLOG(1) << "First entry in '" << kKeyIdsTag << "' not a string"; return false;
diff --git a/media/fuchsia/cdm/client/BUILD.gn b/media/fuchsia/cdm/client/BUILD.gn index bafc1ac4..aff0be0 100644 --- a/media/fuchsia/cdm/client/BUILD.gn +++ b/media/fuchsia/cdm/client/BUILD.gn
@@ -14,7 +14,7 @@ deps = [ "//media", - "//media/fuchsia/mojom:fuchsia_media_resource_provider", + "//media/fuchsia/mojom:fuchsia_media", "//third_party/blink/public:blink_headers", ] }
diff --git a/media/fuchsia/cdm/client/mojo_fuchsia_cdm_provider.cc b/media/fuchsia/cdm/client/mojo_fuchsia_cdm_provider.cc index 143e1b4..67ac256 100644 --- a/media/fuchsia/cdm/client/mojo_fuchsia_cdm_provider.cc +++ b/media/fuchsia/cdm/client/mojo_fuchsia_cdm_provider.cc
@@ -20,12 +20,11 @@ const std::string& key_system, fidl::InterfaceRequest<fuchsia::media::drm::ContentDecryptionModule> cdm_request) { - if (!media_resource_provider_) { - interface_broker_->GetInterface( - media_resource_provider_.BindNewPipeAndPassReceiver()); + if (!cdm_provider_) { + interface_broker_->GetInterface(cdm_provider_.BindNewPipeAndPassReceiver()); } - media_resource_provider_->CreateCdm(key_system, std::move(cdm_request)); + cdm_provider_->CreateCdm(key_system, std::move(cdm_request)); } } // namespace media
diff --git a/media/fuchsia/cdm/client/mojo_fuchsia_cdm_provider.h b/media/fuchsia/cdm/client/mojo_fuchsia_cdm_provider.h index 90a888b67..b35ff20 100644 --- a/media/fuchsia/cdm/client/mojo_fuchsia_cdm_provider.h +++ b/media/fuchsia/cdm/client/mojo_fuchsia_cdm_provider.h
@@ -6,7 +6,7 @@ #define MEDIA_FUCHSIA_CDM_CLIENT_MOJO_FUCHSIA_CDM_PROVIDER_H_ #include "media/fuchsia/cdm/fuchsia_cdm_provider.h" -#include "media/fuchsia/mojom/fuchsia_media_resource_provider.mojom.h" +#include "media/fuchsia/mojom/fuchsia_media.mojom.h" #include "mojo/public/cpp/bindings/remote.h" namespace blink { @@ -34,8 +34,7 @@ private: blink::BrowserInterfaceBrokerProxy* const interface_broker_; - mojo::Remote<media::mojom::FuchsiaMediaResourceProvider> - media_resource_provider_; + mojo::Remote<media::mojom::FuchsiaMediaCdmProvider> cdm_provider_; }; } // namespace media
diff --git a/media/fuchsia/mojom/BUILD.gn b/media/fuchsia/mojom/BUILD.gn index dc0073f..5c537183 100644 --- a/media/fuchsia/mojom/BUILD.gn +++ b/media/fuchsia/mojom/BUILD.gn
@@ -4,8 +4,8 @@ import("//mojo/public/tools/bindings/mojom.gni") -mojom("fuchsia_media_resource_provider") { - sources = [ "fuchsia_media_resource_provider.mojom" ] +mojom("fuchsia_media") { + sources = [ "fuchsia_media.mojom" ] deps = [ "//media/mojo/mojom" ] export_class_attribute_blink = "BLINK_PLATFORM_EXPORT" @@ -25,7 +25,7 @@ move_only = true }, ] - traits_headers = [ "fuchsia_media_resource_provider_mojom_traits.h" ] + traits_headers = [ "fuchsia_media_mojom_traits.h" ] traits_public_deps = [ "//mojo/public/cpp/base/fuchsia:traits", "//third_party/fuchsia-sdk/sdk/fidl/fuchsia.media",
diff --git a/media/fuchsia/mojom/DEPS b/media/fuchsia/mojom/DEPS index 5222e05..777ac6a 100644 --- a/media/fuchsia/mojom/DEPS +++ b/media/fuchsia/mojom/DEPS
@@ -1,5 +1,5 @@ specific_include_rules = { - "fuchsia_.*_provider_mojom_traits\.h": [ + "fuchsia_.*_mojom_traits\.h": [ "+mojo/public/cpp/base/fuchsia/fidl_interface_request_mojom_traits.h", ], }
diff --git a/media/fuchsia/mojom/fuchsia_media_resource_provider.mojom b/media/fuchsia/mojom/fuchsia_media.mojom similarity index 97% rename from media/fuchsia/mojom/fuchsia_media_resource_provider.mojom rename to media/fuchsia/mojom/fuchsia_media.mojom index d743a90..2434ac8 100644 --- a/media/fuchsia/mojom/fuchsia_media_resource_provider.mojom +++ b/media/fuchsia/mojom/fuchsia_media.mojom
@@ -32,7 +32,7 @@ // Interface used by the renderer to connect to CDM and mediacodec resources. // Instances are document-scoped. -interface FuchsiaMediaResourceProvider { +interface FuchsiaMediaCdmProvider { // Create connection to fuchsia::media::drm::ContentDecryptionModule for // `key_system`. Implementation should make sure the persistent storage is // isolated per web origin.
diff --git a/media/fuchsia/mojom/fuchsia_media_resource_provider_mojom_traits.h b/media/fuchsia/mojom/fuchsia_media_mojom_traits.h similarity index 80% rename from media/fuchsia/mojom/fuchsia_media_resource_provider_mojom_traits.h rename to media/fuchsia/mojom/fuchsia_media_mojom_traits.h index 8a32bd8..39a9095 100644 --- a/media/fuchsia/mojom/fuchsia_media_resource_provider_mojom_traits.h +++ b/media/fuchsia/mojom/fuchsia_media_mojom_traits.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef MEDIA_FUCHSIA_MOJOM_FUCHSIA_MEDIA_RESOURCE_PROVIDER_MOJOM_TRAITS_H_ -#define MEDIA_FUCHSIA_MOJOM_FUCHSIA_MEDIA_RESOURCE_PROVIDER_MOJOM_TRAITS_H_ +#ifndef MEDIA_FUCHSIA_MOJOM_FUCHSIA_MEDIA_MOJOM_TRAITS_H_ +#define MEDIA_FUCHSIA_MOJOM_FUCHSIA_MEDIA_MOJOM_TRAITS_H_ #include <fuchsia/media/cpp/fidl.h> #include <fuchsia/media/drm/cpp/fidl.h> @@ -29,4 +29,4 @@ } // namespace mojo -#endif // MEDIA_FUCHSIA_MOJOM_FUCHSIA_MEDIA_RESOURCE_PROVIDER_MOJOM_TRAITS_H_ +#endif // MEDIA_FUCHSIA_MOJOM_FUCHSIA_MEDIA_MOJOM_TRAITS_H_
diff --git a/media/fuchsia/video/BUILD.gn b/media/fuchsia/video/BUILD.gn index f19b31c..4e2bcd09 100644 --- a/media/fuchsia/video/BUILD.gn +++ b/media/fuchsia/video/BUILD.gn
@@ -25,7 +25,7 @@ "//base", "//media", "//media/fuchsia/common", - "//media/fuchsia/mojom:fuchsia_media_resource_provider", + "//media/fuchsia/mojom:fuchsia_media", "//mojo/public/cpp/bindings", "//third_party/fuchsia-sdk/sdk/fidl/fuchsia.media", "//third_party/fuchsia-sdk/sdk/fidl/fuchsia.mediacodec", @@ -57,7 +57,7 @@ "//gpu/command_buffer/client", "//gpu/config", "//media:test_support", - "//media/fuchsia/mojom:fuchsia_media_resource_provider", + "//media/fuchsia/mojom:fuchsia_media", "//testing/gmock", "//testing/gtest", "//third_party/blink/public/common",
diff --git a/media/fuchsia/video/fuchsia_decoder_factory.h b/media/fuchsia/video/fuchsia_decoder_factory.h index adfc2a5..7c28e9e 100644 --- a/media/fuchsia/video/fuchsia_decoder_factory.h +++ b/media/fuchsia/video/fuchsia_decoder_factory.h
@@ -6,7 +6,7 @@ #define MEDIA_FUCHSIA_VIDEO_FUCHSIA_DECODER_FACTORY_H_ #include "media/base/decoder_factory.h" -#include "media/fuchsia/mojom/fuchsia_media_resource_provider.mojom.h" +#include "media/fuchsia/mojom/fuchsia_media.mojom.h" #include "mojo/public/cpp/bindings/shared_remote.h" namespace media { @@ -17,7 +17,7 @@ mojo::PendingRemote<media::mojom::FuchsiaMediaCodecProvider> resource_provider, bool allow_overlays); - ~FuchsiaDecoderFactory() final; + ~FuchsiaDecoderFactory() override; // DecoderFactory implementation. void CreateAudioDecoders(
diff --git a/media/fuchsia/video/fuchsia_video_decoder.cc b/media/fuchsia/video/fuchsia_video_decoder.cc index 103d6dd4..5800696 100644 --- a/media/fuchsia/video/fuchsia_video_decoder.cc +++ b/media/fuchsia/video/fuchsia_video_decoder.cc
@@ -33,7 +33,7 @@ #include "media/fuchsia/common/decrypting_sysmem_buffer_stream.h" #include "media/fuchsia/common/passthrough_sysmem_buffer_stream.h" #include "media/fuchsia/common/stream_processor_helper.h" -#include "media/fuchsia/mojom/fuchsia_media_resource_provider.mojom.h" +#include "media/fuchsia/mojom/fuchsia_media.mojom.h" #include "ui/gfx/buffer_types.h" #include "ui/gfx/client_native_pixmap_factory.h" #include "ui/ozone/public/client_native_pixmap_factory_ozone.h"
diff --git a/media/fuchsia/video/fuchsia_video_decoder.h b/media/fuchsia/video/fuchsia_video_decoder.h index f116dca..f746da7f 100644 --- a/media/fuchsia/video/fuchsia_video_decoder.h +++ b/media/fuchsia/video/fuchsia_video_decoder.h
@@ -18,7 +18,7 @@ #include "media/base/video_decoder_config.h" #include "media/fuchsia/common/sysmem_buffer_stream.h" #include "media/fuchsia/common/sysmem_client.h" -#include "media/fuchsia/mojom/fuchsia_media_resource_provider.mojom.h" +#include "media/fuchsia/mojom/fuchsia_media.mojom.h" #include "mojo/public/cpp/bindings/shared_remote.h" namespace gfx {
diff --git a/media/fuchsia/video/fuchsia_video_decoder_unittest.cc b/media/fuchsia/video/fuchsia_video_decoder_unittest.cc index 99a1c74..c97ff12 100644 --- a/media/fuchsia/video/fuchsia_video_decoder_unittest.cc +++ b/media/fuchsia/video/fuchsia_video_decoder_unittest.cc
@@ -29,7 +29,7 @@ #include "media/base/test_helpers.h" #include "media/base/video_decoder.h" #include "media/base/video_frame.h" -#include "media/fuchsia/mojom/fuchsia_media_resource_provider.mojom.h" +#include "media/fuchsia/mojom/fuchsia_media.mojom.h" #include "mojo/public/cpp/bindings/receiver.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/client_native_pixmap_factory.h" @@ -341,7 +341,7 @@ } void GetSupportedVideoDecoderConfigs( - GetSupportedVideoDecoderConfigsCallback callback) final { + GetSupportedVideoDecoderConfigsCallback callback) override { ADD_FAILURE(); }
diff --git a/media/gpu/test/image.cc b/media/gpu/test/image.cc index 469b9fd..6f3734c 100644 --- a/media/gpu/test/image.cc +++ b/media/gpu/test/image.cc
@@ -139,44 +139,41 @@ << metadata_result.error().message; return false; } - base::Value& metadata = *metadata_result; + const base::Value::Dict& metadata = metadata_result->GetDict(); // Get the pixel format from the json data. - const base::Value* pixel_format = - metadata.FindKeyOfType("pixel_format", base::Value::Type::STRING); + const std::string* pixel_format = metadata.FindString("pixel_format"); if (!pixel_format) { VLOGF(1) << "Key \"pixel_format\" is not found in " << json_path; return false; } - pixel_format_ = ConvertStringtoPixelFormat(pixel_format->GetString()); + pixel_format_ = ConvertStringtoPixelFormat(*pixel_format); if (pixel_format_ == PIXEL_FORMAT_UNKNOWN) { - VLOGF(1) << pixel_format->GetString() << " is not supported"; + VLOGF(1) << *pixel_format << " is not supported"; return false; } // Get the image dimensions from the json data. - const base::Value* width = - metadata.FindKeyOfType("width", base::Value::Type::INTEGER); - if (!width) { + absl::optional<int> width = metadata.FindInt("width"); + if (!width.has_value()) { VLOGF(1) << "Key \"width\" is not found in " << json_path; return false; } - const base::Value* height = - metadata.FindKeyOfType("height", base::Value::Type::INTEGER); + absl::optional<int> height = metadata.FindInt("height"); if (!height) { VLOGF(1) << "Key \"height\" is not found in " << json_path; return false; } - size_ = gfx::Size(width->GetInt(), height->GetInt()); + size_ = gfx::Size(*width, *height); // Try to get the visible rectangle of the image from the json data. // These values are not in json data if all the image data is in the visible // area. visible_rect_ = gfx::Rect(size_); - const base::Value* visible_rect_info = - metadata.FindKeyOfType("visible_rect", base::Value::Type::LIST); + const base::Value::List* visible_rect_info = + metadata.FindList("visible_rect"); if (visible_rect_info) { - base::Value::ConstListView values = visible_rect_info->GetListDeprecated(); + const base::Value::List& values = *visible_rect_info; if (values.size() != 4) { VLOGF(1) << "unexpected json format for visible rectangle"; return false; @@ -190,13 +187,12 @@ } // Get the image rotation info from the json data. - const base::Value* rotation = - metadata.FindKeyOfType("rotation", base::Value::Type::INTEGER); - if (!rotation) { + absl::optional<int> rotation = metadata.FindInt("rotation"); + if (!rotation.has_value()) { // Default rotation value is VIDEO_ROTATION_0 rotation_ = VIDEO_ROTATION_0; } else { - switch (rotation->GetInt()) { + switch (*rotation) { case 0: rotation_ = VIDEO_ROTATION_0; break; @@ -210,19 +206,18 @@ rotation_ = VIDEO_ROTATION_270; break; default: - VLOGF(1) << "Invalid rotation value: " << rotation->GetInt(); + VLOGF(1) << "Invalid rotation value: " << *rotation; return false; }; } // Get the image checksum from the json data. - const base::Value* checksum = - metadata.FindKeyOfType("checksum", base::Value::Type::STRING); + const std::string* checksum = metadata.FindString("checksum"); if (!checksum) { VLOGF(1) << "Key \"checksum\" is not found in " << json_path; return false; } - checksum_ = checksum->GetString(); + checksum_ = *checksum; return true; }
diff --git a/media/gpu/test/video.cc b/media/gpu/test/video.cc index 1dc0c46..d3943b4 100644 --- a/media/gpu/test/video.cc +++ b/media/gpu/test/video.cc
@@ -369,23 +369,22 @@ << ": " << metadata_result.error().message; return false; } - base::Value& metadata = *metadata_result; + base::Value::Dict& metadata = metadata_result->GetDict(); // Find the video's profile, only required for encoded video streams. profile_ = VIDEO_CODEC_PROFILE_UNKNOWN; - const base::Value* profile = - metadata.FindKeyOfType("profile", base::Value::Type::STRING); + const std::string* profile = metadata.FindString("profile"); if (profile) { - auto converted_profile = ConvertStringtoProfile(profile->GetString()); + auto converted_profile = ConvertStringtoProfile(*profile); if (!converted_profile) { - LOG(ERROR) << profile->GetString() << " is not supported"; + LOG(ERROR) << *profile << " is not supported"; return false; } profile_ = converted_profile.value(); auto converted_codec = ConvertProfileToCodec(profile_); if (!converted_codec) { - LOG(ERROR) << profile->GetString() << " is not supported"; + LOG(ERROR) << *profile << " is not supported"; return false; } codec_ = converted_codec.value(); @@ -393,10 +392,9 @@ // Find the video's bit depth. This is optional and only required for encoded // video streams. - const base::Value* bit_depth = - metadata.FindKeyOfType("bit_depth", base::Value::Type::INTEGER); - if (bit_depth) { - bit_depth_ = base::checked_cast<uint8_t>(bit_depth->GetInt()); + absl::optional<int> bit_depth = metadata.FindInt("bit_depth"); + if (bit_depth.has_value()) { + bit_depth_ = base::checked_cast<uint8_t>(*bit_depth); } else { if (profile_ == VP9PROFILE_PROFILE2) { LOG(ERROR) << "Bit depth is unspecified for VP9 profile 2"; @@ -408,13 +406,11 @@ // Find the video's pixel format, only required for raw video streams. pixel_format_ = VideoPixelFormat::PIXEL_FORMAT_UNKNOWN; - const base::Value* pixel_format = - metadata.FindKeyOfType("pixel_format", base::Value::Type::STRING); + const std::string* pixel_format = metadata.FindString("pixel_format"); if (pixel_format) { - auto converted_pixel_format = - ConvertStringtoPixelFormat(pixel_format->GetString()); + auto converted_pixel_format = ConvertStringtoPixelFormat(*pixel_format); if (!converted_pixel_format) { - LOG(ERROR) << pixel_format->GetString() << " is not supported"; + LOG(ERROR) << *pixel_format << " is not supported"; return false; } pixel_format_ = converted_pixel_format.value(); @@ -433,61 +429,55 @@ return false; } - const base::Value* frame_rate = - metadata.FindKeyOfType("frame_rate", base::Value::Type::INTEGER); - if (!frame_rate) { + absl::optional<int> frame_rate = metadata.FindInt("frame_rate"); + if (!frame_rate.has_value()) { LOG(ERROR) << "Key \"frame_rate\" is not found in " << metadata_file_path_; return false; } - frame_rate_ = static_cast<uint32_t>(frame_rate->GetInt()); + frame_rate_ = static_cast<uint32_t>(*frame_rate); - const base::Value* num_frames = - metadata.FindKeyOfType("num_frames", base::Value::Type::INTEGER); - if (!num_frames) { + absl::optional<int> num_frames = metadata.FindInt("num_frames"); + if (!num_frames.has_value()) { LOG(ERROR) << "Key \"num_frames\" is not found in " << metadata_file_path_; return false; } - num_frames_ = static_cast<uint32_t>(num_frames->GetInt()); + num_frames_ = static_cast<uint32_t>(*num_frames); // Find the number of fragments, only required for H.264/HEVC video streams. num_fragments_ = num_frames_; if ((profile_ >= H264PROFILE_MIN && profile_ <= H264PROFILE_MAX) || (profile_ >= HEVCPROFILE_MIN && profile_ <= HEVCPROFILE_MAX)) { - const base::Value* num_fragments = - metadata.FindKeyOfType("num_fragments", base::Value::Type::INTEGER); - if (!num_fragments) { + absl::optional<int> num_fragments = metadata.FindInt("num_fragments"); + if (!num_fragments.has_value()) { LOG(ERROR) << "Key \"num_fragments\" is required for H.264/HEVC video " "streams but could not be found in " << metadata_file_path_; return false; } - num_fragments_ = static_cast<uint32_t>(num_fragments->GetInt()); + num_fragments_ = static_cast<uint32_t>(*num_fragments); } - const base::Value* width = - metadata.FindKeyOfType("width", base::Value::Type::INTEGER); - if (!width) { + absl::optional<int> width = metadata.FindInt("width"); + if (!width.has_value()) { LOG(ERROR) << "Key \"width\" is not found in " << metadata_file_path_; return false; } - const base::Value* height = - metadata.FindKeyOfType("height", base::Value::Type::INTEGER); + absl::optional<int> height = metadata.FindInt("height"); if (!height) { LOG(ERROR) << "Key \"height\" is not found in " << metadata_file_path_; return false; } - resolution_ = gfx::Size(static_cast<uint32_t>(width->GetInt()), - static_cast<uint32_t>(height->GetInt())); + resolution_ = + gfx::Size(static_cast<uint32_t>(*width), static_cast<uint32_t>(*height)); // The default visible rectangle is (0, 0, |resolution_|). Expand() needs to // be called to change the visible rectangle. visible_rect_ = gfx::Rect(resolution_); // Find optional frame checksums. These are only required when using the frame // validator. - const base::Value* md5_checksums = - metadata.FindKeyOfType("md5_checksums", base::Value::Type::LIST); + const base::Value::List* md5_checksums = metadata.FindList("md5_checksums"); if (md5_checksums) { - for (const base::Value& checksum : md5_checksums->GetListDeprecated()) { + for (const base::Value& checksum : *md5_checksums) { frame_checksums_.push_back(checksum.GetString()); } }
diff --git a/net/cert/internal/system_trust_store.cc b/net/cert/internal/system_trust_store.cc index 1ebd921..5691c40 100644 --- a/net/cert/internal/system_trust_store.cc +++ b/net/cert/internal/system_trust_store.cc
@@ -389,8 +389,8 @@ std::unique_ptr<SystemTrustStore> CreateSslSystemTrustStoreChromeRoot( std::unique_ptr<TrustStoreChrome> chrome_root) { - return std::make_unique<SystemTrustStoreChrome>(std::move(chrome_root), - TrustStoreWin::Create()); + return std::make_unique<SystemTrustStoreChrome>( + std::move(chrome_root), std::make_unique<TrustStoreWin>()); } #endif // CHROME_ROOT_STORE_SUPPORTED
diff --git a/net/cert/internal/trust_store_win.cc b/net/cert/internal/trust_store_win.cc index 991a3a98..227edd4 100644 --- a/net/cert/internal/trust_store_win.cc +++ b/net/cert/internal/trust_store_win.cc
@@ -80,7 +80,7 @@ } // namespace // TODO(https://crbug.com/1239268): support CTLs. -std::unique_ptr<TrustStoreWin> TrustStoreWin::Create() { +TrustStoreWin::TrustStoreWin() { crypto::ScopedHCERTSTORE root_cert_store( CertOpenStore(CERT_STORE_PROV_COLLECTION, 0, NULL, 0, nullptr)); crypto::ScopedHCERTSTORE intermediate_cert_store( @@ -91,7 +91,7 @@ CertOpenStore(CERT_STORE_PROV_COLLECTION, 0, NULL, 0, nullptr)); if (!root_cert_store.get() || !intermediate_cert_store.get() || !all_certs_store.get() || !disallowed_cert_store.get()) { - return nullptr; + return; } // Add intermediate and root cert stores to the all_cert_store collection so @@ -101,11 +101,11 @@ if (!CertAddStoreToCollection(all_certs_store.get(), intermediate_cert_store.get(), /*dwUpdateFlags=*/0, /*dwPriority=*/0)) { - return nullptr; + return; } if (!CertAddStoreToCollection(all_certs_store.get(), root_cert_store.get(), /*dwUpdateFlags=*/0, /*dwPriority=*/0)) { - return nullptr; + return; } // Grab the user-added roots. @@ -167,9 +167,10 @@ PLOG(ERROR) << "Error enabling CERT_STORE_CTRL_AUTO_RESYNC"; } - return base::WrapUnique(new TrustStoreWin( - std::move(root_cert_store), std::move(intermediate_cert_store), - std::move(disallowed_cert_store), std::move(all_certs_store))); + root_cert_store_ = std::move(root_cert_store); + intermediate_cert_store_ = std::move(intermediate_cert_store); + disallowed_cert_store_ = std::move(disallowed_cert_store); + all_certs_store_ = std::move(all_certs_store); } std::unique_ptr<TrustStoreWin> TrustStoreWin::CreateForTesting( @@ -178,19 +179,15 @@ crypto::ScopedHCERTSTORE disallowed_cert_store) { crypto::ScopedHCERTSTORE all_certs_store( CertOpenStore(CERT_STORE_PROV_COLLECTION, 0, NULL, 0, nullptr)); - if (!root_cert_store.get() || !intermediate_cert_store.get() || - !all_certs_store.get() || !disallowed_cert_store.get()) { - return nullptr; - } - if (!CertAddStoreToCollection(all_certs_store.get(), - intermediate_cert_store.get(), - /*dwUpdateFlags=*/0, /*dwPriority=*/0)) { - return nullptr; + if (all_certs_store.get() && intermediate_cert_store.get()) { + CertAddStoreToCollection(all_certs_store.get(), + intermediate_cert_store.get(), + /*dwUpdateFlags=*/0, /*dwPriority=*/0); } - if (!CertAddStoreToCollection(all_certs_store.get(), root_cert_store.get(), - /*dwUpdateFlags=*/0, /*dwPriority=*/0)) { - return nullptr; + if (all_certs_store.get() && root_cert_store.get()) { + CertAddStoreToCollection(all_certs_store.get(), root_cert_store.get(), + /*dwUpdateFlags=*/0, /*dwPriority=*/0); } return base::WrapUnique(new TrustStoreWin( @@ -214,6 +211,10 @@ void TrustStoreWin::SyncGetIssuersOf(const ParsedCertificate* cert, ParsedCertificateList* issuers) { + if (!root_cert_store_.get() || !intermediate_cert_store_.get() || + !all_certs_store_.get() || !disallowed_cert_store_.get()) { + return; + } base::span<const uint8_t> issuer_span = cert->issuer_tlv().AsSpan(); CERT_NAME_BLOB cert_issuer_blob; @@ -269,6 +270,11 @@ CertificateTrust TrustStoreWin::GetTrust( const ParsedCertificate* cert, base::SupportsUserData* debug_data) const { + if (!root_cert_store_.get() || !intermediate_cert_store_.get() || + !all_certs_store_.get() || !disallowed_cert_store_.get()) { + return CertificateTrust::ForUnspecified(); + } + base::span<const uint8_t> cert_span = cert->der_cert().AsSpan(); base::SHA1Digest cert_hash = base::SHA1HashSpan(cert_span); CRYPT_HASH_BLOB cert_hash_blob;
diff --git a/net/cert/internal/trust_store_win.h b/net/cert/internal/trust_store_win.h index 3e1b5690..338c2a3 100644 --- a/net/cert/internal/trust_store_win.h +++ b/net/cert/internal/trust_store_win.h
@@ -19,14 +19,15 @@ // TODO(https://crbug.com/1239270): confirm this is thread safe. class NET_EXPORT TrustStoreWin : public TrustStore { public: + // Creates a TrustStoreWin by reading user settings from Windows system + // CertStores. If there are errors, will return a TrustStoreWin object + // that may not read all Windows system CertStores. + TrustStoreWin(); + ~TrustStoreWin() override; TrustStoreWin(const TrustStoreWin& other) = delete; TrustStoreWin& operator=(const TrustStoreWin& other) = delete; - // Creates a TrustStoreWin by reading user settings from Windows system - // CertStores. Returns nullptr on failure. - static std::unique_ptr<TrustStoreWin> Create(); - // Creates a TrustStoreWin for testing, which will treat `root_cert_store` // as if it's the source of truth for roots for `GetTrust, // and `intermediate_cert_store` as an extra store (in addition to
diff --git a/net/cert/internal/trust_store_win_unittest.cc b/net/cert/internal/trust_store_win_unittest.cc index c37b88b..c6f8e892 100644 --- a/net/cert/internal/trust_store_win_unittest.cc +++ b/net/cert/internal/trust_store_win_unittest.cc
@@ -118,6 +118,19 @@ std::move(disallowed_store)); } +TEST(TrustStoreWin, GetTrustInitializationError) { + // Simulate an initialization error by using null stores. + std::unique_ptr<TrustStoreWin> trust_store_win = + TrustStoreWin::CreateForTesting(crypto::ScopedHCERTSTORE(), + crypto::ScopedHCERTSTORE(), + crypto::ScopedHCERTSTORE()); + ASSERT_TRUE(trust_store_win); + auto parsed_cert = ParseCertFromFile(kMultiRootDByD); + CertificateTrust trust = + trust_store_win->GetTrust(parsed_cert.get(), nullptr); + EXPECT_EQ(CertificateTrustType::UNSPECIFIED, trust.type); +} + TEST(TrustStoreWin, GetTrust) { std::unique_ptr<TrustStoreWin> trust_store_win = CreateTrustStoreWin(); ASSERT_TRUE(trust_store_win); @@ -294,6 +307,21 @@ expected_cert->der_cert().AsSpan()); } +TEST(TrustStoreWin, GetIssuersInitializationError) { + // Simulate an initialization error by using null stores. + std::unique_ptr<TrustStoreWin> trust_store_win = + TrustStoreWin::CreateForTesting(crypto::ScopedHCERTSTORE(), + crypto::ScopedHCERTSTORE(), + crypto::ScopedHCERTSTORE()); + ASSERT_TRUE(trust_store_win); + ParsedCertificateList issuers; + scoped_refptr<ParsedCertificate> cert = + ParseCertFromFile("multi-root-B-by-F.pem"); + ASSERT_TRUE(cert); + trust_store_win->SyncGetIssuersOf(cert.get(), &issuers); + ASSERT_EQ(0U, issuers.size()); +} + TEST(TrustStoreWin, GetIssuersNoIssuerFound) { std::unique_ptr<TrustStoreWin> trust_store_win = CreateTrustStoreWin(); ParsedCertificateList issuers;
diff --git a/net/cert/pki/DEPS b/net/cert/pki/DEPS index db925a4..b14a61b 100644 --- a/net/cert/pki/DEPS +++ b/net/cert/pki/DEPS
@@ -5,16 +5,13 @@ "-base", "+base/base_paths.h", "+base/callback_forward.h", - "+base/containers/contains.h", "+base/containers/span.h", "+base/files/file_util.h", - "+base/memory/raw_ptr.h", "+base/memory/ref_counted.h", "+base/memory/scoped_refptr.h", "+base/metrics/histogram_functions.h", "+base/numerics/clamped_math.h", "+base/path_service.h", - "+base/stl_util.h", "+base/strings/string_piece.h", "+base/supports_user_data.h", "+base/time/time.h",
diff --git a/net/cert/pki/crl.cc b/net/cert/pki/crl.cc index 9ae62af..553ba907 100644 --- a/net/cert/pki/crl.cc +++ b/net/cert/pki/crl.cc
@@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "net/cert/pki/crl.h" +#include <algorithm> -#include "base/stl_util.h" #include "net/cert/pki/cert_errors.h" +#include "net/cert/pki/crl.h" #include "net/cert/pki/revocation_util.h" #include "net/cert/pki/signature_algorithm.h" #include "net/cert/pki/verify_name_match.h" @@ -37,7 +37,10 @@ std::vector<std::string_view> b) { std::sort(a.begin(), a.end()); std::sort(b.begin(), b.end()); - return !base::STLSetIntersection<std::vector<std::string_view>>(a, b).empty(); + std::vector<std::string_view> names_in_common; + std::set_intersection(a.begin(), a.end(), b.begin(), b.end(), + std::back_inserter(names_in_common)); + return !names_in_common.empty(); } } // namespace
diff --git a/net/cert/pki/ocsp.cc b/net/cert/pki/ocsp.cc index 6abbe31..7f3946cf 100644 --- a/net/cert/pki/ocsp.cc +++ b/net/cert/pki/ocsp.cc
@@ -4,7 +4,6 @@ #include "net/cert/pki/ocsp.h" -#include "base/containers/contains.h" #include "base/time/time.h" #include "net/cert/asn1_util.h" #include "net/cert/pki/cert_errors.h" @@ -591,8 +590,12 @@ if (!responder_certificate->has_extended_key_usage()) return false; - return base::Contains(responder_certificate->extended_key_usage(), - der::Input(kOCSPSigning)); + for (const auto& key_purpose_oid : + responder_certificate->extended_key_usage()) { + if (key_purpose_oid == der::Input(kOCSPSigning)) + return true; + } + return false; } [[nodiscard]] bool VerifyOCSPResponseSignatureGivenCert(
diff --git a/net/cert/pki/path_builder.cc b/net/cert/pki/path_builder.cc index 311207d6..01677a6d 100644 --- a/net/cert/pki/path_builder.cc +++ b/net/cert/pki/path_builder.cc
@@ -8,7 +8,6 @@ #include <set> #include <unordered_set> -#include "base/memory/raw_ptr.h" #include "base/metrics/histogram_functions.h" #include "net/base/net_errors.h" #include "net/cert/pki/cert_issuer_source.h" @@ -202,8 +201,8 @@ void SortRemainingIssuers(); scoped_refptr<ParsedCertificate> cert_; - raw_ptr<CertIssuerSources> cert_issuer_sources_; - raw_ptr<const TrustStore> trust_store_; + CertIssuerSources* cert_issuer_sources_; + const TrustStore* trust_store_; // The list of issuers for |cert_|. This is added to incrementally (first // synchronous results, then possibly multiple times as asynchronous results @@ -237,7 +236,7 @@ std::vector<std::unique_ptr<CertIssuerSource::Request>> pending_async_requests_; - raw_ptr<base::SupportsUserData> debug_data_; + base::SupportsUserData* debug_data_; }; CertIssuersIter::CertIssuersIter(scoped_refptr<ParsedCertificate> in_cert, @@ -506,9 +505,9 @@ // The CertIssuerSources for retrieving candidate issuers. CertIssuerSources cert_issuer_sources_; // The TrustStore for checking if a path ends in a trust anchor. - raw_ptr<const TrustStore> trust_store_; + const TrustStore* trust_store_; - raw_ptr<base::SupportsUserData> debug_data_; + base::SupportsUserData* debug_data_; }; CertPathIter::CertPathIter(scoped_refptr<ParsedCertificate> cert,
diff --git a/net/cert/pki/path_builder.h b/net/cert/pki/path_builder.h index 6255048..beb1ccb 100644 --- a/net/cert/pki/path_builder.h +++ b/net/cert/pki/path_builder.h
@@ -8,7 +8,6 @@ #include <memory> #include <vector> -#include "base/memory/raw_ptr.h" #include "base/supports_user_data.h" #include "base/time/time.h" #include "net/base/net_export.h"
diff --git a/net/cert/pki/test_helpers.h b/net/cert/pki/test_helpers.h index de2fceed..581cccba 100644 --- a/net/cert/pki/test_helpers.h +++ b/net/cert/pki/test_helpers.h
@@ -11,7 +11,6 @@ #include <string> #include <vector> -#include "base/memory/raw_ptr.h" #include "net/cert/pki/parsed_certificate.h" #include "net/cert/pki/simple_path_builder_delegate.h" #include "net/cert/pki/trust_store.h" @@ -43,7 +42,7 @@ const char* block_name; // The destination where the read value should be written to. - raw_ptr<std::string> value; + std::string* value; // True to indicate that the block is not required to be present. If the // block is optional and is not present, then |value| will not be modified.
diff --git a/net/cert/pki/verify_certificate_chain.cc b/net/cert/pki/verify_certificate_chain.cc index aeb8ec8..d5aea51f 100644 --- a/net/cert/pki/verify_certificate_chain.cc +++ b/net/cert/pki/verify_certificate_chain.cc
@@ -6,7 +6,6 @@ #include <algorithm> -#include "base/memory/raw_ptr.h" #include "net/cert/pki/cert_error_params.h" #include "net/cert/pki/cert_errors.h" #include "net/cert/pki/common_cert_errors.h" @@ -708,7 +707,7 @@ // certificate. size_t max_path_length_; - raw_ptr<VerifyCertificateChainDelegate> delegate_; + VerifyCertificateChainDelegate* delegate_; }; void PathVerifier::VerifyPolicies(const ParsedCertificate& cert,
diff --git a/net/http/http_stream_factory_job_controller.cc b/net/http/http_stream_factory_job_controller.cc index 3984078..6ae426c9 100644 --- a/net/http/http_stream_factory_job_controller.cc +++ b/net/http/http_stream_factory_job_controller.cc
@@ -819,6 +819,7 @@ DCHECK_NE(quic_version, quic::ParsedQuicVersion::Unsupported()); } const bool dns_alpn_h3_job_enabled = + enable_alternative_services_ && session_->params().use_dns_https_svcb_alpn && base::EqualsCaseInsensitiveASCII(origin_url.scheme(), url::kHttpsScheme) &&
diff --git a/net/http/http_stream_factory_job_controller.h b/net/http/http_stream_factory_job_controller.h index 3bf03bb..7b94ff50 100644 --- a/net/http/http_stream_factory_job_controller.h +++ b/net/http/http_stream_factory_job_controller.h
@@ -307,7 +307,8 @@ // the SpdySessionKey is different. const bool enable_ip_based_pooling_; - // Enable using alternative services for the request. + // Enable using alternative services for the request. If false, the + // JobController will only create a |main_job_|. const bool enable_alternative_services_; // For normal (non-preconnect) job, |main_job_| is a job waiting to see if
diff --git a/net/quic/quic_network_transaction_unittest.cc b/net/quic/quic_network_transaction_unittest.cc index 179d564..3e5d0a5a 100644 --- a/net/quic/quic_network_transaction_unittest.cc +++ b/net/quic/quic_network_transaction_unittest.cc
@@ -3839,6 +3839,115 @@ ExpectQuicAlternateProtocolMapping(kNetworkAnonymizationKey2); } +TEST_P(QuicNetworkTransactionTest, + ProtocolErrorAfterHandshakeConfirmedThenBrokenWithUseDnsHttpsSvcbAlpn) { + base::test::ScopedFeatureList feature_list; + feature_list.InitWithFeatures( + // enabled_features + {features::kUseDnsHttpsSvcbAlpn}, + // disabled_features + {}); + context_.params()->idle_connection_timeout = base::Seconds(5); + + // The request will initially go out over QUIC. + MockQuicData quic_data(version_); + client_maker_->SetEncryptionLevel(quic::ENCRYPTION_ZERO_RTT); + int packet_num = 1; + if (VersionUsesHttp3(version_.transport_version)) { + quic_data.AddWrite(SYNCHRONOUS, + ConstructInitialSettingsPacket(packet_num++)); + } + quic_data.AddWrite( + SYNCHRONOUS, + ConstructClientRequestHeadersPacket( + packet_num++, GetNthClientInitiatedBidirectionalStreamId(0), true, + true, GetRequestHeaders("GET", "https", "/"))); + client_maker_->SetEncryptionLevel(quic::ENCRYPTION_FORWARD_SECURE); + quic_data.AddRead(ASYNC, ERR_IO_PENDING); // Pause + + // Peer sending data from an non-existing stream causes this end to raise + // error and close connection. + quic_data.AddRead( + ASYNC, ConstructServerRstPacket( + 1, false, GetNthClientInitiatedBidirectionalStreamId(47), + quic::QUIC_STREAM_LAST_ERROR)); + std::string quic_error_details = "Data for nonexistent stream"; + quic_data.AddWrite( + SYNCHRONOUS, + ConstructClientAckAndConnectionClosePacket( + packet_num++, 1, 1, + version_.HasIetfQuicFrames() ? quic::QUIC_HTTP_STREAM_WRONG_DIRECTION + : quic::QUIC_INVALID_STREAM_ID, + quic_error_details, + version_.HasIetfQuicFrames() ? quic::IETF_STOP_SENDING + : quic::IETF_RST_STREAM)); + quic_data.AddSocketDataToFactory(&socket_factory_); + + // After that fails, it will be resent via TCP. + MockWrite http_writes[] = { + MockWrite(SYNCHRONOUS, 0, "GET / HTTP/1.1\r\n"), + MockWrite(SYNCHRONOUS, 1, "Host: mail.example.org\r\n"), + MockWrite(SYNCHRONOUS, 2, "Connection: keep-alive\r\n\r\n")}; + + MockRead http_reads[] = {MockRead(SYNCHRONOUS, 3, "HTTP/1.1 200 OK\r\n"), + MockRead(SYNCHRONOUS, 4, alt_svc_header_.data()), + MockRead(SYNCHRONOUS, 5, "hello world"), + MockRead(SYNCHRONOUS, OK, 6)}; + SequencedSocketData http_data(http_reads, http_writes); + socket_factory_.AddSocketDataProvider(&http_data); + socket_factory_.AddSSLSocketDataProvider(&ssl_data_); + + HostResolverEndpointResult endpoint_result1; + endpoint_result1.ip_endpoints = {IPEndPoint(IPAddress::IPv4Localhost(), 0)}; + endpoint_result1.metadata.supported_protocol_alpns = { + quic::QuicVersionLabelToString(quic::CreateQuicVersionLabel(version_))}; + HostResolverEndpointResult endpoint_result2; + endpoint_result2.ip_endpoints = {IPEndPoint(IPAddress::IPv4Localhost(), 0)}; + std::vector<HostResolverEndpointResult> endpoints; + endpoints.push_back(endpoint_result1); + endpoints.push_back(endpoint_result2); + host_resolver_.rules()->AddRule( + "mail.example.org", + MockHostResolverBase::RuleResolver::RuleResult( + std::move(endpoints), + /*aliases=*/std::set<std::string>{"mail.example.org"})); + + CreateSession(); + + AddQuicAlternateProtocolMapping(MockCryptoClientStream::ZERO_RTT); + + HttpNetworkTransaction trans(DEFAULT_PRIORITY, session_.get()); + TestCompletionCallback callback; + int rv = trans.Start(&request_, callback.callback(), net_log_with_source_); + EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); + + // Pump the message loop to get the request started. + base::RunLoop().RunUntilIdle(); + // Explicitly confirm the handshake. + crypto_client_stream_factory_.last_stream() + ->NotifySessionOneRttKeyAvailable(); + quic_data.Resume(); + + // Run the QUIC session to completion. + base::RunLoop().RunUntilIdle(); + ASSERT_TRUE(quic_data.AllWriteDataConsumed()); + + ExpectQuicAlternateProtocolMapping(); + + // Let the transaction proceed which will result in QUIC being marked + // as broken and the request falling back to TCP. + EXPECT_THAT(callback.WaitForResult(), IsOk()); + + ASSERT_TRUE(quic_data.AllWriteDataConsumed()); + ASSERT_FALSE(http_data.AllReadDataConsumed()); + + // Read the response body over TCP. + CheckResponseData(&trans, "hello world"); + ExpectBrokenAlternateProtocolMapping(); + ASSERT_TRUE(http_data.AllWriteDataConsumed()); + ASSERT_TRUE(http_data.AllReadDataConsumed()); +} + // Verify that with retry_without_alt_svc_on_quic_errors enabled, if a QUIC // request is reset from, then QUIC will be marked as broken and the request // retried over TCP.
diff --git a/net/spdy/spdy_network_transaction_unittest.cc b/net/spdy/spdy_network_transaction_unittest.cc index ceb3916..d504bf4 100644 --- a/net/spdy/spdy_network_transaction_unittest.cc +++ b/net/spdy/spdy_network_transaction_unittest.cc
@@ -6749,13 +6749,6 @@ std::move(session_deps)); helper.RunPreTestSetup(); - - if (GetParam().expect_ct_error) { - ssl_provider->ssl_info.ct_policy_compliance = - ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS; - ssl_provider->ssl_info.is_issued_by_known_root = true; - } - helper.AddDataWithSSLSocketDataProvider(&data, std::move(ssl_provider)); HttpNetworkTransaction* trans = helper.trans();
diff --git a/remoting/host/chromoting_host.cc b/remoting/host/chromoting_host.cc index 326830e..6a75a9a 100644 --- a/remoting/host/chromoting_host.cc +++ b/remoting/host/chromoting_host.cc
@@ -128,8 +128,9 @@ #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN) ipc_server_ = std::make_unique< named_mojo_ipc_server::NamedMojoIpcServer<mojom::ChromotingHostServices>>( - GetChromotingHostServicesServerName(), this, - base::BindRepeating(&IsTrustedMojoEndpoint)); + GetChromotingHostServicesServerName(), + named_mojo_ipc_server::NamedMojoIpcServerBase::kUseIsolatedConnection, + this, base::BindRepeating(&IsTrustedMojoEndpoint)); ipc_server_->StartServer(); HOST_LOG << "ChromotingHostServices IPC server has been started."; #else
diff --git a/services/image_annotation/annotator.cc b/services/image_annotation/annotator.cc index a36ba13f..569bd77 100644 --- a/services/image_annotation/annotator.cc +++ b/services/image_annotation/annotator.cc
@@ -94,11 +94,12 @@ // annotations message. mojom::AnnotationPtr ParseJsonOcrAnnotation(const base::Value& ocr_engine, const double min_ocr_confidence) { - if (!ocr_engine.is_dict()) + const base::Value::Dict* const ocr_engine_dict = ocr_engine.GetIfDict(); + if (!ocr_engine_dict) return mojom::AnnotationPtr(nullptr); // No OCR regions is valid - it just means there is no text. - const base::Value* const ocr_regions = ocr_engine.FindKey("ocrRegions"); + const base::Value* const ocr_regions = ocr_engine_dict->Find("ocrRegions"); if (!ocr_regions) { ReportOcrAnnotation(1.0 /* confidence */, true /* empty */); return mojom::Annotation::New(mojom::AnnotationType::kOcr, 1.0 /* score */, @@ -111,43 +112,44 @@ std::string all_ocr_text; int word_count = 0; double word_confidence_sum = 0.0; - for (const base::Value& ocr_region : ocr_regions->GetListDeprecated()) { + for (const base::Value& ocr_region : ocr_regions->GetList()) { if (!ocr_region.is_dict()) continue; - const base::Value* const words = ocr_region.FindKey("words"); - if (!words || !words->is_list()) + const base::Value::List* const words = + ocr_region.GetDict().FindList("words"); + if (!words) continue; std::string region_ocr_text; - for (const base::Value& word : words->GetListDeprecated()) { - if (!word.is_dict()) + for (const base::Value& word : *words) { + const base::Value::Dict* word_dict = word.GetIfDict(); + if (!word_dict) continue; - const base::Value* const detected_text = word.FindKey("detectedText"); - if (!detected_text || !detected_text->is_string()) + const std::string* const detected_text = + word_dict->FindString("detectedText"); + if (!detected_text) continue; // A confidence value of 0 or 1 is interpreted as an int and not a double. - const base::Value* const confidence = word.FindKey("confidenceScore"); - if (!confidence || (!confidence->is_double() && !confidence->is_int()) || - confidence->GetDouble() < 0.0 || confidence->GetDouble() > 1.0) + absl::optional<double> confidence = + word_dict->FindDouble("confidenceScore"); + if (!confidence.has_value() || *confidence < 0.0 || *confidence > 1.0) continue; - if (confidence->GetDouble() < min_ocr_confidence) + if (*confidence < min_ocr_confidence) continue; - const std::string& detected_text_str = detected_text->GetString(); - - if (detected_text_str.empty()) + if (detected_text->empty()) continue; if (!region_ocr_text.empty()) region_ocr_text += " "; - region_ocr_text += detected_text_str; + region_ocr_text += *detected_text; ++word_count; - word_confidence_sum += confidence->GetDouble(); + word_confidence_sum += *confidence; } if (!all_ocr_text.empty() && !region_ocr_text.empty()) @@ -177,63 +179,65 @@ bool adult = false; std::vector<mojom::AnnotationPtr> results; - if (!desc_engine.is_dict()) + const base::Value::Dict* desc_engine_dict = desc_engine.GetIfDict(); + if (!desc_engine_dict) return {adult, std::move(results)}; // If there is a failure reason, log it and track whether it is due to adult // content. - const base::Value* const failure_reason_value = - desc_engine.FindKey("failureReason"); - if (failure_reason_value && failure_reason_value->is_string()) { + const std::string* const failure_reason_value = + desc_engine_dict->FindString("failureReason"); + if (failure_reason_value) { const DescFailureReason failure_reason = - ParseDescFailureReason(failure_reason_value->GetString()); + ParseDescFailureReason(*failure_reason_value); ReportDescFailure(failure_reason); adult = failure_reason == DescFailureReason::kAdult; } - const base::Value* const desc_list_dict = - desc_engine.FindKey("descriptionList"); - if (!desc_list_dict || !desc_list_dict->is_dict()) + const base::Value::Dict* const desc_list_dict = + desc_engine_dict->FindDict("descriptionList"); + if (!desc_list_dict) return {adult, std::move(results)}; - const base::Value* const desc_list = desc_list_dict->FindKey("descriptions"); - if (!desc_list || !desc_list->is_list()) + const base::Value::List* const desc_list = + desc_list_dict->FindList("descriptions"); + if (!desc_list) return {adult, std::move(results)}; - for (const base::Value& desc : desc_list->GetListDeprecated()) { - if (!desc.is_dict()) + for (const base::Value& desc : *desc_list) { + const base::Value::Dict* const desc_dict = desc.GetIfDict(); + if (!desc_dict) continue; - const base::Value* const type = desc.FindKey("type"); - if (!type || !type->is_string()) + const std::string* const type = desc_dict->FindString("type"); + if (!type) continue; - const auto type_lookup = kAnnotationTypes->find(type->GetString()); + const auto type_lookup = kAnnotationTypes->find(*type); if (type_lookup == kAnnotationTypes->end()) continue; - const base::Value* const score = desc.FindKey("score"); - if (!score || (!score->is_double() && !score->is_int())) + const absl::optional<double> score = desc_dict->FindDouble("score"); + if (!score.has_value()) continue; - const base::Value* const text = desc.FindKey("text"); - if (!text || !text->is_string()) + const std::string* const text = desc_dict->FindString("text"); + if (!text) continue; - ReportDescAnnotation(type_lookup->second, score->GetDouble(), - text->GetString().empty()); + ReportDescAnnotation(type_lookup->second, *score, text->empty()); // For OCR, we allow empty text and unusual scores; at the time of writing, // a score of -1 is always returned for OCR. // // For other annotation types, we do not allow these cases. if (type_lookup->second != mojom::AnnotationType::kOcr && - (text->GetString().empty() || score->GetDouble() < 0.0 || - score->GetDouble() > 1.0)) + (text->empty() || *score < 0.0 || *score > 1.0)) { continue; + } - results.push_back(mojom::Annotation::New( - type_lookup->second, score->GetDouble(), text->GetString())); + results.push_back( + mojom::Annotation::New(type_lookup->second, *score, *text)); } return {adult, std::move(results)}; @@ -242,30 +246,32 @@ // Extracts annotations from the given icon engine result. mojom::AnnotationPtr ParseJsonIconAnnotations(const base::Value& icon_engine) { mojom::AnnotationPtr result; - if (!icon_engine.is_dict()) + const base::Value::Dict* icon_engine_dict = icon_engine.GetIfDict(); + if (!icon_engine_dict) return {}; - const base::Value* const icon_list = icon_engine.FindKey("icon"); - if (!icon_list || !icon_list->is_list()) + const base::Value::List* const icon_list = icon_engine_dict->FindList("icon"); + if (!icon_list) return {}; - for (const base::Value& icon : icon_list->GetListDeprecated()) { - if (!icon.is_dict()) + for (const base::Value& icon : *icon_list) { + const base::Value::Dict* icon_dict = icon.GetIfDict(); + if (!icon_dict) continue; - const base::Value* const icon_type = icon.FindKey("iconType"); - if (!icon_type || !icon_type->is_string()) + const std::string* const icon_type = icon_dict->FindString("iconType"); + if (!icon_type) continue; - std::string icon_type_value = icon_type->GetString(); + std::string icon_type_value = *icon_type; - const base::Value* const score = icon.FindKey("score"); - if (!score || (!score->is_double() && !score->is_int())) + const absl::optional<double> score = icon_dict->FindDouble("score"); + if (!score.has_value()) continue; // Only return the first matching icon. auto type = mojom::AnnotationType::kIcon; - return mojom::Annotation::New(type, score->GetDouble(), icon_type_value); + return mojom::Annotation::New(type, *score, icon_type_value); } return {}; @@ -273,11 +279,11 @@ // Returns the integer status code for this engine, or -1 if no status can be // extracted. -int ExtractStatusCode(const base::Value* const status_dict) { - if (!status_dict || !status_dict->is_dict()) +int ExtractStatusCode(const base::Value::Dict* const status_dict) { + if (!status_dict) return -1; - const base::Value* const code_value = status_dict->FindKey("code"); + const base::Value* const code_value = status_dict->Find("code"); // A missing code is the same as a default (i.e. OK) code. if (!code_value) @@ -289,10 +295,10 @@ #ifndef NDEBUG // Also log error status messages (which are helpful for debugging). - const base::Value* const message = status_dict->FindKey("message"); - if (code != 0 && message && message->is_string()) + const std::string* const message = status_dict->FindString("message"); + if (code != 0 && message) DVLOG(1) << "Engine failed with status " << code << " and message '" - << message->GetString() << "'"; + << *message << "'"; #endif return code; @@ -303,24 +309,27 @@ std::map<std::string, mojom::AnnotateImageResultPtr> UnpackJsonResponse( const base::Value& json_data, const double min_ocr_confidence) { - if (!json_data.is_dict()) + const base::Value::Dict* json_dict = json_data.GetIfDict(); + if (!json_dict) return {}; - const base::Value* const results = json_data.FindKey("results"); - if (!results || !results->is_list()) + const base::Value::List* const results = json_dict->FindList("results"); + if (!results) return {}; std::map<std::string, mojom::AnnotateImageResultPtr> out; - for (const base::Value& result : results->GetListDeprecated()) { - if (!result.is_dict()) + for (const base::Value& result : *results) { + const base::Value::Dict* result_dict = result.GetIfDict(); + if (!result_dict) continue; - const base::Value* const image_id = result.FindKey("imageId"); - if (!image_id || !image_id->is_string()) + const std::string* const image_id = result_dict->FindString("imageId"); + if (!image_id) continue; - const base::Value* const engine_results = result.FindKey("engineResults"); - if (!engine_results || !engine_results->is_list()) + const base::Value::List* const engine_results = + result_dict->FindList("engineResults"); + if (!engine_results) continue; // We expect the engine result list to have exactly two results: one for OCR @@ -331,9 +340,9 @@ std::vector<mojom::AnnotationPtr> annotations; mojom::AnnotationPtr ocr_annotation; mojom::AnnotationPtr icon_annotation; - for (const base::Value& engine_result : - engine_results->GetListDeprecated()) { - if (!engine_result.is_dict()) + for (const base::Value& engine_result : *engine_results) { + const base::Value::Dict* engine_result_dict = engine_result.GetIfDict(); + if (!engine_result_dict) continue; // A non-zero status code means the following: @@ -344,13 +353,14 @@ // known failure. We always report an error // in this case. const int status_code = - ExtractStatusCode(engine_result.FindKey("status")); + ExtractStatusCode(engine_result_dict->FindDict("status")); const base::Value* const desc_engine = - engine_result.FindKey("descriptionEngine"); - const base::Value* const ocr_engine = engine_result.FindKey("ocrEngine"); + engine_result_dict->Find("descriptionEngine"); + const base::Value* const ocr_engine = + engine_result_dict->Find("ocrEngine"); const base::Value* const icon_engine = - engine_result.FindKey("iconEngine"); + engine_result_dict->Find("iconEngine"); if (desc_engine) { // Add description annotations and update the adult image flag. @@ -399,10 +409,10 @@ } if (adult) { - out[image_id->GetString()] = mojom::AnnotateImageResult::NewErrorCode( + out[*image_id] = mojom::AnnotateImageResult::NewErrorCode( mojom::AnnotateImageError::kAdult); } else if (!annotations.empty()) { - out[image_id->GetString()] = + out[*image_id] = mojom::AnnotateImageResult::NewAnnotations(std::move(annotations)); } } @@ -571,7 +581,7 @@ std::string Annotator::FormatJsonRequest( const std::deque<ServerRequestInfo>::iterator begin, const std::deque<ServerRequestInfo>::iterator end) { - base::Value image_request_list(base::Value::Type::LIST); + base::Value::List image_request_list; for (std::deque<ServerRequestInfo>::iterator it = begin; it != end; ++it) { // Re-encode image bytes into base64, which can be represented in JSON. std::string base64_data; @@ -582,28 +592,27 @@ // TODO(crbug.com/916420): accept and propagate page language info to // improve OCR accuracy. - base::Value ocr_engine_params(base::Value::Type::DICTIONARY); - ocr_engine_params.SetKey("ocrParameters", - base::Value(base::Value::Type::DICTIONARY)); + base::Value::Dict ocr_engine_params; + ocr_engine_params.Set("ocrParameters", base::Value::Dict()); - base::Value engine_params_list(base::Value::Type::LIST); + base::Value::List engine_params_list; engine_params_list.Append(std::move(ocr_engine_params)); // Also add a description annotations request if the image is within model // policy. if (it->desc_requested) { - base::Value desc_params(base::Value::Type::DICTIONARY); + base::Value::Dict desc_params; // Add preferred description language if it has been specified. if (!it->desc_lang_tag.empty()) { - base::Value desc_lang_list(base::Value::Type::LIST); - desc_lang_list.Append(base::Value(it->desc_lang_tag)); + base::Value::List desc_lang_list; + desc_lang_list.Append(it->desc_lang_tag); - desc_params.SetKey("preferredLanguages", std::move(desc_lang_list)); + desc_params.Set("preferredLanguages", std::move(desc_lang_list)); } - base::Value engine_params(base::Value::Type::DICTIONARY); - engine_params.SetKey("descriptionParameters", std::move(desc_params)); + base::Value::Dict engine_params; + engine_params.Set("descriptionParameters", std::move(desc_params)); engine_params_list.Append(std::move(engine_params)); } @@ -613,24 +622,23 @@ // TODO(accessibility): Maybe only do this for certain // file sizes? if (it->icon_requested) { - base::Value icon_params(base::Value::Type::DICTIONARY); - base::Value engine_params(base::Value::Type::DICTIONARY); - engine_params.SetKey("iconParameters", std::move(icon_params)); + base::Value::Dict icon_params; + base::Value::Dict engine_params; + engine_params.Set("iconParameters", std::move(icon_params)); engine_params_list.Append(std::move(engine_params)); } ReportImageRequestIncludesIcon(it->icon_requested); - base::Value image_request(base::Value::Type::DICTIONARY); - image_request.SetKey( - "imageId", base::Value(MakeImageId(it->source_id, it->desc_lang_tag))); - image_request.SetKey("imageBytes", base::Value(std::move(base64_data))); - image_request.SetKey("engineParameters", std::move(engine_params_list)); + base::Value::Dict image_request; + image_request.Set("imageId", MakeImageId(it->source_id, it->desc_lang_tag)); + image_request.Set("imageBytes", std::move(base64_data)); + image_request.Set("engineParameters", std::move(engine_params_list)); image_request_list.Append(std::move(image_request)); } - base::Value request(base::Value::Type::DICTIONARY); - request.SetKey("imageRequests", std::move(image_request_list)); + base::Value::Dict request; + request.Set("imageRequests", std::move(image_request_list)); std::string json_request; base::JSONWriter::Write(request, &json_request); @@ -998,14 +1006,14 @@ return; } - const base::Value* const langs = json_data->FindKey("langs"); - if (!langs || !langs->is_list()) { + const base::Value::List* const langs = json_data->GetDict().FindList("langs"); + if (!langs) { DVLOG(1) << "No langs in response JSON"; return; } std::vector<std::string> new_server_languages; - for (const base::Value& lang : langs->GetListDeprecated()) { + for (const base::Value& lang : *langs) { if (!lang.is_string()) { DVLOG(1) << "Lang in response JSON is not a string"; return;
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index cc55ff10..0a6b684e 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -791,7 +791,7 @@ "colorful_mic": "false", "enable_multi_account_check": "false", "experiment_id": "48114790", - "min_agsa_version": "13.37" + "min_agsa_version": "13.45" }, "enable_features": [ "AssistantIntentExperimentId", @@ -3804,7 +3804,7 @@ ] } ], - "DesktopPartialTranslate": [ + "DesktopPartialTranslateGWSVisible": [ { "platforms": [ "linux", @@ -3813,7 +3813,7 @@ ], "experiments": [ { - "name": "Enabled", + "name": "Enabled_20221129", "params": { "DesktopPartialTranslateTextSelectionMaxCharacters": "500" }, @@ -4834,6 +4834,7 @@ { "name": "EnableSearchPageString_20220901", "params": { + "enable-lens-fullscreen-search": "false", "use-google-as-visual-search-provider": "false", "use-menu-item-alt-text-1": "true" }, @@ -4844,6 +4845,7 @@ { "name": "EnableNoLensAttributionAndSearchInsideImageString_20220901", "params": { + "enable-lens-fullscreen-search": "false", "use-google-as-visual-search-provider": "true", "use-menu-item-alt-text-3": "true" }, @@ -4854,6 +4856,7 @@ { "name": "EnableSearchAnyPartOfThePageString_20220901", "params": { + "enable-lens-fullscreen-search": "false", "use-google-as-visual-search-provider": "false", "use-menu-item-alt-text-2": "true" }, @@ -4864,6 +4867,7 @@ { "name": "EnableNoLensAttribution_20220901", "params": { + "enable-lens-fullscreen-search": "false", "use-google-as-visual-search-provider": "true" }, "enable_features": [ @@ -4873,6 +4877,7 @@ { "name": "EnableNoLensAttributionAndSearchPageString_20220901", "params": { + "enable-lens-fullscreen-search": "false", "use-google-as-visual-search-provider": "true", "use-menu-item-alt-text-1": "true" }, @@ -4883,6 +4888,7 @@ { "name": "EnableNoLensAttributionAndSearchAnyPartOfThePageString_20220901", "params": { + "enable-lens-fullscreen-search": "false", "use-google-as-visual-search-provider": "true", "use-menu-item-alt-text-2": "true" }, @@ -5487,6 +5493,22 @@ ] } ], + "IOSExpKitCalendarTextClassifier": [ + { + "platforms": [ + "ios" + ], + "experiments": [ + { + "name": "Enabled", + "enable_features": [ + "EnableExpKitCalendarTextClassifier", + "EnableExpKitTextClassifier" + ] + } + ] + } + ], "IOSExpKitMaps": [ { "platforms": [
diff --git a/third_party/Python-Markdown/README.chromium b/third_party/Python-Markdown/README.chromium index 6e531db75..f78fac4c 100644 --- a/third_party/Python-Markdown/README.chromium +++ b/third_party/Python-Markdown/README.chromium
@@ -1,6 +1,6 @@ Name: Python-Markdown -URL: https://files.pythonhosted.org/packages/49/02/37bd82ae255bb4dfef97a4b32d95906187b7a7a74970761fca1360c4ba22/Markdown-3.3.4.tar.gz -Version: 3.3.4 +URL: https://files.pythonhosted.org/packages/85/7e/133e943e97a943d2f1d8bae0c5060f8ac50e6691754eb9dbe036b047a9bb/Markdown-3.4.1.tar.gz +Version: 3.4.1 Revision: None Security Critical: no License: BSD
diff --git a/third_party/Python-Markdown/README.md b/third_party/Python-Markdown/README.md index 7b979b00..c2c573e 100644 --- a/third_party/Python-Markdown/README.md +++ b/third_party/Python-Markdown/README.md
@@ -60,5 +60,5 @@ Code of Conduct --------------- -Everyone interacting in the Python-Markdown project's codebases, issue trackers, +Everyone interacting in the Python-Markdown project's code bases, issue trackers, and mailing lists is expected to follow the [Code of Conduct].
diff --git a/third_party/Python-Markdown/markdown/__init__.py b/third_party/Python-Markdown/markdown/__init__.py index e05af10..d88b1e97 100644 --- a/third_party/Python-Markdown/markdown/__init__.py +++ b/third_party/Python-Markdown/markdown/__init__.py
@@ -19,43 +19,10 @@ License: BSD (see LICENSE.md for details). """ -import sys - -# TODO: Remove this check at some point in the future. -# (also remove flake8's 'ignore E402' comments below) -if sys.version_info[0] < 3: # pragma: no cover - raise ImportError('A recent version of Python 3 is required.') - -from .core import Markdown, markdown, markdownFromFile # noqa: E402 -from .util import PY37 # noqa: E402 -from .pep562 import Pep562 # noqa: E402 -from .__meta__ import __version__, __version_info__ # noqa: E402 -import warnings # noqa: E402 +from .core import Markdown, markdown, markdownFromFile +from .__meta__ import __version__, __version_info__ # noqa # For backward compatibility as some extensions expect it... from .extensions import Extension # noqa __all__ = ['Markdown', 'markdown', 'markdownFromFile'] - -__deprecated__ = { - "version": ("__version__", __version__), - "version_info": ("__version_info__", __version_info__) -} - - -def __getattr__(name): - """Get attribute.""" - - deprecated = __deprecated__.get(name) - if deprecated: - warnings.warn( - "'{}' is deprecated. Use '{}' instead.".format(name, deprecated[0]), - category=DeprecationWarning, - stacklevel=(3 if PY37 else 4) - ) - return deprecated[1] - raise AttributeError("module '{}' has no attribute '{}'".format(__name__, name)) - - -if not PY37: - Pep562(__name__)
diff --git a/third_party/Python-Markdown/markdown/__main__.py b/third_party/Python-Markdown/markdown/__main__.py index 7d78b7e..01840082 100644 --- a/third_party/Python-Markdown/markdown/__main__.py +++ b/third_party/Python-Markdown/markdown/__main__.py
@@ -70,7 +70,7 @@ parser.add_option("-c", "--extension_configs", dest="configfile", default=None, help="Read extension configurations from CONFIG_FILE. " - "CONFIG_FILE must be of JSON or YAML format. YAML" + "CONFIG_FILE must be of JSON or YAML format. YAML " "format requires that a python YAML library be " "installed. The parsed JSON or YAML must result in a " "python dictionary which would be accepted by the "
diff --git a/third_party/Python-Markdown/markdown/__meta__.py b/third_party/Python-Markdown/markdown/__meta__.py index 79ae2f8e..ccabee52 100644 --- a/third_party/Python-Markdown/markdown/__meta__.py +++ b/third_party/Python-Markdown/markdown/__meta__.py
@@ -26,7 +26,7 @@ # (1, 2, 0, 'beta', 2) => "1.2b2" # (1, 2, 0, 'rc', 4) => "1.2rc4" # (1, 2, 0, 'final', 0) => "1.2" -__version_info__ = (3, 3, 4, 'final', 0) +__version_info__ = (3, 4, 1, 'final', 0) def _get_version(version_info):
diff --git a/third_party/Python-Markdown/markdown/blockparser.py b/third_party/Python-Markdown/markdown/blockparser.py index 39219fd..b0ca4b1b 100644 --- a/third_party/Python-Markdown/markdown/blockparser.py +++ b/third_party/Python-Markdown/markdown/blockparser.py
@@ -69,12 +69,6 @@ self.state = State() self.md = md - @property - @util.deprecated("Use 'md' instead.") - def markdown(self): - # TODO: remove this later - return self.md - def parseDocument(self, lines): """ Parse a markdown document into an ElementTree.
diff --git a/third_party/Python-Markdown/markdown/blockprocessors.py b/third_party/Python-Markdown/markdown/blockprocessors.py index 8518e50..3d0ff86 100644 --- a/third_party/Python-Markdown/markdown/blockprocessors.py +++ b/third_party/Python-Markdown/markdown/blockprocessors.py
@@ -286,7 +286,7 @@ m = self.RE.search(block) if m: before = block[:m.start()] # Lines before blockquote - # Pass lines before blockquote in recursively for parsing forst. + # Pass lines before blockquote in recursively for parsing first. self.parser.parseBlocks(parent, [before]) # Remove ``> `` from beginning of each line. block = '\n'.join( @@ -321,7 +321,7 @@ TAG = 'ol' # The integer (python string) with which the lists starts (default=1) - # Eg: If list is intialized as) + # Eg: If list is initialized as) # 3. Item # The ol tag will get starts="3" attribute STARTSWITH = '1' @@ -559,7 +559,7 @@ class ReferenceProcessor(BlockProcessor): """ Process link references. """ RE = re.compile( - r'^[ ]{0,3}\[([^\]]*)\]:[ ]*\n?[ ]*([^\s]+)[ ]*\n?[ ]*((["\'])(.*)\4|\((.*)\))?[ ]*$', re.MULTILINE + r'^[ ]{0,3}\[([^\[\]]*)\]:[ ]*\n?[ ]*([^\s]+)[ ]*(?:\n[ ]*)?((["\'])(.*)\4[ ]*|\((.*)\)[ ]*)?$', re.MULTILINE ) def test(self, parent, block):
diff --git a/third_party/Python-Markdown/markdown/core.py b/third_party/Python-Markdown/markdown/core.py index 2f7f2d5c..f6a171c1 100644 --- a/third_party/Python-Markdown/markdown/core.py +++ b/third_party/Python-Markdown/markdown/core.py
@@ -82,7 +82,7 @@ # Other elements which Markdown should not be mucking up the contents of. 'canvas', 'colgroup', 'dd', 'body', 'dt', 'group', 'iframe', 'li', 'legend', 'math', 'map', 'noscript', 'output', 'object', 'option', 'progress', 'script', - 'style', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'tr', 'video' + 'style', 'summary', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'tr', 'video' ] self.registeredExtensions = [] @@ -122,7 +122,7 @@ if isinstance(ext, str): ext = self.build_extension(ext, configs.get(ext, {})) if isinstance(ext, Extension): - ext._extendMarkdown(self) + ext.extendMarkdown(self) logger.debug( 'Successfully loaded extension "%s.%s".' % (ext.__class__.__module__, ext.__class__.__name__) @@ -150,7 +150,7 @@ """ configs = dict(configs) - entry_points = [ep for ep in util.INSTALLED_EXTENSIONS if ep.name == ext_name] + entry_points = [ep for ep in util.get_installed_extensions() if ep.name == ext_name] if entry_points: ext = entry_points[0].load() return ext(**configs)
diff --git a/third_party/Python-Markdown/markdown/extensions/__init__.py b/third_party/Python-Markdown/markdown/extensions/__init__.py index 4bc8e5f..2d8d72a 100644 --- a/third_party/Python-Markdown/markdown/extensions/__init__.py +++ b/third_party/Python-Markdown/markdown/extensions/__init__.py
@@ -19,14 +19,13 @@ License: BSD (see LICENSE.md for details). """ -import warnings from ..util import parseBoolValue class Extension: """ Base class for extensions to subclass. """ - # Default config -- to be overriden by a subclass + # Default config -- to be overridden by a subclass # Must be of the following format: # { # 'key': ['value', 'description'] @@ -70,36 +69,16 @@ for key, value in items: self.setConfig(key, value) - def _extendMarkdown(self, *args): - """ Private wrapper around extendMarkdown. """ - md = args[0] - try: - self.extendMarkdown(md) - except TypeError as e: - if "missing 1 required positional argument" in str(e): - # Must be a 2.x extension. Pass in a dumby md_globals. - self.extendMarkdown(md, {}) - warnings.warn( - "The 'md_globals' parameter of '{}.{}.extendMarkdown' is " - "deprecated.".format(self.__class__.__module__, self.__class__.__name__), - category=DeprecationWarning, - stacklevel=2 - ) - else: - raise - def extendMarkdown(self, md): """ - Add the various proccesors and patterns to the Markdown Instance. + Add the various processors and patterns to the Markdown Instance. - This method must be overriden by every extension. + This method must be overridden by every extension. Keyword arguments: * md: The Markdown instance. - * md_globals: Global variables in the markdown module namespace. - """ raise NotImplementedError( 'Extension "%s.%s" must define an "extendMarkdown"'
diff --git a/third_party/Python-Markdown/markdown/extensions/admonition.py b/third_party/Python-Markdown/markdown/extensions/admonition.py index 9c66b4f..cb8d9015 100644 --- a/third_party/Python-Markdown/markdown/extensions/admonition.py +++ b/third_party/Python-Markdown/markdown/extensions/admonition.py
@@ -49,9 +49,9 @@ self.content_indention = 0 def parse_content(self, parent, block): - """Get sibling admontion. + """Get sibling admonition. - Retrieve the appropriate siblimg element. This can get trickly when + Retrieve the appropriate sibling element. This can get tricky when dealing with lists. """ @@ -72,8 +72,8 @@ if sibling is None or sibling.get('class', '').find(self.CLASSNAME) == -1: sibling = None else: - # If the last child is a list and the content is idented sufficient - # to be under it, then the content's is sibling is in the list. + # If the last child is a list and the content is sufficiently indented + # to be under it, then the content's sibling is in the list. last_child = self.lastChild(sibling) indent = 0 while last_child: @@ -83,12 +83,12 @@ ): # The expectation is that we'll find an <li> or <dt>. - # We should get it's last child as well. + # We should get its last child as well. sibling = self.lastChild(last_child) last_child = self.lastChild(sibling) if sibling else None # Context has been lost at this point, so we must adjust the - # text's identation level so it will be evaluated correctly + # text's indentation level so it will be evaluated correctly # under the list. block = block[self.tab_length:] indent += self.tab_length
diff --git a/third_party/Python-Markdown/markdown/extensions/codehilite.py b/third_party/Python-Markdown/markdown/extensions/codehilite.py index 9eed561f..a54ba21 100644 --- a/third_party/Python-Markdown/markdown/extensions/codehilite.py +++ b/third_party/Python-Markdown/markdown/extensions/codehilite.py
@@ -23,6 +23,7 @@ from pygments import highlight from pygments.lexers import get_lexer_by_name, guess_lexer from pygments.formatters import get_formatter_by_name + from pygments.util import ClassNotFound pygments = True except ImportError: # pragma: no cover pygments = False @@ -63,12 +64,14 @@ * use_pygments: Pass code to pygments for code highlighting. If `False`, the code is instead wrapped for highlighting by a JavaScript library. Default: `True`. + * pygments_formatter: The name of a Pygments formatter or a formatter class used for + highlighting the code blocks. Default: `html`. + * linenums: An alias to Pygments `linenos` formatter option. Default: `None`. * css_class: An alias to Pygments `cssclass` formatter option. Default: 'codehilite'. - * lang_prefix: Prefix prepended to the language when `use_pygments` is `False`. - Default: "language-". + * lang_prefix: Prefix prepended to the language. Default: "language-". Other Options: Any other options are accepted and passed on to the lexer and formatter. Therefore, @@ -80,6 +83,10 @@ Formatter options: https://pygments.org/docs/formatters/#HtmlFormatter Lexer Options: https://pygments.org/docs/lexers/ + Additionally, when Pygments is enabled, the code's language is passed to the + formatter as an extra option `lang_str`, whose value being `{lang_prefix}{lang}`. + This option has no effect to the Pygments's builtin formatters. + Advanced Usage: code = CodeHilite( src = some_code, @@ -99,6 +106,7 @@ self.guess_lang = options.pop('guess_lang', True) self.use_pygments = options.pop('use_pygments', True) self.lang_prefix = options.pop('lang_prefix', 'language-') + self.pygments_formatter = options.pop('pygments_formatter', 'html') if 'linenos' not in options: options['linenos'] = options.pop('linenums', None) @@ -112,7 +120,7 @@ self.options = options - def hilite(self): + def hilite(self, shebang=True): """ Pass code to the [Pygments](http://pygments.pocoo.org/) highliter with optional line numbers. The output should then be styled with css to @@ -125,7 +133,7 @@ self.src = self.src.strip('\n') - if self.lang is None: + if self.lang is None and shebang: self._parseHeader() if pygments and self.use_pygments: @@ -139,7 +147,17 @@ lexer = get_lexer_by_name('text', **self.options) except ValueError: # pragma: no cover lexer = get_lexer_by_name('text', **self.options) - formatter = get_formatter_by_name('html', **self.options) + if not self.lang: + # Use the guessed lexer's language instead + self.lang = lexer.aliases[0] + lang_str = f'{self.lang_prefix}{self.lang}' + if isinstance(self.pygments_formatter, str): + try: + formatter = get_formatter_by_name(self.pygments_formatter, **self.options) + except ClassNotFound: + formatter = get_formatter_by_name('html', **self.options) + else: + formatter = self.pygments_formatter(lang_str=lang_str, **self.options) return highlight(self.src, lexer, formatter) else: # just escape and build markup usable by JS highlighting libs @@ -221,7 +239,7 @@ class HiliteTreeprocessor(Treeprocessor): - """ Hilight source code in code blocks. """ + """ Highlight source code in code blocks. """ def code_unescape(self, text): """Unescape code.""" @@ -237,11 +255,12 @@ blocks = root.iter('pre') for block in blocks: if len(block) == 1 and block[0].tag == 'code': + local_config = self.config.copy() code = CodeHilite( self.code_unescape(block[0].text), tab_length=self.md.tab_length, - style=self.config.pop('pygments_style', 'default'), - **self.config + style=local_config.pop('pygments_style', 'default'), + **local_config ) placeholder = self.md.htmlStash.store(code.hilite()) # Clear codeblock in etree instance @@ -253,7 +272,7 @@ class CodeHiliteExtension(Extension): - """ Add source code hilighting to markdown codeblocks. """ + """ Add source code highlighting to markdown codeblocks. """ def __init__(self, **kwargs): # define default configs @@ -278,7 +297,11 @@ 'lang_prefix': [ 'language-', 'Prefix prepended to the language when use_pygments is false. Default: "language-"' - ] + ], + 'pygments_formatter': ['html', + 'Use a specific formatter for Pygments highlighting.' + 'Default: "html"', + ], } for key, value in kwargs.items():
diff --git a/third_party/Python-Markdown/markdown/extensions/def_list.py b/third_party/Python-Markdown/markdown/extensions/def_list.py index 0e8e452..17549f0 100644 --- a/third_party/Python-Markdown/markdown/extensions/def_list.py +++ b/third_party/Python-Markdown/markdown/extensions/def_list.py
@@ -87,7 +87,7 @@ class DefListIndentProcessor(ListIndentProcessor): """ Process indented children of definition list items. """ - # Defintion lists need to be aware of all list types + # Definition lists need to be aware of all list types ITEM_TYPES = ['dd', 'li'] LIST_TYPES = ['dl', 'ol', 'ul']
diff --git a/third_party/Python-Markdown/markdown/extensions/extra.py b/third_party/Python-Markdown/markdown/extensions/extra.py index ebd168c..909ba075 100644 --- a/third_party/Python-Markdown/markdown/extensions/extra.py +++ b/third_party/Python-Markdown/markdown/extensions/extra.py
@@ -16,7 +16,7 @@ are not part of PHP Markdown Extra, and therefore, not part of Python-Markdown Extra. If you really would like Extra to include additional extensions, we suggest creating your own clone of Extra -under a differant name. You could also edit the `extensions` global +under a different name. You could also edit the `extensions` global variable defined below, but be aware that such changes may be lost when you upgrade to any future version of Python-Markdown.
diff --git a/third_party/Python-Markdown/markdown/extensions/fenced_code.py b/third_party/Python-Markdown/markdown/extensions/fenced_code.py index 716b467..409166ad 100644 --- a/third_party/Python-Markdown/markdown/extensions/fenced_code.py +++ b/third_party/Python-Markdown/markdown/extensions/fenced_code.py
@@ -22,6 +22,7 @@ from .codehilite import CodeHilite, CodeHiliteExtension, parse_hl_lines from .attr_list import get_attrs, AttrListExtension from ..util import parseBoolValue +from ..serializers import _escape_attrib_html import re @@ -42,13 +43,13 @@ class FencedBlockPreprocessor(Preprocessor): FENCED_BLOCK_RE = re.compile( dedent(r''' - (?P<fence>^(?:~{3,}|`{3,}))[ ]* # opening fence - ((\{(?P<attrs>[^\}\n]*)\})?| # (optional {attrs} or - (\.?(?P<lang>[\w#.+-]*))?[ ]* # optional (.)lang - (hl_lines=(?P<quot>"|')(?P<hl_lines>.*?)(?P=quot))?) # optional hl_lines) - [ ]*\n # newline (end of opening fence) - (?P<code>.*?)(?<=\n) # the code block - (?P=fence)[ ]*$ # closing fence + (?P<fence>^(?:~{3,}|`{3,}))[ ]* # opening fence + ((\{(?P<attrs>[^\}\n]*)\})| # (optional {attrs} or + (\.?(?P<lang>[\w#.+-]*)[ ]*)? # optional (.)lang + (hl_lines=(?P<quot>"|')(?P<hl_lines>.*?)(?P=quot)[ ]*)?) # optional hl_lines) + \n # newline (end of opening fence) + (?P<code>.*?)(?<=\n) # the code block + (?P=fence)[ ]*$ # closing fence '''), re.MULTILINE | re.DOTALL | re.VERBOSE ) @@ -116,34 +117,28 @@ **local_config ) - code = highliter.hilite() + code = highliter.hilite(shebang=False) else: id_attr = lang_attr = class_attr = kv_pairs = '' if lang: - lang_attr = ' class="{}{}"'.format(self.config.get('lang_prefix', 'language-'), lang) + prefix = self.config.get('lang_prefix', 'language-') + lang_attr = f' class="{prefix}{_escape_attrib_html(lang)}"' if classes: - class_attr = ' class="{}"'.format(' '.join(classes)) + class_attr = f' class="{_escape_attrib_html(" ".join(classes))}"' if id: - id_attr = ' id="{}"'.format(id) + id_attr = f' id="{_escape_attrib_html(id)}"' if self.use_attr_list and config and not config.get('use_pygments', False): # Only assign key/value pairs to code element if attr_list ext is enabled, key/value pairs # were defined on the code block, and the `use_pygments` key was not set to True. The # `use_pygments` key could be either set to False or not defined. It is omitted from output. - kv_pairs = ' ' + ' '.join( - '{k}="{v}"'.format(k=k, v=v) for k, v in config.items() if k != 'use_pygments' + kv_pairs = ''.join( + f' {k}="{_escape_attrib_html(v)}"' for k, v in config.items() if k != 'use_pygments' ) - code = '<pre{id}{cls}><code{lang}{kv}>{code}</code></pre>'.format( - id=id_attr, - cls=class_attr, - lang=lang_attr, - kv=kv_pairs, - code=self._escape(m.group('code')) - ) + code = self._escape(m.group('code')) + code = f'<pre{id_attr}{class_attr}><code{lang_attr}{kv_pairs}>{code}</code></pre>' placeholder = self.md.htmlStash.store(code) - text = '{}\n{}\n{}'.format(text[:m.start()], - placeholder, - text[m.end():]) + text = f'{text[:m.start()]}\n{placeholder}\n{text[m.end():]}' else: break return text.split("\n")
diff --git a/third_party/Python-Markdown/markdown/extensions/footnotes.py b/third_party/Python-Markdown/markdown/extensions/footnotes.py index f6f4c85..96ed5c2 100644 --- a/third_party/Python-Markdown/markdown/extensions/footnotes.py +++ b/third_party/Python-Markdown/markdown/extensions/footnotes.py
@@ -47,6 +47,10 @@ ["↩", "The text string that links from the footnote " "to the reader's place."], + "SUPERSCRIPT_TEXT": + ["{}", + "The text string that links from the reader's place " + "to the footnote."], "BACKLINK_TITLE": ["Jump back to footnote %d in the text", "The text string used for the title HTML attribute " @@ -170,6 +174,9 @@ ol = etree.SubElement(div, "ol") surrogate_parent = etree.Element("div") + # Backward compatibility with old '%d' placeholder + backlink_title = self.getConfig("BACKLINK_TITLE").replace("%d", "{}") + for index, id in enumerate(self.footnotes.keys(), start=1): li = etree.SubElement(ol, "li") li.set("id", self.makeFootnoteId(id)) @@ -185,7 +192,7 @@ backlink.set("class", "footnote-backref") backlink.set( "title", - self.getConfig("BACKLINK_TITLE") % (index) + backlink_title.format(index) ) backlink.text = FN_BACKLINK_TEXT @@ -228,7 +235,7 @@ # Any content before match is continuation of this footnote, which may be lazily indented. before = therest[:m2.start()].rstrip('\n') fn_blocks[0] = '\n'.join([fn_blocks[0], self.detab(before)]).lstrip('\n') - # Add back to blocks everything from begining of match forward for next iteration. + # Add back to blocks everything from beginning of match forward for next iteration. blocks.insert(0, therest[m2.start():]) else: # All remaining lines of block are continuation of this footnote, which may be lazily indented. @@ -264,7 +271,7 @@ # Any content before match is continuation of this footnote, which may be lazily indented. before = block[:m.start()].rstrip('\n') fn_blocks.append(self.detab(before)) - # Add back to blocks everything from begining of match forward for next iteration. + # Add back to blocks everything from beginning of match forward for next iteration. blocks.insert(0, block[m.start():]) # End of this footnote. break @@ -303,7 +310,9 @@ sup.set('id', self.footnotes.makeFootnoteRefId(id, found=True)) a.set('href', '#' + self.footnotes.makeFootnoteId(id)) a.set('class', 'footnote-ref') - a.text = str(list(self.footnotes.footnotes.keys()).index(id) + 1) + a.text = self.footnotes.getConfig("SUPERSCRIPT_TEXT").format( + list(self.footnotes.footnotes.keys()).index(id) + 1 + ) return sup, m.start(0), m.end(0) else: return None, None, None @@ -355,7 +364,7 @@ self.offset = 0 for div in root.iter('div'): if div.attrib.get('class', '') == 'footnote': - # Footnotes shoul be under the first orderd list under + # Footnotes should be under the first ordered list under # the footnote div. So once we find it, quit. for ol in div.iter('ol'): self.handle_duplicates(ol)
diff --git a/third_party/Python-Markdown/markdown/extensions/legacy_attrs.py b/third_party/Python-Markdown/markdown/extensions/legacy_attrs.py index b51d7780..445aba11 100644 --- a/third_party/Python-Markdown/markdown/extensions/legacy_attrs.py +++ b/third_party/Python-Markdown/markdown/extensions/legacy_attrs.py
@@ -26,7 +26,7 @@ Prior to Python-Markdown version 3.0, the Markdown class had an `enable_attributes` keyword which was on by default and provided for attributes to be defined for elements using the format `{@key=value}`. This extension is provided as a replacement for -backward compatability. New documents should be authored using attr_lists. However, +backward compatibility. New documents should be authored using attr_lists. However, numerious documents exist which have been using the old attribute format for many years. This extension can be used to continue to render those documents correctly. """
diff --git a/third_party/Python-Markdown/markdown/extensions/legacy_em.py b/third_party/Python-Markdown/markdown/extensions/legacy_em.py index 7fddb77..360988b6 100644 --- a/third_party/Python-Markdown/markdown/extensions/legacy_em.py +++ b/third_party/Python-Markdown/markdown/extensions/legacy_em.py
@@ -2,7 +2,7 @@ Legacy Em Extension for Python-Markdown ======================================= -This extention provides legacy behavior for _connected_words_. +This extension provides legacy behavior for _connected_words_. Copyright 2015-2018 The Python Markdown Project
diff --git a/third_party/Python-Markdown/markdown/extensions/md_in_html.py b/third_party/Python-Markdown/markdown/extensions/md_in_html.py index 86cf00d..ec7dcba0 100644 --- a/third_party/Python-Markdown/markdown/extensions/md_in_html.py +++ b/third_party/Python-Markdown/markdown/extensions/md_in_html.py
@@ -33,13 +33,14 @@ self.block_level_tags = set(md.block_level_elements.copy()) # Block-level tags in which the content only gets span level parsing self.span_tags = set( - ['address', 'dd', 'dt', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'legend', 'li', 'p', 'td', 'th'] + ['address', 'dd', 'dt', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'legend', 'li', 'p', 'summary', 'td', 'th'] ) # Block-level tags which never get their content parsed. self.raw_tags = set(['canvas', 'math', 'option', 'pre', 'script', 'style', 'textarea']) - # Block-level tags in which the content gets parsed as blocks + super().__init__(md, *args, **kwargs) + # Block-level tags in which the content gets parsed as blocks self.block_tags = set(self.block_level_tags) - (self.span_tags | self.raw_tags | self.empty_tags) self.span_and_blocks_tags = self.block_tags | self.span_tags @@ -247,11 +248,11 @@ def parse_element_content(self, element): """ - Resursively parse the text content of an etree Element as Markdown. + Recursively parse the text content of an etree Element as Markdown. Any block level elements generated from the Markdown will be inserted as children of the element in place of the text content. All `markdown` attributes are removed. For any elements in which Markdown parsing has - been dissabled, the text content of it and its chidlren are wrapped in an `AtomicString`. + been disabled, the text content of it and its chidlren are wrapped in an `AtomicString`. """ md_attr = element.attrib.pop('markdown', 'off') @@ -267,7 +268,7 @@ for child in list(element): self.parse_element_content(child) - # Parse Markdown text in tail of children. Do this seperate to avoid raw HTML parsing. + # Parse Markdown text in tail of children. Do this separate to avoid raw HTML parsing. # Save the position of each item to be inserted later in reverse. tails = [] for pos, child in enumerate(element): @@ -328,7 +329,7 @@ # Cleanup stash. Replace element with empty string to avoid confusing postprocessor. self.parser.md.htmlStash.rawHtmlBlocks.pop(index) self.parser.md.htmlStash.rawHtmlBlocks.insert(index, '') - # Comfirm the match to the blockparser. + # Confirm the match to the blockparser. return True # No match found. return False
diff --git a/third_party/Python-Markdown/markdown/extensions/smarty.py b/third_party/Python-Markdown/markdown/extensions/smarty.py index 894805f..c4bfd58 100644 --- a/third_party/Python-Markdown/markdown/extensions/smarty.py +++ b/third_party/Python-Markdown/markdown/extensions/smarty.py
@@ -83,7 +83,7 @@ from . import Extension from ..inlinepatterns import HtmlInlineProcessor, HTML_RE from ..treeprocessors import InlineProcessor -from ..util import Registry, deprecated +from ..util import Registry # Constants for quote education. @@ -155,12 +155,6 @@ self.replace = replace self.md = md - @property - @deprecated("Use 'md' instead.") - def markdown(self): - # TODO: remove this later - return self.md - def handleMatch(self, m, data): result = '' for part in self.replace:
diff --git a/third_party/Python-Markdown/markdown/extensions/tables.py b/third_party/Python-Markdown/markdown/extensions/tables.py index 4b027bb..c8b1024 100644 --- a/third_party/Python-Markdown/markdown/extensions/tables.py +++ b/third_party/Python-Markdown/markdown/extensions/tables.py
@@ -30,9 +30,11 @@ RE_CODE_PIPES = re.compile(r'(?:(\\\\)|(\\`+)|(`+)|(\\\|)|(\|))') RE_END_BORDER = re.compile(r'(?<!\\)(?:\\\\)*\|$') - def __init__(self, parser): + def __init__(self, parser, config): self.border = False self.separator = '' + self.config = config + super().__init__(parser) def test(self, parent, block): @@ -126,7 +128,10 @@ except IndexError: # pragma: no cover c.text = "" if a: - c.set('align', a) + if self.config['use_align_attribute']: + c.set('align', a) + else: + c.set('style', f'text-align: {a};') def _split_row(self, row): """ split a row of text into list of cells. """ @@ -200,7 +205,7 @@ if not throw_out: good_pipes.append(pipe) - # Split row according to table delimeters. + # Split row according to table delimiters. pos = 0 for pipe in good_pipes: elements.append(row[pos:pipe]) @@ -212,11 +217,19 @@ class TableExtension(Extension): """ Add tables to Markdown. """ + def __init__(self, **kwargs): + self.config = { + 'use_align_attribute': [False, 'True to use align attribute instead of style.'], + } + + super().__init__(**kwargs) + def extendMarkdown(self, md): """ Add an instance of TableProcessor to BlockParser. """ if '|' not in md.ESCAPED_CHARS: md.ESCAPED_CHARS.append('|') - md.parser.blockprocessors.register(TableProcessor(md.parser), 'table', 75) + processor = TableProcessor(md.parser, self.getConfigs()) + md.parser.blockprocessors.register(processor, 'table', 75) def makeExtension(**kwargs): # pragma: no cover
diff --git a/third_party/Python-Markdown/markdown/extensions/toc.py b/third_party/Python-Markdown/markdown/extensions/toc.py index d64ec16..1ded18d6 100644 --- a/third_party/Python-Markdown/markdown/extensions/toc.py +++ b/third_party/Python-Markdown/markdown/extensions/toc.py
@@ -16,23 +16,26 @@ from . import Extension from ..treeprocessors import Treeprocessor from ..util import code_escape, parseBoolValue, AMP_SUBSTITUTE, HTML_PLACEHOLDER_RE, AtomicString -from ..postprocessors import UnescapePostprocessor +from ..treeprocessors import UnescapeTreeprocessor import re import html import unicodedata import xml.etree.ElementTree as etree -def slugify(value, separator, encoding='ascii'): +def slugify(value, separator, unicode=False): """ Slugify a string, to make it URL friendly. """ - value = unicodedata.normalize('NFKD', value).encode(encoding, 'ignore') - value = re.sub(r'[^\w\s-]', '', value.decode(encoding)).strip().lower() + if not unicode: + # Replace Extended Latin characters with ASCII, i.e. žlutý → zluty + value = unicodedata.normalize('NFKD', value) + value = value.encode('ascii', 'ignore').decode('ascii') + value = re.sub(r'[^\w\s-]', '', value).strip().lower() return re.sub(r'[{}\s]+'.format(separator), separator, value) def slugify_unicode(value, separator): """ Slugify a string, to make it URL friendly while preserving Unicode characters. """ - return slugify(value, separator, 'utf-8') + return slugify(value, separator, unicode=True) IDCOUNT_RE = re.compile(r'^(.*)_([0-9]+)$') @@ -81,8 +84,8 @@ def unescape(text): """ Unescape escaped text. """ - c = UnescapePostprocessor() - return c.run(text) + c = UnescapeTreeprocessor() + return c.unescape(text) def nest_toc_tokens(toc_list): @@ -157,6 +160,7 @@ self.base_level = int(config["baselevel"]) - 1 self.slugify = config["slugify"] self.sep = config["separator"] + self.toc_class = config["toc_class"] self.use_anchors = parseBoolValue(config["anchorlink"]) self.anchorlink_class = config["anchorlink_class"] self.use_permalinks = parseBoolValue(config["permalink"], False) @@ -192,7 +196,12 @@ # To keep the output from screwing up the # validation by putting a <div> inside of a <p> # we actually replace the <p> in its entirety. - if c.text and c.text.strip() == self.marker: + + # The <p> element may contain more than a single text content + # (nl2br can introduce a <br>). In this situation, c.text returns + # the very first content, ignore children contents or tail content. + # len(c) == 0 is here to ensure there is only text in the <p>. + if c.text and c.text.strip() == self.marker and len(c) == 0: for i in range(len(p)): if p[i] == c: p[i] = elem @@ -231,7 +240,7 @@ def build_toc_div(self, toc_list): """ Return a string div given a toc list. """ div = etree.Element("div") - div.attrib["class"] = "toc" + div.attrib["class"] = self.toc_class # Add title to the div if self.title: @@ -280,10 +289,10 @@ toc_tokens.append({ 'level': int(el.tag[-1]), 'id': el.attrib["id"], - 'name': unescape(stashedHTML2text( + 'name': stashedHTML2text( code_escape(el.attrib.get('data-toc-label', text)), self.md, strip_entities=False - )) + ) }) # Remove the data-toc-label attribute as it is no longer needed @@ -320,6 +329,9 @@ "title": ["", "Title to insert into TOC <div> - " "Defaults to an empty string"], + "toc_class": ['toc', + 'CSS class(es) used for the link. ' + 'Defaults to "toclink"'], "anchorlink": [False, "True if header should be a self link - " "Defaults to False"], @@ -357,7 +369,7 @@ self.reset() tocext = self.TreeProcessorClass(md, self.getConfigs()) # Headerid ext is set to '>prettify'. With this set to '_end', - # it should always come after headerid ext (and honor ids assinged + # it should always come after headerid ext (and honor ids assigned # by the header id extension) if both are used. Same goes for # attr_list extension. This must come last because we don't want # to redefine ids after toc is created. But we do want toc prettified.
diff --git a/third_party/Python-Markdown/markdown/htmlparser.py b/third_party/Python-Markdown/markdown/htmlparser.py index c08856a..3512d1a7 100644 --- a/third_party/Python-Markdown/markdown/htmlparser.py +++ b/third_party/Python-Markdown/markdown/htmlparser.py
@@ -20,7 +20,7 @@ """ import re -import importlib +import importlib.util import sys @@ -113,7 +113,7 @@ return m.end() else: # pragma: no cover # Value of self.lineno must exceed total number of lines. - # Find index of begining of last line. + # Find index of beginning of last line. return self.rawdata.rfind('\n') return 0
diff --git a/third_party/Python-Markdown/markdown/inlinepatterns.py b/third_party/Python-Markdown/markdown/inlinepatterns.py index b0621a8..eb313bd 100644 --- a/third_party/Python-Markdown/markdown/inlinepatterns.py +++ b/third_party/Python-Markdown/markdown/inlinepatterns.py
@@ -160,10 +160,10 @@ AUTOLINK_RE = r'<((?:[Ff]|[Hh][Tt])[Tt][Pp][Ss]?://[^<>]*)>' # <me@example.com> -AUTOMAIL_RE = r'<([^<> !]*@[^@<> ]*)>' +AUTOMAIL_RE = r'<([^<> !]+@[^@<> ]+)>' # <...> -HTML_RE = r'(<([a-zA-Z/][^<>]*|!--(?:(?!<!--|-->).)*--)>)' +HTML_RE = r'(<(\/?[a-zA-Z][^<>@ ]*( [^<>]*)?|!--(?:(?!<!--|-->).)*--)>)' # "&" (decimal) or "&" (hex) or "&" (named) ENTITY_RE = r'(&(?:\#[0-9]+|\#x[0-9a-fA-F]+|[a-zA-Z0-9]+);)' @@ -211,12 +211,6 @@ self.md = md - @property - @util.deprecated("Use 'md' instead.") - def markdown(self): - # TODO: remove this later - return self.md - def getCompiledRegExp(self): """ Return a compiled regular expression. """ return self.compiled_re @@ -673,7 +667,7 @@ bracket_count -= 1 elif backtrack_count > 0: backtrack_count -= 1 - # We've found our backup end location if the title doesn't reslove. + # We've found our backup end location if the title doesn't resolve. if backtrack_count == 0: last_bracket = index + 1
diff --git a/third_party/Python-Markdown/markdown/pep562.py b/third_party/Python-Markdown/markdown/pep562.py deleted file mode 100644 index b130d3b..0000000 --- a/third_party/Python-Markdown/markdown/pep562.py +++ /dev/null
@@ -1,245 +0,0 @@ -""" -Backport of PEP 562. - -https://pypi.org/search/?q=pep562 - -Licensed under MIT -Copyright (c) 2018 Isaac Muse <isaacmuse@gmail.com> - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated -documentation files (the "Software"), to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, -and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions -of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL -THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF -CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -IN THE SOFTWARE. -""" -import sys -from collections import namedtuple -import re - -__all__ = ('Pep562',) - -RE_VER = re.compile( - r'''(?x) - (?P<major>\d+)(?:\.(?P<minor>\d+))?(?:\.(?P<micro>\d+))? - (?:(?P<type>a|b|rc)(?P<pre>\d+))? - (?:\.post(?P<post>\d+))? - (?:\.dev(?P<dev>\d+))? - ''' -) - -REL_MAP = { - ".dev": "", - ".dev-alpha": "a", - ".dev-beta": "b", - ".dev-candidate": "rc", - "alpha": "a", - "beta": "b", - "candidate": "rc", - "final": "" -} - -DEV_STATUS = { - ".dev": "2 - Pre-Alpha", - ".dev-alpha": "2 - Pre-Alpha", - ".dev-beta": "2 - Pre-Alpha", - ".dev-candidate": "2 - Pre-Alpha", - "alpha": "3 - Alpha", - "beta": "4 - Beta", - "candidate": "4 - Beta", - "final": "5 - Production/Stable" -} - -PRE_REL_MAP = {"a": 'alpha', "b": 'beta', "rc": 'candidate'} - - -class Version(namedtuple("Version", ["major", "minor", "micro", "release", "pre", "post", "dev"])): - """ - Get the version (PEP 440). - - A biased approach to the PEP 440 semantic version. - - Provides a tuple structure which is sorted for comparisons `v1 > v2` etc. - (major, minor, micro, release type, pre-release build, post-release build, development release build) - Release types are named in is such a way they are comparable with ease. - Accessors to check if a development, pre-release, or post-release build. Also provides accessor to get - development status for setup files. - - How it works (currently): - - - You must specify a release type as either `final`, `alpha`, `beta`, or `candidate`. - - To define a development release, you can use either `.dev`, `.dev-alpha`, `.dev-beta`, or `.dev-candidate`. - The dot is used to ensure all development specifiers are sorted before `alpha`. - You can specify a `dev` number for development builds, but do not have to as implicit development releases - are allowed. - - You must specify a `pre` value greater than zero if using a prerelease as this project (not PEP 440) does not - allow implicit prereleases. - - You can optionally set `post` to a value greater than zero to make the build a post release. While post releases - are technically allowed in prereleases, it is strongly discouraged, so we are rejecting them. It should be - noted that we do not allow `post0` even though PEP 440 does not restrict this. This project specifically - does not allow implicit post releases. - - It should be noted that we do not support epochs `1!` or local versions `+some-custom.version-1`. - - Acceptable version releases: - - ``` - Version(1, 0, 0, "final") 1.0 - Version(1, 2, 0, "final") 1.2 - Version(1, 2, 3, "final") 1.2.3 - Version(1, 2, 0, ".dev-alpha", pre=4) 1.2a4 - Version(1, 2, 0, ".dev-beta", pre=4) 1.2b4 - Version(1, 2, 0, ".dev-candidate", pre=4) 1.2rc4 - Version(1, 2, 0, "final", post=1) 1.2.post1 - Version(1, 2, 3, ".dev") 1.2.3.dev0 - Version(1, 2, 3, ".dev", dev=1) 1.2.3.dev1 - ``` - - """ - - def __new__(cls, major, minor, micro, release="final", pre=0, post=0, dev=0): - """Validate version info.""" - - # Ensure all parts are positive integers. - for value in (major, minor, micro, pre, post): - if not (isinstance(value, int) and value >= 0): - raise ValueError("All version parts except 'release' should be integers.") - - if release not in REL_MAP: - raise ValueError("'{}' is not a valid release type.".format(release)) - - # Ensure valid pre-release (we do not allow implicit pre-releases). - if ".dev-candidate" < release < "final": - if pre == 0: - raise ValueError("Implicit pre-releases not allowed.") - elif dev: - raise ValueError("Version is not a development release.") - elif post: - raise ValueError("Post-releases are not allowed with pre-releases.") - - # Ensure valid development or development/pre release - elif release < "alpha": - if release > ".dev" and pre == 0: - raise ValueError("Implicit pre-release not allowed.") - elif post: - raise ValueError("Post-releases are not allowed with pre-releases.") - - # Ensure a valid normal release - else: - if pre: - raise ValueError("Version is not a pre-release.") - elif dev: - raise ValueError("Version is not a development release.") - - return super().__new__(cls, major, minor, micro, release, pre, post, dev) - - def _is_pre(self): - """Is prerelease.""" - - return self.pre > 0 - - def _is_dev(self): - """Is development.""" - - return bool(self.release < "alpha") - - def _is_post(self): - """Is post.""" - - return self.post > 0 - - def _get_dev_status(self): # pragma: no cover - """Get development status string.""" - - return DEV_STATUS[self.release] - - def _get_canonical(self): - """Get the canonical output string.""" - - # Assemble major, minor, micro version and append `pre`, `post`, or `dev` if needed.. - if self.micro == 0: - ver = "{}.{}".format(self.major, self.minor) - else: - ver = "{}.{}.{}".format(self.major, self.minor, self.micro) - if self._is_pre(): - ver += '{}{}'.format(REL_MAP[self.release], self.pre) - if self._is_post(): - ver += ".post{}".format(self.post) - if self._is_dev(): - ver += ".dev{}".format(self.dev) - - return ver - - -def parse_version(ver, pre=False): - """Parse version into a comparable Version tuple.""" - - m = RE_VER.match(ver) - - # Handle major, minor, micro - major = int(m.group('major')) - minor = int(m.group('minor')) if m.group('minor') else 0 - micro = int(m.group('micro')) if m.group('micro') else 0 - - # Handle pre releases - if m.group('type'): - release = PRE_REL_MAP[m.group('type')] - pre = int(m.group('pre')) - else: - release = "final" - pre = 0 - - # Handle development releases - dev = m.group('dev') if m.group('dev') else 0 - if m.group('dev'): - dev = int(m.group('dev')) - release = '.dev-' + release if pre else '.dev' - else: - dev = 0 - - # Handle post - post = int(m.group('post')) if m.group('post') else 0 - - return Version(major, minor, micro, release, pre, post, dev) - - -class Pep562: - """ - Backport of PEP 562 <https://pypi.org/search/?q=pep562>. - - Wraps the module in a class that exposes the mechanics to override `__dir__` and `__getattr__`. - The given module will be searched for overrides of `__dir__` and `__getattr__` and use them when needed. - """ - - def __init__(self, name): - """Acquire `__getattr__` and `__dir__`, but only replace module for versions less than Python 3.7.""" - - self._module = sys.modules[name] - self._get_attr = getattr(self._module, '__getattr__', None) - self._get_dir = getattr(self._module, '__dir__', None) - sys.modules[name] = self - - def __dir__(self): - """Return the overridden `dir` if one was provided, else apply `dir` to the module.""" - - return self._get_dir() if self._get_dir else dir(self._module) - - def __getattr__(self, name): - """Attempt to retrieve the attribute from the module, and if missing, use the overridden function if present.""" - - try: - return getattr(self._module, name) - except AttributeError: - if self._get_attr: - return self._get_attr(name) - raise - - -__version_info__ = Version(1, 0, 0, "final") -__version__ = __version_info__._get_canonical()
diff --git a/third_party/Python-Markdown/markdown/postprocessors.py b/third_party/Python-Markdown/markdown/postprocessors.py index 2e572f6..498f7e8 100644 --- a/third_party/Python-Markdown/markdown/postprocessors.py +++ b/third_party/Python-Markdown/markdown/postprocessors.py
@@ -37,7 +37,6 @@ postprocessors = util.Registry() postprocessors.register(RawHtmlPostprocessor(md), 'raw_html', 30) postprocessors.register(AndSubstitutePostprocessor(), 'amp_substitute', 20) - postprocessors.register(UnescapePostprocessor(), 'unescape', 10) return postprocessors @@ -65,6 +64,8 @@ class RawHtmlPostprocessor(Postprocessor): """ Restore raw html to the document. """ + BLOCK_LEVEL_REGEX = re.compile(r'^\<\/?([^ >]+)') + def run(self, text): """ Iterate over html stash and restore html. """ replacements = OrderedDict() @@ -99,7 +100,7 @@ return self.run(processed_text) def isblocklevel(self, html): - m = re.match(r'^\<\/?([^ >]+)', html) + m = self.BLOCK_LEVEL_REGEX.match(html) if m: if m.group(1)[0] in ('!', '?', '@', '%'): # Comment, php etc... @@ -120,6 +121,10 @@ return text +@util.deprecated( + "This class will be removed in the future; " + "use 'treeprocessors.UnescapeTreeprocessor' instead." +) class UnescapePostprocessor(Postprocessor): """ Restore escaped chars """
diff --git a/third_party/Python-Markdown/markdown/test_tools.py b/third_party/Python-Markdown/markdown/test_tools.py index 21ae1a7d..2ce0e74f7 100644 --- a/third_party/Python-Markdown/markdown/test_tools.py +++ b/third_party/Python-Markdown/markdown/test_tools.py
@@ -42,7 +42,7 @@ The `assertMarkdownRenders` method accepts the source text, the expected output, and any keywords to pass to Markdown. The `default_kwargs` are used - except where overridden by `kwargs`. The ouput and expected ouput are passed + except where overridden by `kwargs`. The output and expected output are passed to `TestCase.assertMultiLineEqual`. An AssertionError is raised with a diff if the actual output does not equal the expected output. @@ -195,7 +195,7 @@ text-based test files and define various behaviors/defaults for those tests. The following properties are supported: - location: A path to the directory fo test files. An absolute path is preferred. + location: A path to the directory of test files. An absolute path is preferred. exclude: A list of tests to exclude. Each test name should comprise the filename without an extension. normalize: A boolean value indicating if the HTML should be normalized.
diff --git a/third_party/Python-Markdown/markdown/treeprocessors.py b/third_party/Python-Markdown/markdown/treeprocessors.py index eb6bf41..e9f48ca 100644 --- a/third_party/Python-Markdown/markdown/treeprocessors.py +++ b/third_party/Python-Markdown/markdown/treeprocessors.py
@@ -19,6 +19,7 @@ License: BSD (see LICENSE.md for details). """ +import re import xml.etree.ElementTree as etree from . import util from . import inlinepatterns @@ -29,6 +30,7 @@ treeprocessors = util.Registry() treeprocessors.register(InlineProcessor(md), 'inline', 20) treeprocessors.register(PrettifyTreeprocessor(md), 'prettify', 10) + treeprocessors.register(UnescapeTreeprocessor(md), 'unescape', 0) return treeprocessors @@ -75,12 +77,6 @@ self.inlinePatterns = md.inlinePatterns self.ancestors = [] - @property - @util.deprecated("Use 'md' instead.") - def markdown(self): - # TODO: remove this later - return self.md - def __makePlaceholder(self, type): """ Generate a placeholder """ id = "%04d" % len(self.stashed_nodes) @@ -331,7 +327,7 @@ Iterate over ElementTree, find elements with inline tag, apply inline patterns and append newly created Elements to tree. If you don't - want to process your data with inline paterns, instead of normal + want to process your data with inline patterns, instead of normal string, use subclass AtomicString: node.text = markdown.AtomicString("This will not be processed.") @@ -412,8 +408,6 @@ for e in elem: if self.md.is_block_level(e.tag): self._prettifyETree(e) - if not elem.tail or not elem.tail.strip(): - elem.tail = i if not elem.tail or not elem.tail.strip(): elem.tail = i @@ -433,4 +427,32 @@ pres = root.iter('pre') for pre in pres: if len(pre) and pre[0].tag == 'code': - pre[0].text = util.AtomicString(pre[0].text.rstrip() + '\n') + code = pre[0] + # Only prettify code containing text only + if not len(code) and code.text is not None: + code.text = util.AtomicString(code.text.rstrip() + '\n') + + +class UnescapeTreeprocessor(Treeprocessor): + """ Restore escaped chars """ + + RE = re.compile(r'{}(\d+){}'.format(util.STX, util.ETX)) + + def _unescape(self, m): + return chr(int(m.group(1))) + + def unescape(self, text): + return self.RE.sub(self._unescape, text) + + def run(self, root): + """ Loop over all elements and unescape all text. """ + for elem in root.iter(): + # Unescape text content + if elem.text and not elem.tag == 'code': + elem.text = self.unescape(elem.text) + # Unescape tail content + if elem.tail: + elem.tail = self.unescape(elem.tail) + # Unescape attribute values + for key, value in elem.items(): + elem.set(key, self.unescape(value))
diff --git a/third_party/Python-Markdown/markdown/util.py b/third_party/Python-Markdown/markdown/util.py index 2cb2317a..e6b08e5 100644 --- a/third_party/Python-Markdown/markdown/util.py +++ b/third_party/Python-Markdown/markdown/util.py
@@ -21,31 +21,11 @@ import re import sys -from collections import namedtuple -from functools import wraps import warnings -import xml.etree.ElementTree -from .pep562 import Pep562 +from collections import namedtuple +from functools import wraps, lru_cache from itertools import count -try: - from importlib import metadata -except ImportError: - # <PY38 use backport - import importlib_metadata as metadata - -PY37 = (3, 7) <= sys.version_info - - -# TODO: Remove deprecated variables in a future release. -__deprecated__ = { - 'etree': ('xml.etree.ElementTree', xml.etree.ElementTree), - 'string_type': ('str', str), - 'text_type': ('str', str), - 'int2str': ('chr', chr), - 'iterrange': ('range', range) -} - """ Constants you might want to modify @@ -83,8 +63,6 @@ ----------------------------------------------------------------------------- """ -# Only load extension entry_points once. -INSTALLED_EXTENSIONS = metadata.entry_points().get('markdown.extensions', ()) RTL_BIDI_RANGES = ( ('\u0590', '\u07FF'), # Hebrew (0590-05FF), Arabic (0600-06FF), @@ -100,32 +78,36 @@ """ +@lru_cache(maxsize=None) +def get_installed_extensions(): + if sys.version_info >= (3, 10): + from importlib import metadata + else: # <PY310 use backport + import importlib_metadata as metadata + # Only load extension entry_points once. + return metadata.entry_points(group='markdown.extensions') + + def deprecated(message, stacklevel=2): """ Raise a DeprecationWarning when wrapped function/method is called. - Borrowed from https://stackoverflow.com/a/48632082/866026 + Usage: + @deprecated("This method will be removed in version X; use Y instead.") + def some_method()" + pass """ - def deprecated_decorator(func): + def wrapper(func): @wraps(func) def deprecated_func(*args, **kwargs): warnings.warn( - "'{}' is deprecated. {}".format(func.__name__, message), + f"'{func.__name__}' is deprecated. {message}", category=DeprecationWarning, stacklevel=stacklevel ) return func(*args, **kwargs) return deprecated_func - return deprecated_decorator - - -@deprecated("Use 'Markdown.is_block_level' instead.") -def isBlockLevel(tag): - """Check if the tag is a block level HTML tag.""" - if isinstance(tag, str): - return tag.lower().rstrip('/') in BLOCK_LEVEL_ELEMENTS - # Some ElementTree tags are not strings, so return False. - return False + return wrapper def parseBoolValue(value, fail_on_errors=True, preserve_none=False): @@ -159,8 +141,7 @@ def _get_stack_depth(size=2): - """Get stack size for caller's frame. - See https://stackoverflow.com/a/47956089/866026 + """Get current stack depth, performantly. """ frame = sys._getframe(size) @@ -171,7 +152,7 @@ def nearing_recursion_limit(): - """Return true if current stack depth is withing 100 of maximum limit.""" + """Return true if current stack depth is within 100 of maximum limit.""" return sys.getrecursionlimit() - _get_stack_depth() < 100 @@ -190,12 +171,6 @@ def __init__(self, md=None): self.md = md - @property - @deprecated("Use 'md' instead.") - def markdown(self): - # TODO: remove this later - return self.md - class HtmlStash: """ @@ -346,7 +321,7 @@ * `priority`: An integer or float used to sort against all items. If an item is registered with a "name" which already exists, the - existing item is replaced with the new item. Tread carefully as the + existing item is replaced with the new item. Treat carefully as the old item is lost with no way to recover it. The new item will be sorted according to its priority and will **not** retain the position of the old item. @@ -381,102 +356,3 @@ if not self._is_sorted: self._priority.sort(key=lambda item: item.priority, reverse=True) self._is_sorted = True - - # Deprecated Methods which provide a smooth transition from OrderedDict - - def __setitem__(self, key, value): - """ Register item with priorty 5 less than lowest existing priority. """ - if isinstance(key, str): - warnings.warn( - 'Using setitem to register a processor or pattern is deprecated. ' - 'Use the `register` method instead.', - DeprecationWarning, - stacklevel=2, - ) - if key in self: - # Key already exists, replace without altering priority - self._data[key] = value - return - if len(self) == 0: - # This is the first item. Set priority to 50. - priority = 50 - else: - self._sort() - priority = self._priority[-1].priority - 5 - self.register(value, key, priority) - else: - raise TypeError - - def __delitem__(self, key): - """ Deregister an item by name. """ - if key in self: - self.deregister(key) - warnings.warn( - 'Using del to remove a processor or pattern is deprecated. ' - 'Use the `deregister` method instead.', - DeprecationWarning, - stacklevel=2, - ) - else: - raise KeyError('Cannot delete key {}, not registered.'.format(key)) - - def add(self, key, value, location): - """ Register a key by location. """ - if len(self) == 0: - # This is the first item. Set priority to 50. - priority = 50 - elif location == '_begin': - self._sort() - # Set priority 5 greater than highest existing priority - priority = self._priority[0].priority + 5 - elif location == '_end': - self._sort() - # Set priority 5 less than lowest existing priority - priority = self._priority[-1].priority - 5 - elif location.startswith('<') or location.startswith('>'): - # Set priority halfway between existing priorities. - i = self.get_index_for_name(location[1:]) - if location.startswith('<'): - after = self._priority[i].priority - if i > 0: - before = self._priority[i-1].priority - else: - # Location is first item` - before = after + 10 - else: - # location.startswith('>') - before = self._priority[i].priority - if i < len(self) - 1: - after = self._priority[i+1].priority - else: - # location is last item - after = before - 10 - priority = before - ((before - after) / 2) - else: - raise ValueError('Not a valid location: "%s". Location key ' - 'must start with a ">" or "<".' % location) - self.register(value, key, priority) - warnings.warn( - 'Using the add method to register a processor or pattern is deprecated. ' - 'Use the `register` method instead.', - DeprecationWarning, - stacklevel=2, - ) - - -def __getattr__(name): - """Get attribute.""" - - deprecated = __deprecated__.get(name) - if deprecated: - warnings.warn( - "'{}' is deprecated. Use '{}' instead.".format(name, deprecated[0]), - category=DeprecationWarning, - stacklevel=(3 if PY37 else 4) - ) - return deprecated[1] - raise AttributeError("module '{}' has no attribute '{}'".format(__name__, name)) - - -if not PY37: - Pep562(__name__)
diff --git a/third_party/blink/public/common/frame/user_activation_state.h b/third_party/blink/public/common/frame/user_activation_state.h index 1bc1458d..6a6a047 100644 --- a/third_party/blink/public/common/frame/user_activation_state.h +++ b/third_party/blink/public/common/frame/user_activation_state.h
@@ -60,7 +60,7 @@ // ========================================== // // The user activation state is replicated in the browser process (in -// |FrameTreeNode|) and in the renderer processes (in |LocalFrame| and +// |RenderFrameHostImpl|) and in the renderer processes (in |LocalFrame| and // |RemoteFrame|). The replicated states across the browser and renderer // processes are kept in sync as follows: //
diff --git a/third_party/blink/renderer/core/css/css_default_style_sheets.cc b/third_party/blink/renderer/core/css/css_default_style_sheets.cc index b7b082c0..717fce9a 100644 --- a/third_party/blink/renderer/core/css/css_default_style_sheets.cc +++ b/third_party/blink/renderer/core/css/css_default_style_sheets.cc
@@ -325,7 +325,7 @@ if (!RuntimeEnabledFeatures:: FormControlsVerticalWritingModeSupportEnabled() && !form_controls_not_vertical_style_sheet_ && - IsA<HTMLProgressElement>(element)) { + (IsA<HTMLProgressElement>(element) || IsA<HTMLMeterElement>(element))) { form_controls_not_vertical_style_sheet_ = ParseUASheet(UncompressResourceAsASCIIString( IDR_UASTYLE_FORM_CONTROLS_NOT_VERTICAL_CSS));
diff --git a/third_party/blink/renderer/core/css/form_controls_not_vertical.css b/third_party/blink/renderer/core/css/form_controls_not_vertical.css index b50d185..0fcbefe6 100644 --- a/third_party/blink/renderer/core/css/form_controls_not_vertical.css +++ b/third_party/blink/renderer/core/css/form_controls_not_vertical.css
@@ -11,6 +11,6 @@ /* TODO(crbug.com/681917): These form controls don't go vertical if FormControlsVerticalWritingModeSupport is disabled. */ -progress { +meter, progress { writing-mode: horizontal-tb !important; } \ No newline at end of file
diff --git a/third_party/blink/renderer/core/exported/web_plugin_container_impl.cc b/third_party/blink/renderer/core/exported/web_plugin_container_impl.cc index 8c4cc72..c56aae3 100644 --- a/third_party/blink/renderer/core/exported/web_plugin_container_impl.cc +++ b/third_party/blink/renderer/core/exported/web_plugin_container_impl.cc
@@ -447,6 +447,9 @@ } void WebPluginContainerImpl::Copy() { + if (!web_plugin_->CanCopy()) + return; + if (!web_plugin_->HasSelection()) return;
diff --git a/third_party/blink/renderer/core/exported/web_plugin_container_test.cc b/third_party/blink/renderer/core/exported/web_plugin_container_test.cc index d51dde2..71ed747 100644 --- a/third_party/blink/renderer/core/exported/web_plugin_container_test.cc +++ b/third_party/blink/renderer/core/exported/web_plugin_container_test.cc
@@ -142,6 +142,7 @@ bool HasSelection() const override { return true; } WebString SelectionAsText() const override { return WebString("x"); } WebString SelectionAsMarkup() const override { return WebString("y"); } + bool CanCopy() const override; bool SupportsPaginatedPrint() override { return true; } int PrintBegin(const WebPrintParams& print_params) override { return 1; } void PrintPage(int page_number, cc::PaintCanvas*) override; @@ -230,13 +231,21 @@ void SetHasEditableText(bool has_editable_text) { has_editable_text_ = has_editable_text; } + void SetCanCopy(bool can_copy) { can_copy_ = can_copy; } + bool CanCopy() const { return can_copy_; } private: bool printed_page_ = false; bool has_editable_text_ = false; + bool can_copy_ = true; PageTestBase::MockClipboardHostProvider mock_clipboard_host_provider_; }; +bool TestPlugin::CanCopy() const { + DCHECK(test_client_); + return test_client_->CanCopy(); +} + void TestPlugin::PrintPage(int page_number, cc::PaintCanvas* canvas) { DCHECK(test_client_); test_client_->OnPrintPage(); @@ -369,7 +378,7 @@ // Verifies executing the command 'Copy' results in copying to the clipboard. TEST_F(WebPluginContainerTest, Copy) { RegisterMockedURL("plugin_container.html"); - // Must outlive |web_view_helper|. + // Must outlive `web_view_helper`. TestPluginWebFrameClient plugin_web_frame_client; frame_test_helpers::WebViewHelper web_view_helper; WebViewImpl* web_view = web_view_helper.InitializeAndLoad( @@ -389,9 +398,35 @@ ClearClipboardBuffer(*local_frame); } +// Verifies executing the command 'Copy' results in copying nothing to the +// clipboard when the plugin does not have the copy permission. +TEST_F(WebPluginContainerTest, CopyWithoutPermission) { + RegisterMockedURL("plugin_container.html"); + // Must outlive `web_view_helper`. + TestPluginWebFrameClient plugin_web_frame_client; + // Make sure to create a plugin without the copy permission. + plugin_web_frame_client.SetCanCopy(false); + frame_test_helpers::WebViewHelper web_view_helper; + WebViewImpl* web_view = web_view_helper.InitializeAndLoad( + base_url_ + "plugin_container.html", &plugin_web_frame_client); + EnablePlugins(web_view, gfx::Size(300, 300)); + + web_view->MainFrameImpl() + ->GetDocument() + .Unwrap<Document>() + ->body() + ->getElementById("translated-plugin") + ->Focus(); + EXPECT_TRUE(web_view->MainFrame()->ToWebLocalFrame()->ExecuteCommand("Copy")); + + LocalFrame* local_frame = web_view->MainFrameImpl()->GetFrame(); + EXPECT_EQ(String(""), ReadClipboard(*local_frame)); + ClearClipboardBuffer(*local_frame); +} + TEST_F(WebPluginContainerTest, CopyFromContextMenu) { RegisterMockedURL("plugin_container.html"); - // Must outlive |web_view_helper|. + // Must outlive `web_view_helper`. TestPluginWebFrameClient plugin_web_frame_client; frame_test_helpers::WebViewHelper web_view_helper; WebViewImpl* web_view = web_view_helper.InitializeAndLoad( @@ -424,11 +459,46 @@ ClearClipboardBuffer(*local_frame); } -// Verifies |Ctrl-C| and |Ctrl-Insert| keyboard events, results in copying to +TEST_F(WebPluginContainerTest, CopyFromContextMenuWithoutCopyPermission) { + RegisterMockedURL("plugin_container.html"); + // Must outlive `web_view_helper`. + TestPluginWebFrameClient plugin_web_frame_client; + // Make sure to create a plugin without the copy permission. + plugin_web_frame_client.SetCanCopy(false); + frame_test_helpers::WebViewHelper web_view_helper; + WebViewImpl* web_view = web_view_helper.InitializeAndLoad( + base_url_ + "plugin_container.html", &plugin_web_frame_client); + EnablePlugins(web_view, gfx::Size(300, 300)); + + // Make sure the right-click + command copies nothing in common scenario. + ExecuteContextMenuCommand(web_view, "Copy"); + LocalFrame* local_frame = web_view->MainFrameImpl()->GetFrame(); + EXPECT_EQ(String(""), ReadClipboard(*local_frame)); + ClearClipboardBuffer(*local_frame); + + auto event = frame_test_helpers::CreateMouseEvent( + WebMouseEvent::Type::kMouseDown, WebMouseEvent::Button::kRight, + gfx::Point(30, 30), 0); + event.click_count = 1; + + // Now, make sure the context menu copies nothing in a more complex scenario. + // 1) open the context menu. This will focus the plugin. + web_view->MainFrameWidget()->HandleInputEvent( + WebCoalescedInputEvent(event, ui::LatencyInfo())); + // 2) document blurs the plugin, because it can. + web_view->FocusedElement()->blur(); + // 3) Copy should still operate on the context node, even though the focus had + // shifted. + EXPECT_TRUE(web_view->MainFrameImpl()->ExecuteCommand("Copy")); + EXPECT_EQ(String(""), ReadClipboard(*local_frame)); + ClearClipboardBuffer(*local_frame); +} + +// Verifies `Ctrl-C` and `Ctrl-Insert` keyboard events, results in copying to // the clipboard. TEST_F(WebPluginContainerTest, CopyInsertKeyboardEventsTest) { RegisterMockedURL("plugin_container.html"); - // Must outlive |web_view_helper|. + // Must outlive `web_view_helper`. TestPluginWebFrameClient plugin_web_frame_client; frame_test_helpers::WebViewHelper web_view_helper; WebViewImpl* web_view = web_view_helper.InitializeAndLoad( @@ -452,6 +522,37 @@ ClearClipboardBuffer(*local_frame); } +// Verifies `Ctrl-C` and `Ctrl-Insert` keyboard events, results in copying +// nothing to the clipboard. +TEST_F(WebPluginContainerTest, + CopyInsertKeyboardEventsTestWithoutCopyPermission) { + RegisterMockedURL("plugin_container.html"); + // Must outlive `web_view_helper`. + TestPluginWebFrameClient plugin_web_frame_client; + // Make sure to create a plugin without the copy permission. + plugin_web_frame_client.SetCanCopy(false); + frame_test_helpers::WebViewHelper web_view_helper; + WebViewImpl* web_view = web_view_helper.InitializeAndLoad( + base_url_ + "plugin_container.html", &plugin_web_frame_client); + EnablePlugins(web_view, gfx::Size(300, 300)); + + WebElement plugin_container_one_element = + web_view->MainFrameImpl()->GetDocument().GetElementById( + WebString::FromUTF8("translated-plugin")); + WebInputEvent::Modifiers modifier_key = static_cast<WebInputEvent::Modifiers>( + kEditingModifier | WebInputEvent::kNumLockOn | WebInputEvent::kIsLeft); + CreateAndHandleKeyboardEvent(&plugin_container_one_element, modifier_key, + VKEY_C); + LocalFrame* local_frame = web_view->MainFrameImpl()->GetFrame(); + EXPECT_EQ(String(""), ReadClipboard(*local_frame)); + ClearClipboardBuffer(*local_frame); + + CreateAndHandleKeyboardEvent(&plugin_container_one_element, modifier_key, + VKEY_INSERT); + EXPECT_EQ(String(""), ReadClipboard(*local_frame)); + ClearClipboardBuffer(*local_frame); +} + // Verifies |Ctrl-X| and |Shift-Delete| keyboard events, results in the "Cut" // command being invoked. TEST_F(WebPluginContainerTest, CutDeleteKeyboardEventsTest) {
diff --git a/third_party/blink/renderer/core/html/html_meter_element.cc b/third_party/blink/renderer/core/html/html_meter_element.cc index f2b61e3..e5c247a 100644 --- a/third_party/blink/renderer/core/html/html_meter_element.cc +++ b/third_party/blink/renderer/core/html/html_meter_element.cc
@@ -41,6 +41,7 @@ : HTMLElement(html_names::kMeterTag, document) { UseCounter::Count(document, WebFeature::kMeterElement); EnsureUserAgentShadowRoot(); + SetHasCustomStyleCallbacks(); } HTMLMeterElement::~HTMLMeterElement() = default; @@ -204,7 +205,9 @@ DEFINE_STATIC_LOCAL(AtomicString, even_less_good_pseudo_id, ("-webkit-meter-even-less-good-value")); - value_->SetInlineStyleProperty(CSSPropertyID::kWidth, percentage, + value_->SetInlineStyleProperty(CSSPropertyID::kInlineSize, percentage, + CSSPrimitiveValue::UnitType::kPercentage); + value_->SetInlineStyleProperty(CSSPropertyID::kBlockSize, 100, CSSPrimitiveValue::UnitType::kPercentage); switch (GetGaugeRegion()) { case kGaugeRegionOptimum: @@ -235,4 +238,18 @@ HTMLElement::Trace(visitor); } +scoped_refptr<ComputedStyle> HTMLMeterElement::CustomStyleForLayoutObject( + const StyleRecalcContext& style_recalc_context) { + scoped_refptr<ComputedStyle> style = + OriginalStyleForLayoutObject(style_recalc_context); + // For vertical writing-mode, we need to set the direction to rtl so that + // the meter value bar is rendered bottom up. + if (!IsHorizontalWritingMode(style->GetWritingMode())) { + ComputedStyleBuilder builder(*style); + builder.SetDirection(TextDirection::kRtl); + style = builder.TakeStyle(); + } + return style; +} + } // namespace blink
diff --git a/third_party/blink/renderer/core/html/html_meter_element.h b/third_party/blink/renderer/core/html/html_meter_element.h index ab6ddfc..9a0d4bf 100644 --- a/third_party/blink/renderer/core/html/html_meter_element.h +++ b/third_party/blink/renderer/core/html/html_meter_element.h
@@ -77,6 +77,8 @@ void DidElementStateChange(); void UpdateValueAppearance(double percentage); void DidAddUserAgentShadowRoot(ShadowRoot&) override; + scoped_refptr<ComputedStyle> CustomStyleForLayoutObject( + const StyleRecalcContext&) override; Member<HTMLDivElement> value_; };
diff --git a/third_party/blink/renderer/core/html/resources/html.css b/third_party/blink/renderer/core/html/resources/html.css index 420e109..7122ecc3 100644 --- a/third_party/blink/renderer/core/html/resources/html.css +++ b/third_party/blink/renderer/core/html/resources/html.css
@@ -398,7 +398,7 @@ } /* Form controls don't go vertical. */ -input, textarea, select, button, meter { +input, textarea, select, button { writing-mode: horizontal-tb !important; } @@ -998,8 +998,8 @@ appearance: auto; box-sizing: border-box; display: inline-block; - height: 1em; - width: 5em; + block-size: 1em; + inline-size: 5em; vertical-align: -0.2em; -webkit-user-modify: read-only !important; } @@ -1009,8 +1009,8 @@ box-sizing: inherit; display: none; -webkit-user-modify: read-only !important; - height: 100%; - width: 100%; + block-size: 100%; + inline-size: 100%; } meter::-webkit-meter-inner-element:-internal-shadow-host-has-appearance { @@ -1024,8 +1024,8 @@ } meter::-webkit-meter-bar { - height: 100%; - width: 100%; + block-size: 100%; + inline-size: 100%; -webkit-user-modify: read-only !important; background: -internal-light-dark(#efefef, #3B3B3B); border: thin solid -internal-light-dark(rgba(118, 118, 118, 0.3), #858585); @@ -1039,21 +1039,21 @@ } meter::-webkit-meter-optimum-value { - height: 100%; + block-size: 100%; -webkit-user-modify: read-only !important; box-sizing: border-box; background: -internal-light-dark(#107c10, #74b374) } meter::-webkit-meter-suboptimum-value { - height: 100%; + block-size: 100%; -webkit-user-modify: read-only !important; box-sizing: border-box; background: -internal-light-dark(#ffb900, #f2c812) } meter::-webkit-meter-even-less-good-value { - height: 100%; + block-size: 100%; -webkit-user-modify: read-only !important; box-sizing: border-box; background: -internal-light-dark(#d83b01, #e98f6d) @@ -1073,22 +1073,22 @@ progress::-webkit-progress-inner-element { box-sizing: inherit; -webkit-user-modify: read-only; - height: 100%; - width: 100%; + block-size: 100%; + inline-size: 100%; } progress::-webkit-progress-bar { background-color: gray; - height: 100%; - width: 100%; + block-size: 100%; + inline-size: 100%; -webkit-user-modify: read-only !important; box-sizing: border-box; } progress::-webkit-progress-value { background-color: green; - height: 100%; - width: 50%; /* should be removed later */ + block-size: 100%; + inline-size: 50%; /* should be removed later */ -webkit-user-modify: read-only !important; box-sizing: border-box; }
diff --git a/third_party/blink/renderer/platform/graphics/canvas_resource_provider.h b/third_party/blink/renderer/platform/graphics/canvas_resource_provider.h index ee6123f3..7367f84 100644 --- a/third_party/blink/renderer/platform/graphics/canvas_resource_provider.h +++ b/third_party/blink/renderer/platform/graphics/canvas_resource_provider.h
@@ -79,7 +79,10 @@ kPassThrough = 7, kSwapChain = 8, kSkiaDawnSharedImage [[deprecated]] = 9, +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" kMaxValue = kSkiaDawnSharedImage, +#pragma GCC diagnostic pop }; // The following parameters attempt to reach a compromise between not flushing
diff --git a/third_party/blink/renderer/platform/graphics/paint/drawing_recorder.cc b/third_party/blink/renderer/platform/graphics/paint/drawing_recorder.cc index f432c57..40d98ab 100644 --- a/third_party/blink/renderer/platform/graphics/paint/drawing_recorder.cc +++ b/third_party/blink/renderer/platform/graphics/paint/drawing_recorder.cc
@@ -21,11 +21,10 @@ visual_rect_(visual_rect) { // Must check DrawingRecorder::UseCachedDrawingIfPossible before creating the // DrawingRecorder. - DCHECK(RuntimeEnabledFeatures::PaintUnderInvalidationCheckingEnabled() || - context_.GetPaintController().ShouldForcePaintForBenchmark() || - !UseCachedDrawingIfPossible(context_, client_, type_)); - +#if DCHECK_IS_ON() + context_.GetPaintController().AssertLastCheckedCachedItem(client_, type_); DCHECK(DisplayItem::IsDrawingType(display_item_type)); +#endif context.SetInDrawingRecorder(true); context.BeginRecording();
diff --git a/third_party/blink/renderer/platform/graphics/paint/paint_controller.cc b/third_party/blink/renderer/platform/graphics/paint/paint_controller.cc index 704f9da..9cd1233 100644 --- a/third_party/blink/renderer/platform/graphics/paint/paint_controller.cc +++ b/third_party/blink/renderer/platform/graphics/paint/paint_controller.cc
@@ -120,35 +120,48 @@ bool PaintController::UseCachedItemIfPossible(const DisplayItemClient& client, DisplayItem::Type type) { + last_matching_item_ = kNotFound; + if (usage_ == kTransient) return false; if (benchmark_mode_ == PaintBenchmarkMode::kCachingDisabled) return false; - if (!ClientCacheIsValid(client)) - return false; - if (IsCheckingUnderInvalidation()) { // We are checking under-invalidation of a subsequence enclosing this // display item. Let the client continue to actually paint the display item. return false; } - auto cached_item = FindCachedItem( - client, DisplayItem::Id(client.Id(), type, current_fragment_)); + DisplayItem::Id id(client.Id(), type, current_fragment_); +#if DCHECK_IS_ON() + last_checked_cached_item_id_ = id.AsHashKey(); +#endif + + if (client.IsJustCreated() || !client.IsCacheable()) { + return false; + } + + auto cached_item = FindCachedItem(client, id); if (cached_item == kNotFound) { // See FindOutOfOrderCachedItemForward() for explanation of the situation. return false; } - ++num_cached_new_items_; next_item_to_match_ = cached_item + 1; - // Items before |next_item_to_match_| have been copied so we don't need to + // Items before |next_item_to_match_| have been matched so we don't need to // index them. if (next_item_to_match_ > next_item_to_index_) next_item_to_index_ = next_item_to_match_; + if (!ClientCacheIsValid(client)) { + last_matching_item_ = cached_item; + return false; + } + + ++num_cached_new_items_; + if (RuntimeEnabledFeatures::PaintUnderInvalidationCheckingEnabled()) { EnsureUnderInvalidationChecker().WouldUseCachedItem(cached_item); // Return false to let the painter actually paint. We will check if the new @@ -165,6 +178,30 @@ return true; } +#if DCHECK_IS_ON() +void PaintController::AssertLastCheckedCachedItem( + const DisplayItemClient& client, + DisplayItem::Type type) { + if (RuntimeEnabledFeatures::PaintUnderInvalidationCheckingEnabled() || + ShouldForcePaintForBenchmark() || usage_ == PaintController::kTransient) { + return; + } + + DCHECK(last_checked_cached_item_id_ == + DisplayItem::Id(client.Id(), type, current_fragment_).AsHashKey()); +} +#endif + +DisplayItem* PaintController::MatchingCachedItemToBeRepainted() { + if (last_matching_item_ == kNotFound) { + return nullptr; + } + DisplayItem& item = + current_paint_artifact_->GetDisplayItemList()[last_matching_item_]; + DCHECK(!item.IsTombstone()); + return &item; +} + bool PaintController::UseCachedSubsequenceIfPossible( const DisplayItemClient& client) { if (usage_ == kTransient) @@ -175,9 +212,6 @@ return false; } - if (!ClientCacheIsValid(client)) - return false; - if (IsCheckingUnderInvalidation()) { // We are checking under-invalidation of an ancestor subsequence enclosing // this one. The ancestor subsequence is supposed to have already "copied", @@ -187,6 +221,10 @@ return false; } + if (client.IsJustCreated() || !client.IsCacheable()) { + return false; + } + wtf_size_t subsequence_index = GetSubsequenceIndex(client.Id()); if (subsequence_index == kNotFound) return false; @@ -202,7 +240,7 @@ if (end_item_index > start_item_index && current_paint_artifact_->GetDisplayItemList()[start_item_index] .IsTombstone()) { - // The subsequence has already been copied, indicating that the same client + // The subsequence has already been matched, indicating that the same client // created multiple subsequences. If DCHECK_IS_ON(), then we should have // encountered the DCHECK at the end of EndSubsequence() during the previous // paint. @@ -214,12 +252,15 @@ // We are matching new and cached display items sequentially. Skip the // subsequence for later sequential matching of individual display items. next_item_to_match_ = end_item_index; - // Items before |next_item_to_match_| have been copied so we don't need to + // Items before |next_item_to_match_| have been matched so we don't need to // index them. if (next_item_to_match_ > next_item_to_index_) next_item_to_index_ = next_item_to_match_; } + if (!ClientCacheIsValid(client)) + return false; + num_cached_new_items_ += end_item_index - start_item_index; ++num_cached_new_subsequences_; @@ -230,7 +271,7 @@ return false; } - // This subsequence was copied from the cache, so client must already be + // This subsequence was moved from the cache, so client must already be // valid, hence we don't call MarkClientForValidation(client). AppendSubsequenceByMoving(client, subsequence_index, markers.start_chunk_index, markers.end_chunk_index); @@ -469,10 +510,9 @@ // new item. const DisplayItem& item = current_paint_artifact_->GetDisplayItemList()[next_item_to_match_]; - // We encounter an item that has already been copied which indicates we + // We encounter an item that has already been moved which indicates we // can't do sequential matching. if (!item.IsTombstone() && id == item.GetId()) { - DCHECK(item.IsCacheable()); #if DCHECK_IS_ON() ++num_sequential_matches_; #endif @@ -523,7 +563,8 @@ // rendering, but causes AddItemToIndexIfNeeded() for all remaining display // item, which is not the best for performance. In this case, the caller // should fall back to repaint the display item. - if (RuntimeEnabledFeatures::PaintUnderInvalidationCheckingEnabled()) { + if (RuntimeEnabledFeatures::PaintUnderInvalidationCheckingEnabled() && + ClientCacheIsValid(client)) { // Ensure our paint invalidation tests don't trigger the less performant // situation which should be rare. RecordDebugInfo(client); @@ -643,6 +684,7 @@ #if DCHECK_IS_ON() new_display_item_id_index_map_.clear(); new_paint_chunk_id_index_map_.clear(); + last_checked_cached_item_id_ = DisplayItem::Id::HashKey(); #endif cache_is_all_invalid_ = false; @@ -666,6 +708,7 @@ next_item_to_match_ = 0; next_item_to_index_ = 0; + last_matching_item_ = kNotFound; out_of_order_item_id_index_map_.clear(); #if DCHECK_IS_ON() @@ -755,6 +798,10 @@ return *under_invalidation_checker_; } +bool PaintController::IsCheckingUnderInvalidationForTesting() const { + return IsCheckingUnderInvalidation(); +} + bool PaintController::IsCheckingUnderInvalidation() const { if (under_invalidation_checker_) { DCHECK(RuntimeEnabledFeatures::PaintUnderInvalidationCheckingEnabled());
diff --git a/third_party/blink/renderer/platform/graphics/paint/paint_controller.h b/third_party/blink/renderer/platform/graphics/paint/paint_controller.h index e4eadd6..a8e5c02 100644 --- a/third_party/blink/renderer/platform/graphics/paint/paint_controller.h +++ b/third_party/blink/renderer/platform/graphics/paint/paint_controller.h
@@ -164,6 +164,16 @@ // list and returns true. Otherwise returns false. bool UseCachedItemIfPossible(const DisplayItemClient&, DisplayItem::Type); +#if DCHECK_IS_ON() + void AssertLastCheckedCachedItem(const DisplayItemClient&, DisplayItem::Type); +#endif + + // This can only be called if the previous UseCachedItemIfPossible() returned + // false. Returns the cached display item that was matched in the previous + // UseCachedItemIfPossible() for an invalidated DisplayItemClient, or nullptr + // if there is no matching item. + DisplayItem* MatchingCachedItemToBeRepainted(); + // Tries to find the cached subsequence corresponding to the given parameters. // If found, copies the cache subsequence to the new display list and returns // true. Otherwise returns false. @@ -246,6 +256,8 @@ return benchmark_mode_ >= PaintBenchmarkMode::kForcePaint; } + bool IsCheckingUnderInvalidationForTesting() const; + void SetFirstPainted(); void SetTextPainted(); void SetImagePainted(); @@ -424,6 +436,8 @@ // requests. wtf_size_t next_item_to_index_ = 0; + wtf_size_t last_matching_item_ = kNotFound; + #if DCHECK_IS_ON() wtf_size_t num_indexed_items_ = 0; wtf_size_t num_sequential_matches_ = 0; @@ -433,6 +447,8 @@ IdIndexMap new_display_item_id_index_map_; // This is used to check duplicated ids for new paint chunks. IdIndexMap new_paint_chunk_id_index_map_; + + DisplayItem::Id::HashKey last_checked_cached_item_id_; #endif std::unique_ptr<PaintUnderInvalidationChecker> under_invalidation_checker_;
diff --git a/third_party/blink/renderer/platform/graphics/paint/paint_controller_test.cc b/third_party/blink/renderer/platform/graphics/paint/paint_controller_test.cc index ab3ff0b..994bb0f 100644 --- a/third_party/blink/renderer/platform/graphics/paint/paint_controller_test.cc +++ b/third_party/blink/renderer/platform/graphics/paint/paint_controller_test.cc
@@ -20,6 +20,36 @@ namespace blink { +PaintControllerTestBase::DrawResult PaintControllerTestBase::Draw( + GraphicsContext& context, + const DisplayItemClient& client, + DisplayItem::Type type, + base::FunctionRef<void()> draw_function) { + if (DrawingRecorder::UseCachedDrawingIfPossible(context, client, type)) { + return kCached; + } + + auto& paint_controller = context.GetPaintController(); + auto* matching_cached_item = + paint_controller.MatchingCachedItemToBeRepainted(); + if (matching_cached_item) { + EXPECT_EQ( + matching_cached_item->GetId(), + DisplayItem::Id(client.Id(), type, paint_controller.CurrentFragment())); + } + + bool would_be_cached = + context.GetPaintController().IsCheckingUnderInvalidationForTesting(); + + draw_function(); + + if (would_be_cached) { + DCHECK(!matching_cached_item); + return kCached; + } + return matching_cached_item ? kRepaintedCachedItem : kPaintedNew; +} + // Tests using this class will be tested with under-invalidation-checking // enabled and disabled. class PaintControllerTest : public PaintTestConfigurations, @@ -42,7 +72,8 @@ CommitCycleScope cycle_scope(GetPaintController()); InitRootChunk(); - DrawRect(context, client, kBackgroundType, gfx::Rect(100, 100, 200, 200)); + EXPECT_EQ(kPaintedNew, DrawRect(context, client, kBackgroundType, + gfx::Rect(100, 100, 200, 200))); } EXPECT_THAT(GetPaintController().GetDisplayItemList(), @@ -60,9 +91,12 @@ CommitCycleScope cycle_scope(GetPaintController()); InitRootChunk(); - DrawRect(context, first, kBackgroundType, gfx::Rect(100, 100, 300, 300)); - DrawRect(context, second, kBackgroundType, gfx::Rect(100, 100, 200, 200)); - DrawRect(context, first, kForegroundType, gfx::Rect(100, 100, 300, 300)); + EXPECT_EQ(kPaintedNew, DrawRect(context, first, kBackgroundType, + gfx::Rect(100, 100, 300, 300))); + EXPECT_EQ(kPaintedNew, DrawRect(context, second, kBackgroundType, + gfx::Rect(100, 100, 200, 200))); + EXPECT_EQ(kPaintedNew, DrawRect(context, first, kForegroundType, + gfx::Rect(100, 100, 300, 300))); EXPECT_EQ(0u, NumCachedNewItems()); EXPECT_EQ(0u, NumCachedNewSubsequences()); @@ -77,8 +111,10 @@ { CommitCycleScope cycle_scope(GetPaintController()); InitRootChunk(); - DrawRect(context, first, kBackgroundType, gfx::Rect(100, 100, 300, 300)); - DrawRect(context, first, kForegroundType, gfx::Rect(100, 100, 300, 300)); + EXPECT_EQ(kCached, DrawRect(context, first, kBackgroundType, + gfx::Rect(100, 100, 300, 300))); + EXPECT_EQ(kCached, DrawRect(context, first, kForegroundType, + gfx::Rect(100, 100, 300, 300))); EXPECT_EQ(2u, NumCachedNewItems()); EXPECT_EQ(0u, NumCachedNewSubsequences()); @@ -107,12 +143,18 @@ CommitCycleScope cycle_scope(GetPaintController()); InitRootChunk(); - DrawRect(context, first, kBackgroundType, gfx::Rect(100, 100, 100, 100)); - DrawRect(context, first, kForegroundType, gfx::Rect(100, 100, 100, 100)); - DrawRect(context, second, kBackgroundType, gfx::Rect(100, 100, 50, 200)); - DrawRect(context, second, kForegroundType, gfx::Rect(100, 100, 50, 200)); - DrawRect(context, unaffected, kBackgroundType, gfx::Rect(300, 300, 10, 10)); - DrawRect(context, unaffected, kForegroundType, gfx::Rect(300, 300, 10, 10)); + EXPECT_EQ(kPaintedNew, DrawRect(context, first, kBackgroundType, + gfx::Rect(100, 100, 100, 100))); + EXPECT_EQ(kPaintedNew, DrawRect(context, first, kForegroundType, + gfx::Rect(100, 100, 100, 100))); + EXPECT_EQ(kPaintedNew, DrawRect(context, second, kBackgroundType, + gfx::Rect(100, 100, 50, 200))); + EXPECT_EQ(kPaintedNew, DrawRect(context, second, kForegroundType, + gfx::Rect(100, 100, 50, 200))); + EXPECT_EQ(kPaintedNew, DrawRect(context, unaffected, kBackgroundType, + gfx::Rect(300, 300, 10, 10))); + EXPECT_EQ(kPaintedNew, DrawRect(context, unaffected, kForegroundType, + gfx::Rect(300, 300, 10, 10))); } EXPECT_THAT(GetPaintController().GetDisplayItemList(), @@ -126,12 +168,18 @@ { CommitCycleScope cycle_scope(GetPaintController()); InitRootChunk(); - DrawRect(context, second, kBackgroundType, gfx::Rect(100, 100, 50, 200)); - DrawRect(context, second, kForegroundType, gfx::Rect(100, 100, 50, 200)); - DrawRect(context, first, kBackgroundType, gfx::Rect(100, 100, 100, 100)); - DrawRect(context, first, kForegroundType, gfx::Rect(100, 100, 100, 100)); - DrawRect(context, unaffected, kBackgroundType, gfx::Rect(300, 300, 10, 10)); - DrawRect(context, unaffected, kForegroundType, gfx::Rect(300, 300, 10, 10)); + EXPECT_EQ(kCached, DrawRect(context, second, kBackgroundType, + gfx::Rect(100, 100, 50, 200))); + EXPECT_EQ(kCached, DrawRect(context, second, kForegroundType, + gfx::Rect(100, 100, 50, 200))); + EXPECT_EQ(kCached, DrawRect(context, first, kBackgroundType, + gfx::Rect(100, 100, 100, 100))); + EXPECT_EQ(kCached, DrawRect(context, first, kForegroundType, + gfx::Rect(100, 100, 100, 100))); + EXPECT_EQ(kCached, DrawRect(context, unaffected, kBackgroundType, + gfx::Rect(300, 300, 10, 10))); + EXPECT_EQ(kCached, DrawRect(context, unaffected, kForegroundType, + gfx::Rect(300, 300, 10, 10))); EXPECT_EQ(6u, NumCachedNewItems()); EXPECT_EQ(0u, NumCachedNewSubsequences()); @@ -165,12 +213,18 @@ CommitCycleScope cycle_scope(GetPaintController()); InitRootChunk(); - DrawRect(context, first, kBackgroundType, gfx::Rect(100, 100, 100, 100)); - DrawRect(context, first, kForegroundType, gfx::Rect(100, 100, 100, 100)); - DrawRect(context, second, kBackgroundType, gfx::Rect(100, 100, 50, 200)); - DrawRect(context, second, kForegroundType, gfx::Rect(100, 100, 50, 200)); - DrawRect(context, unaffected, kBackgroundType, gfx::Rect(300, 300, 10, 10)); - DrawRect(context, unaffected, kForegroundType, gfx::Rect(300, 300, 10, 10)); + EXPECT_EQ(kPaintedNew, DrawRect(context, first, kBackgroundType, + gfx::Rect(100, 100, 100, 100))); + EXPECT_EQ(kPaintedNew, DrawRect(context, first, kForegroundType, + gfx::Rect(100, 100, 100, 100))); + EXPECT_EQ(kPaintedNew, DrawRect(context, second, kBackgroundType, + gfx::Rect(100, 100, 50, 200))); + EXPECT_EQ(kPaintedNew, DrawRect(context, second, kForegroundType, + gfx::Rect(100, 100, 50, 200))); + EXPECT_EQ(kPaintedNew, DrawRect(context, unaffected, kBackgroundType, + gfx::Rect(300, 300, 10, 10))); + EXPECT_EQ(kPaintedNew, DrawRect(context, unaffected, kForegroundType, + gfx::Rect(300, 300, 10, 10))); } EXPECT_THAT(GetPaintController().GetDisplayItemList(), @@ -185,19 +239,25 @@ CommitCycleScope cycle_scope(GetPaintController()); InitRootChunk(); first.Invalidate(); - DrawRect(context, second, kBackgroundType, gfx::Rect(100, 100, 50, 200)); - DrawRect(context, second, kForegroundType, gfx::Rect(100, 100, 50, 200)); - DrawRect(context, first, kBackgroundType, gfx::Rect(100, 100, 100, 100)); - DrawRect(context, first, kForegroundType, gfx::Rect(100, 100, 100, 100)); - DrawRect(context, unaffected, kBackgroundType, gfx::Rect(300, 300, 10, 10)); - DrawRect(context, unaffected, kForegroundType, gfx::Rect(300, 300, 10, 10)); + EXPECT_EQ(kCached, DrawRect(context, second, kBackgroundType, + gfx::Rect(100, 100, 50, 200))); + EXPECT_EQ(kCached, DrawRect(context, second, kForegroundType, + gfx::Rect(100, 100, 50, 200))); + EXPECT_EQ(kRepaintedCachedItem, DrawRect(context, first, kBackgroundType, + gfx::Rect(100, 100, 100, 100))); + EXPECT_EQ(kRepaintedCachedItem, DrawRect(context, first, kForegroundType, + gfx::Rect(100, 100, 100, 100))); + EXPECT_EQ(kCached, DrawRect(context, unaffected, kBackgroundType, + gfx::Rect(300, 300, 10, 10))); + EXPECT_EQ(kCached, DrawRect(context, unaffected, kForegroundType, + gfx::Rect(300, 300, 10, 10))); EXPECT_EQ(4u, NumCachedNewItems()); EXPECT_EQ(0u, NumCachedNewSubsequences()); #if DCHECK_IS_ON() EXPECT_EQ(2u, NumIndexedItems()); - EXPECT_EQ(4u, NumSequentialMatches()); // second, unaffected - EXPECT_EQ(0u, NumOutOfOrderMatches()); + EXPECT_EQ(5u, NumSequentialMatches()); + EXPECT_EQ(1u, NumOutOfOrderMatches()); #endif } @@ -223,8 +283,10 @@ CommitCycleScope cycle_scope(GetPaintController()); InitRootChunk(); - DrawRect(context, first, kBackgroundType, gfx::Rect(100, 100, 100, 100)); - DrawRect(context, second, kBackgroundType, gfx::Rect(100, 100, 50, 200)); + EXPECT_EQ(kPaintedNew, DrawRect(context, first, kBackgroundType, + gfx::Rect(100, 100, 100, 100))); + EXPECT_EQ(kPaintedNew, DrawRect(context, second, kBackgroundType, + gfx::Rect(100, 100, 50, 200))); } EXPECT_THAT(GetPaintController().GetDisplayItemList(), @@ -235,9 +297,12 @@ CommitCycleScope cycle_scope(GetPaintController()); InitRootChunk(); - DrawRect(context, first, kBackgroundType, gfx::Rect(100, 100, 100, 100)); - DrawRect(context, third, kBackgroundType, gfx::Rect(125, 100, 200, 50)); - DrawRect(context, second, kBackgroundType, gfx::Rect(100, 100, 50, 200)); + EXPECT_EQ(kCached, DrawRect(context, first, kBackgroundType, + gfx::Rect(100, 100, 100, 100))); + EXPECT_EQ(kPaintedNew, DrawRect(context, third, kBackgroundType, + gfx::Rect(125, 100, 200, 50))); + EXPECT_EQ(kCached, DrawRect(context, second, kBackgroundType, + gfx::Rect(100, 100, 50, 200))); EXPECT_EQ(2u, NumCachedNewItems()); EXPECT_EQ(0u, NumCachedNewSubsequences()); @@ -288,18 +353,24 @@ InitRootChunk(); second.Invalidate(); - DrawRect(context, first, kBackgroundType, gfx::Rect(100, 100, 100, 100)); - DrawRect(context, second, kBackgroundType, gfx::Rect(100, 100, 50, 200)); - DrawRect(context, third, kBackgroundType, gfx::Rect(300, 100, 50, 50)); - DrawRect(context, first, kForegroundType, gfx::Rect(100, 100, 100, 100)); - DrawRect(context, second, kForegroundType, gfx::Rect(100, 100, 50, 200)); - DrawRect(context, third, kForegroundType, gfx::Rect(300, 100, 50, 50)); + EXPECT_EQ(kCached, DrawRect(context, first, kBackgroundType, + gfx::Rect(100, 100, 100, 100))); + EXPECT_EQ(kRepaintedCachedItem, DrawRect(context, second, kBackgroundType, + gfx::Rect(100, 100, 50, 200))); + EXPECT_EQ(kCached, DrawRect(context, third, kBackgroundType, + gfx::Rect(300, 100, 50, 50))); + EXPECT_EQ(kCached, DrawRect(context, first, kForegroundType, + gfx::Rect(100, 100, 100, 100))); + EXPECT_EQ(kRepaintedCachedItem, DrawRect(context, second, kForegroundType, + gfx::Rect(100, 100, 50, 200))); + EXPECT_EQ(kCached, DrawRect(context, third, kForegroundType, + gfx::Rect(300, 100, 50, 50))); EXPECT_EQ(4u, NumCachedNewItems()); EXPECT_EQ(0u, NumCachedNewSubsequences()); #if DCHECK_IS_ON() - EXPECT_EQ(2u, NumIndexedItems()); - EXPECT_EQ(4u, NumSequentialMatches()); + EXPECT_EQ(0u, NumIndexedItems()); + EXPECT_EQ(6u, NumSequentialMatches()); EXPECT_EQ(0u, NumOutOfOrderMatches()); #endif } @@ -338,10 +409,14 @@ first.Invalidate(); second.Invalidate(); - DrawRect(context, first, kBackgroundType, gfx::Rect(100, 100, 150, 150)); - DrawRect(context, first, kForegroundType, gfx::Rect(100, 100, 150, 150)); - DrawRect(context, second, kBackgroundType, gfx::Rect(150, 250, 100, 100)); - DrawRect(context, second, kForegroundType, gfx::Rect(150, 250, 100, 100)); + EXPECT_EQ(kPaintedNew, DrawRect(context, first, kBackgroundType, + gfx::Rect(100, 100, 150, 150))); + EXPECT_EQ(kPaintedNew, DrawRect(context, first, kForegroundType, + gfx::Rect(100, 100, 150, 150))); + EXPECT_EQ(kRepaintedCachedItem, DrawRect(context, second, kBackgroundType, + gfx::Rect(150, 250, 100, 100))); + EXPECT_EQ(kRepaintedCachedItem, DrawRect(context, second, kForegroundType, + gfx::Rect(150, 250, 100, 100))); EXPECT_EQ(0u, NumCachedNewItems()); EXPECT_EQ(0u, NumCachedNewSubsequences()); } @@ -356,8 +431,10 @@ { CommitCycleScope cycle_scope(GetPaintController()); InitRootChunk(); - DrawRect(context, second, kBackgroundType, gfx::Rect(150, 250, 100, 100)); - DrawRect(context, second, kForegroundType, gfx::Rect(150, 250, 100, 100)); + EXPECT_EQ(kCached, DrawRect(context, second, kBackgroundType, + gfx::Rect(150, 250, 100, 100))); + EXPECT_EQ(kCached, DrawRect(context, second, kForegroundType, + gfx::Rect(150, 250, 100, 100))); EXPECT_EQ(2u, NumCachedNewItems()); EXPECT_EQ(0u, NumCachedNewSubsequences()); @@ -398,10 +475,14 @@ first.Invalidate(); second.Invalidate(); - DrawRect(context, first, kBackgroundType, gfx::Rect(150, 150, 100, 100)); - DrawRect(context, first, kForegroundType, gfx::Rect(150, 150, 100, 100)); - DrawRect(context, second, kBackgroundType, gfx::Rect(200, 200, 50, 50)); - DrawRect(context, second, kForegroundType, gfx::Rect(200, 200, 50, 50)); + EXPECT_EQ(kRepaintedCachedItem, DrawRect(context, first, kBackgroundType, + gfx::Rect(150, 150, 100, 100))); + EXPECT_EQ(kRepaintedCachedItem, DrawRect(context, first, kForegroundType, + gfx::Rect(150, 150, 100, 100))); + EXPECT_EQ(kPaintedNew, DrawRect(context, second, kBackgroundType, + gfx::Rect(200, 200, 50, 50))); + EXPECT_EQ(kPaintedNew, DrawRect(context, second, kForegroundType, + gfx::Rect(200, 200, 50, 50))); EXPECT_EQ(0u, NumCachedNewItems()); EXPECT_EQ(0u, NumCachedNewSubsequences()); } @@ -418,8 +499,10 @@ InitRootChunk(); first.Invalidate(); second.Invalidate(); - DrawRect(context, first, kBackgroundType, gfx::Rect(100, 100, 150, 150)); - DrawRect(context, first, kForegroundType, gfx::Rect(100, 100, 150, 150)); + EXPECT_EQ(kRepaintedCachedItem, DrawRect(context, first, kBackgroundType, + gfx::Rect(100, 100, 150, 150))); + EXPECT_EQ(kRepaintedCachedItem, DrawRect(context, first, kForegroundType, + gfx::Rect(100, 100, 150, 150))); EXPECT_EQ(0u, NumCachedNewItems()); EXPECT_EQ(0u, NumCachedNewSubsequences()); } @@ -463,8 +546,10 @@ { CommitCycleScope cycle_scope(GetPaintController()); InitRootChunk(); - DrawRect(context, first, kBackgroundType, gfx::Rect(100, 100, 150, 150)); - DrawRect(context, second, kBackgroundType, gfx::Rect(100, 100, 150, 150)); + EXPECT_EQ(kRepaintedCachedItem, DrawRect(context, first, kBackgroundType, + gfx::Rect(100, 100, 150, 150))); + EXPECT_EQ(kCached, DrawRect(context, second, kBackgroundType, + gfx::Rect(100, 100, 150, 150))); } EXPECT_THAT(GetPaintController().GetDisplayItemList(), @@ -533,18 +618,22 @@ // Simulate the situation when |container1| gets a z-index that is greater // than that of |container2|. - DrawRect(context, container2, kBackgroundType, - gfx::Rect(100, 200, 100, 100)); - DrawRect(context, content2, kBackgroundType, gfx::Rect(100, 200, 50, 200)); - DrawRect(context, content2, kForegroundType, gfx::Rect(100, 200, 50, 200)); - DrawRect(context, container2, kForegroundType, - gfx::Rect(100, 200, 100, 100)); - DrawRect(context, container1, kBackgroundType, - gfx::Rect(100, 100, 100, 100)); - DrawRect(context, content1, kBackgroundType, gfx::Rect(100, 100, 50, 200)); - DrawRect(context, content1, kForegroundType, gfx::Rect(100, 100, 50, 200)); - DrawRect(context, container1, kForegroundType, - gfx::Rect(100, 100, 100, 100)); + EXPECT_EQ(kCached, DrawRect(context, container2, kBackgroundType, + gfx::Rect(100, 200, 100, 100))); + EXPECT_EQ(kCached, DrawRect(context, content2, kBackgroundType, + gfx::Rect(100, 200, 50, 200))); + EXPECT_EQ(kCached, DrawRect(context, content2, kForegroundType, + gfx::Rect(100, 200, 50, 200))); + EXPECT_EQ(kCached, DrawRect(context, container2, kForegroundType, + gfx::Rect(100, 200, 100, 100))); + EXPECT_EQ(kCached, DrawRect(context, container1, kBackgroundType, + gfx::Rect(100, 100, 100, 100))); + EXPECT_EQ(kCached, DrawRect(context, content1, kBackgroundType, + gfx::Rect(100, 100, 50, 200))); + EXPECT_EQ(kCached, DrawRect(context, content1, kForegroundType, + gfx::Rect(100, 100, 50, 200))); + EXPECT_EQ(kCached, DrawRect(context, container1, kForegroundType, + gfx::Rect(100, 100, 100, 100))); } EXPECT_THAT(GetPaintController().GetDisplayItemList(), @@ -604,18 +693,24 @@ // Simulate the situation when |container1| gets a z-index that is greater // than that of |container2|, and |container1| is invalidated. container1.Invalidate(); - DrawRect(context, container2, kBackgroundType, - gfx::Rect(100, 200, 100, 100)); - DrawRect(context, content2, kBackgroundType, gfx::Rect(100, 200, 50, 200)); - DrawRect(context, content2, kForegroundType, gfx::Rect(100, 200, 50, 200)); - DrawRect(context, container2, kForegroundType, - gfx::Rect(100, 200, 100, 100)); - DrawRect(context, container1, kBackgroundType, - gfx::Rect(100, 100, 100, 100)); - DrawRect(context, content1, kBackgroundType, gfx::Rect(100, 100, 50, 200)); - DrawRect(context, content1, kForegroundType, gfx::Rect(100, 100, 50, 200)); - DrawRect(context, container1, kForegroundType, - gfx::Rect(100, 100, 100, 100)); + EXPECT_EQ(kCached, DrawRect(context, container2, kBackgroundType, + gfx::Rect(100, 200, 100, 100))); + EXPECT_EQ(kCached, DrawRect(context, content2, kBackgroundType, + gfx::Rect(100, 200, 50, 200))); + EXPECT_EQ(kCached, DrawRect(context, content2, kForegroundType, + gfx::Rect(100, 200, 50, 200))); + EXPECT_EQ(kCached, DrawRect(context, container2, kForegroundType, + gfx::Rect(100, 200, 100, 100))); + EXPECT_EQ(kRepaintedCachedItem, + DrawRect(context, container1, kBackgroundType, + gfx::Rect(100, 100, 100, 100))); + EXPECT_EQ(kCached, DrawRect(context, content1, kBackgroundType, + gfx::Rect(100, 100, 50, 200))); + EXPECT_EQ(kCached, DrawRect(context, content1, kForegroundType, + gfx::Rect(100, 100, 50, 200))); + EXPECT_EQ(kRepaintedCachedItem, + DrawRect(context, container1, kForegroundType, + gfx::Rect(100, 100, 100, 100))); } EXPECT_THAT(GetPaintController().GetDisplayItemList(), @@ -677,9 +772,11 @@ CommitCycleScope cycle_scope(GetPaintController()); GetPaintController().UpdateCurrentPaintChunkProperties(root_id, root, root_properties); - DrawRect(context, root, kBackgroundType, gfx::Rect(100, 100, 100, 100)); + EXPECT_EQ(kCached, DrawRect(context, root, kBackgroundType, + gfx::Rect(100, 100, 100, 100))); EXPECT_TRUE(GetPaintController().UseCachedSubsequenceIfPossible(container)); - DrawRect(context, root, kForegroundType, gfx::Rect(100, 100, 100, 100)); + EXPECT_EQ(kCached, DrawRect(context, root, kForegroundType, + gfx::Rect(100, 100, 100, 100))); } // |container| should still receive its own PaintChunk because it is a cached @@ -782,14 +879,14 @@ container2_id, container2, container2_properties); SubsequenceRecorder r(context, container2); - DrawRect(context, container2, kBackgroundType, - gfx::Rect(100, 200, 100, 100)); - DrawRect(context, content2, kBackgroundType, - gfx::Rect(100, 200, 50, 200)); - DrawRect(context, content2, kForegroundType, - gfx::Rect(100, 200, 50, 200)); - DrawRect(context, container2, kForegroundType, - gfx::Rect(100, 200, 100, 100)); + EXPECT_EQ(kCached, DrawRect(context, container2, kBackgroundType, + gfx::Rect(100, 200, 100, 100))); + EXPECT_EQ(kCached, DrawRect(context, content2, kBackgroundType, + gfx::Rect(100, 200, 50, 200))); + EXPECT_EQ(kCached, DrawRect(context, content2, kForegroundType, + gfx::Rect(100, 200, 50, 200))); + EXPECT_EQ(kCached, DrawRect(context, container2, kForegroundType, + gfx::Rect(100, 200, 100, 100))); } EXPECT_FALSE(SubsequenceRecorder::UseCachedSubsequenceIfPossible( context, container1)); @@ -798,14 +895,14 @@ container1_id, container1, container1_properties); SubsequenceRecorder r(context, container1); - DrawRect(context, container1, kBackgroundType, - gfx::Rect(100, 100, 100, 100)); - DrawRect(context, content1, kBackgroundType, - gfx::Rect(100, 100, 50, 200)); - DrawRect(context, content1, kForegroundType, - gfx::Rect(100, 100, 50, 200)); - DrawRect(context, container1, kForegroundType, - gfx::Rect(100, 100, 100, 100)); + EXPECT_EQ(kCached, DrawRect(context, container1, kBackgroundType, + gfx::Rect(100, 100, 100, 100))); + EXPECT_EQ(kCached, DrawRect(context, content1, kBackgroundType, + gfx::Rect(100, 100, 50, 200))); + EXPECT_EQ(kCached, DrawRect(context, content1, kForegroundType, + gfx::Rect(100, 100, 50, 200))); + EXPECT_EQ(kCached, DrawRect(context, container1, kForegroundType, + gfx::Rect(100, 100, 100, 100))); } } else { EXPECT_TRUE(SubsequenceRecorder::UseCachedSubsequenceIfPossible( @@ -911,19 +1008,19 @@ context, container2)); { SubsequenceRecorder r(context, container2); - DrawRect(context, container2, kBackgroundType, - gfx::Rect(100, 200, 100, 100)); - DrawRect(context, content2, kBackgroundType, - gfx::Rect(100, 200, 50, 200)); - DrawRect(context, content2, kForegroundType, - gfx::Rect(100, 200, 50, 200)); - DrawRect(context, container2, kForegroundType, - gfx::Rect(100, 200, 100, 100)); + EXPECT_EQ(kCached, DrawRect(context, container2, kBackgroundType, + gfx::Rect(100, 200, 100, 100))); + EXPECT_EQ(kCached, DrawRect(context, content2, kBackgroundType, + gfx::Rect(100, 200, 50, 200))); + EXPECT_EQ(kCached, DrawRect(context, content2, kForegroundType, + gfx::Rect(100, 200, 50, 200))); + EXPECT_EQ(kCached, DrawRect(context, container2, kForegroundType, + gfx::Rect(100, 200, 100, 100))); } - DrawRect(context, content1, kBackgroundType, - gfx::Rect(100, 100, 50, 200)); - DrawRect(context, content1, kForegroundType, - gfx::Rect(100, 100, 50, 200)); + EXPECT_EQ(kCached, DrawRect(context, content1, kBackgroundType, + gfx::Rect(100, 100, 50, 200))); + EXPECT_EQ(kCached, DrawRect(context, content1, kForegroundType, + gfx::Rect(100, 100, 50, 200))); } else { EXPECT_TRUE(SubsequenceRecorder::UseCachedSubsequenceIfPossible( context, container2)); @@ -1009,19 +1106,20 @@ if (RuntimeEnabledFeatures::PaintUnderInvalidationCheckingEnabled()) { EXPECT_FALSE(DrawingRecorder::UseCachedDrawingIfPossible( context, content1b, kBackgroundType)); - DrawRect(context, content1b, kBackgroundType, rect); + EXPECT_EQ(kCached, DrawRect(context, content1b, kBackgroundType, rect)); EXPECT_FALSE(DrawingRecorder::UseCachedDrawingIfPossible( context, content1a, kBackgroundType)); - DrawRect(context, content1a, kBackgroundType, rect); + EXPECT_EQ(kCached, DrawRect(context, content1a, kBackgroundType, rect)); { EXPECT_FALSE(SubsequenceRecorder::UseCachedSubsequenceIfPossible( context, container2)); SubsequenceRecorder r(context, container2); - DrawRect(context, container2, kBackgroundType, rect); + EXPECT_EQ(kCached, + DrawRect(context, container2, kBackgroundType, rect)); } EXPECT_FALSE(DrawingRecorder::UseCachedDrawingIfPossible( context, content3, kBackgroundType)); - DrawRect(context, content3, kBackgroundType, rect); + EXPECT_EQ(kCached, DrawRect(context, content3, kBackgroundType, rect)); } else { EXPECT_TRUE(DrawingRecorder::UseCachedDrawingIfPossible( context, content1b, kBackgroundType)); @@ -1102,7 +1200,8 @@ ScopedPaintChunkProperties root_chunk_properties( GetPaintController(), DefaultPaintChunkProperties(), root, kBackgroundType); - DrawRect(context, root, kBackgroundType, gfx::Rect(100, 100, 100, 100)); + EXPECT_EQ(kCached, DrawRect(context, root, kBackgroundType, + gfx::Rect(100, 100, 100, 100))); if (RuntimeEnabledFeatures::PaintUnderInvalidationCheckingEnabled()) { EXPECT_FALSE( @@ -1112,7 +1211,8 @@ EXPECT_TRUE( GetPaintController().UseCachedSubsequenceIfPossible(container)); } - DrawRect(context, root, kForegroundType, gfx::Rect(100, 100, 100, 100)); + EXPECT_EQ(kCached, DrawRect(context, root, kForegroundType, + gfx::Rect(100, 100, 100, 100))); } // The second paint should produce the exactly same results. @@ -1170,14 +1270,16 @@ CommitCycleScope cycle_scope(GetPaintController()); GetPaintController().UpdateCurrentPaintChunkProperties( container1_id, container1, container1_properties); - DrawRect(context, container1, kBackgroundType, - gfx::Rect(100, 100, 100, 100)); - DrawRect(context, content1, kBackgroundType, gfx::Rect(100, 100, 50, 200)); - DrawRect(context, content2, kBackgroundType, gfx::Rect(100, 200, 50, 200)); + EXPECT_EQ(kCached, DrawRect(context, container1, kBackgroundType, + gfx::Rect(100, 100, 100, 100))); + EXPECT_EQ(kCached, DrawRect(context, content1, kBackgroundType, + gfx::Rect(100, 100, 50, 200))); + EXPECT_EQ(kCached, DrawRect(context, content2, kBackgroundType, + gfx::Rect(100, 200, 50, 200))); GetPaintController().UpdateCurrentPaintChunkProperties( container2_id, container2, container2_properties); - DrawRect(context, container2, kBackgroundType, - gfx::Rect(100, 200, 100, 100)); + EXPECT_EQ(kCached, DrawRect(context, container2, kBackgroundType, + gfx::Rect(100, 200, 100, 100))); EXPECT_EQ(4u, NumCachedNewItems()); EXPECT_EQ(0u, NumCachedNewSubsequences()); @@ -1225,10 +1327,14 @@ { CommitCycleScope cycle_scope(GetPaintController()); InitRootChunk(); - DrawRect(context, client, kType2, gfx::Rect(100, 100, 50, 200)); - DrawRect(context, client, kType3, gfx::Rect(100, 100, 50, 200)); - DrawRect(context, client, kType1, gfx::Rect(100, 100, 100, 100)); - DrawRect(context, client, kType4, gfx::Rect(100, 100, 100, 100)); + EXPECT_EQ(kCached, + DrawRect(context, client, kType2, gfx::Rect(100, 100, 50, 200))); + EXPECT_EQ(kCached, + DrawRect(context, client, kType3, gfx::Rect(100, 100, 50, 200))); + EXPECT_EQ(kCached, + DrawRect(context, client, kType1, gfx::Rect(100, 100, 100, 100))); + EXPECT_EQ(kCached, + DrawRect(context, client, kType4, gfx::Rect(100, 100, 100, 100))); } } @@ -1349,8 +1455,8 @@ SubsequenceRecorder r(context, content2); GetPaintController().UpdateCurrentPaintChunkProperties( content2_id, content2, content2_properties); - DrawRect(context, content2, kForegroundType, - gfx::Rect(100, 200, 50, 200)); + EXPECT_EQ(kPaintedNew, DrawRect(context, content2, kForegroundType, + gfx::Rect(100, 200, 50, 200))); } // Repaint container1 with foreground only. { @@ -1367,10 +1473,10 @@ SubsequenceRecorder inner_r(context, content1); GetPaintController().UpdateCurrentPaintChunkProperties( content1_id, content1, content1_properties); - DrawRect(context, content1, kBackgroundType, - gfx::Rect(100, 100, 50, 200)); - DrawRect(context, content1, kForegroundType, - gfx::Rect(100, 100, 50, 200)); + EXPECT_EQ(kCached, DrawRect(context, content1, kBackgroundType, + gfx::Rect(100, 100, 50, 200))); + EXPECT_EQ(kCached, DrawRect(context, content1, kForegroundType, + gfx::Rect(100, 100, 50, 200))); } else { EXPECT_TRUE(SubsequenceRecorder::UseCachedSubsequenceIfPossible( context, content1)); @@ -1378,16 +1484,17 @@ GetPaintController().UpdateCurrentPaintChunkProperties( container1_foreground_id, container1, container1_foreground_properties); - DrawRect(context, container1, kForegroundType, - gfx::Rect(100, 100, 100, 100)); + EXPECT_EQ(kRepaintedCachedItem, + DrawRect(context, container1, kForegroundType, + gfx::Rect(100, 100, 100, 100))); } EXPECT_EQ(2u, NumCachedNewItems()); EXPECT_EQ(1u, NumCachedNewSubsequences()); #if DCHECK_IS_ON() - EXPECT_EQ(0u, NumIndexedItems()); + EXPECT_EQ(6u, NumIndexedItems()); EXPECT_EQ(0u, NumSequentialMatches()); - EXPECT_EQ(0u, NumOutOfOrderMatches()); + EXPECT_EQ(1u, NumOutOfOrderMatches()); #endif } @@ -1620,11 +1727,12 @@ InitRootChunk(); // Draw again with nothing invalidated. EXPECT_TRUE(ClientCacheIsValid(multicol)); - DrawRect(context, multicol, kBackgroundType, gfx::Rect(100, 200, 100, 100)); + EXPECT_EQ(kCached, DrawRect(context, multicol, kBackgroundType, + gfx::Rect(100, 200, 100, 100))); GetPaintController().BeginSkippingCache(); - DrawRect(context, content, kForegroundType, rect1); - DrawRect(context, content, kForegroundType, rect2); + EXPECT_EQ(kPaintedNew, DrawRect(context, content, kForegroundType, rect1)); + EXPECT_EQ(kPaintedNew, DrawRect(context, content, kForegroundType, rect2)); GetPaintController().EndSkippingCache(); EXPECT_EQ(1u, NumCachedNewItems()); @@ -1653,12 +1761,13 @@ InitRootChunk(); // Now the multicol becomes 3 columns and repaints. multicol.Invalidate(); - DrawRect(context, multicol, kBackgroundType, gfx::Rect(100, 100, 100, 100)); + EXPECT_EQ(kRepaintedCachedItem, DrawRect(context, multicol, kBackgroundType, + gfx::Rect(100, 100, 100, 100))); GetPaintController().BeginSkippingCache(); - DrawRect(context, content, kForegroundType, rect1); - DrawRect(context, content, kForegroundType, rect2); - DrawRect(context, content, kForegroundType, rect3); + EXPECT_EQ(kPaintedNew, DrawRect(context, content, kForegroundType, rect1)); + EXPECT_EQ(kPaintedNew, DrawRect(context, content, kForegroundType, rect2)); + EXPECT_EQ(kPaintedNew, DrawRect(context, content, kForegroundType, rect3)); GetPaintController().EndSkippingCache(); // We should repaint everything on invalidation of the scope container. @@ -1720,11 +1829,11 @@ CommitCycleScope cycle_scope(GetPaintController()); InitRootChunk(); // Draw again with nothing invalidated. - DrawRect(context, content, kBackgroundType, rect1); + EXPECT_EQ(kPaintedNew, DrawRect(context, content, kBackgroundType, rect1)); GetPaintController().BeginSkippingCache(); - DrawRect(context, content, kForegroundType, rect2); + EXPECT_EQ(kPaintedNew, DrawRect(context, content, kForegroundType, rect2)); GetPaintController().EndSkippingCache(); - DrawRect(context, content, kForegroundType, rect3); + EXPECT_EQ(kPaintedNew, DrawRect(context, content, kForegroundType, rect3)); EXPECT_EQ(0u, NumCachedNewItems()); EXPECT_EQ(0u, NumCachedNewSubsequences()); @@ -1902,8 +2011,10 @@ { CommitCycleScope cycle_scope(GetPaintController()); InitRootChunk(); - DrawRect(context, third, kBackgroundType, gfx::Rect(100, 100, 100, 100)); - DrawRect(context, fourth, kBackgroundType, gfx::Rect(100, 100, 50, 50)); + EXPECT_EQ(kCached, DrawRect(context, third, kBackgroundType, + gfx::Rect(100, 100, 100, 100))); + EXPECT_EQ(kCached, DrawRect(context, fourth, kBackgroundType, + gfx::Rect(100, 100, 50, 50))); EXPECT_EQ(2u, NumCachedNewItems()); EXPECT_EQ(0u, NumCachedNewSubsequences()); @@ -1926,10 +2037,14 @@ { CommitCycleScope cycle_scope(GetPaintController()); InitRootChunk(); - DrawRect(context, first, kBackgroundType, gfx::Rect(100, 100, 300, 300)); - DrawRect(context, second, kBackgroundType, gfx::Rect(100, 100, 200, 200)); - DrawRect(context, third, kBackgroundType, gfx::Rect(100, 100, 100, 100)); - DrawRect(context, fourth, kBackgroundType, gfx::Rect(100, 100, 50, 50)); + EXPECT_EQ(kPaintedNew, DrawRect(context, first, kBackgroundType, + gfx::Rect(100, 100, 300, 300))); + EXPECT_EQ(kPaintedNew, DrawRect(context, second, kBackgroundType, + gfx::Rect(100, 100, 200, 200))); + EXPECT_EQ(kCached, DrawRect(context, third, kBackgroundType, + gfx::Rect(100, 100, 100, 100))); + EXPECT_EQ(kCached, DrawRect(context, fourth, kBackgroundType, + gfx::Rect(100, 100, 50, 50))); EXPECT_EQ(2u, NumCachedNewItems()); EXPECT_EQ(0u, NumCachedNewSubsequences());
diff --git a/third_party/blink/renderer/platform/graphics/paint/paint_controller_test.h b/third_party/blink/renderer/platform/graphics/paint/paint_controller_test.h index 589fcb7..7c2ad22 100644 --- a/third_party/blink/renderer/platform/graphics/paint/paint_controller_test.h +++ b/third_party/blink/renderer/platform/graphics/paint/paint_controller_test.h
@@ -5,7 +5,10 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_PAINT_PAINT_CONTROLLER_TEST_H_ #define THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_PAINT_PAINT_CONTROLLER_TEST_H_ +#include <utility> + #include "base/dcheck_is_on.h" +#include "base/functional/function_ref.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/platform/graphics/paint/drawing_recorder.h" @@ -35,22 +38,33 @@ class PaintControllerTestBase : public testing::Test { public: - static void DrawNothing(GraphicsContext& context, - const DisplayItemClient& client, - DisplayItem::Type type) { - if (DrawingRecorder::UseCachedDrawingIfPossible(context, client, type)) - return; - DrawingRecorder recorder(context, client, type, gfx::Rect()); + enum DrawResult { + kCached, + kPaintedNew, + kRepaintedCachedItem, + }; + + static DrawResult Draw(GraphicsContext& context, + const DisplayItemClient& client, + DisplayItem::Type type, + base::FunctionRef<void()> draw_function); + + static DrawResult DrawNothing(GraphicsContext& context, + const DisplayItemClient& client, + DisplayItem::Type type) { + return Draw(context, client, type, [&]() { + DrawingRecorder recorder(context, client, type, gfx::Rect()); + }); } - static void DrawRect(GraphicsContext& context, - const DisplayItemClient& client, - DisplayItem::Type type, - const gfx::Rect& bounds) { - if (DrawingRecorder::UseCachedDrawingIfPossible(context, client, type)) - return; - DrawingRecorder recorder(context, client, type, bounds); - context.DrawRect(bounds, AutoDarkMode::Disabled()); + static DrawResult DrawRect(GraphicsContext& context, + const DisplayItemClient& client, + DisplayItem::Type type, + const gfx::Rect& bounds) { + return Draw(context, client, type, [&]() { + DrawingRecorder recorder(context, client, type, bounds); + context.DrawRect(bounds, AutoDarkMode::Disabled()); + }); } protected:
diff --git a/third_party/blink/renderer/platform/wtf/BUILD.gn b/third_party/blink/renderer/platform/wtf/BUILD.gn index 9772b10..74df4627 100644 --- a/third_party/blink/renderer/platform/wtf/BUILD.gn +++ b/third_party/blink/renderer/platform/wtf/BUILD.gn
@@ -42,7 +42,6 @@ "allocator/partition_allocator.h", "allocator/partitions.cc", "allocator/partitions.h", - "assertions.cc", "assertions.h", "atomic_operations.cc", "atomic_operations.h", @@ -95,8 +94,6 @@ "pod_red_black_tree.h", "ref_counted.h", "sanitizers.h", - "scoped_logger.cc", - "scoped_logger.h", "sequence_bound.h", "shared_buffer.cc", "shared_buffer.h", @@ -319,7 +316,6 @@ "pod_red_black_tree_test.cc", "pod_tree_test_helpers.cc", "pod_tree_test_helpers.h", - "scoped_logger_test.cc", "sequence_bound_test.cc", "shared_buffer_test.cc", "testing/run_all_tests.cc",
diff --git a/third_party/blink/renderer/platform/wtf/ScopedLogger.md b/third_party/blink/renderer/platform/wtf/ScopedLogger.md deleted file mode 100644 index 868ea26..0000000 --- a/third_party/blink/renderer/platform/wtf/ScopedLogger.md +++ /dev/null
@@ -1,101 +0,0 @@ -# Debugging with ScopedLogger - -## Overview - -ScopedLogger is a logger that shows nested calls by indenting. - -For example, if you were debugging a layout issue you could add a ScopedLogger -to the top of the `LayoutBlock::layout` function: - -```c++ -void LayoutBlock::layout() -{ - WTF_CREATE_SCOPED_LOGGER(logger, "layout %s", debugName().utf8().data()); - ... -``` - -The arguments of the `WTF_CREATE_SCOPED_LOGGER` macro are the name of the -object, followed by the first log message, followed by printf-style varargs. -In the above example, the log message includes the debug name of the block that -is currently being laid out. - -ScopedLogger wraps log messages in parentheses, with indentation proportional to -the number of instances. This makes it easy to see the flow of control in the -output, particularly when instrumenting recursive functions. Here is some of -the output of the above example when laying out www.google.com: - -``` -( layout LayoutView #document - ( layout LayoutBlockFlow HTML - ( layout LayoutBlockFlow BODY id='gsr' class='hp vasq' - ( layout LayoutBlockFlow (relative positioned) DIV id='viewport' class='ctr-p' - ( layout LayoutBlockFlow DIV id='doc-info' ) - ( layout LayoutBlockFlow DIV id='cst' ) - ( layout LayoutBlockFlow (positioned) A ) - ( layout LayoutBlockFlow (positioned) DIV id='searchform' class='jhp' ) - ) - ) - ) -) -``` - -## Appending to a ScopedLogger - -Every ScopedLogger has an initial log message, which is often sufficient. But -you can also write additional messages to an existing ScopedLogger with -`WTF_APPEND_SCOPED_LOGGER`. For example: - -```c++ - // further down in LayoutBlock::layout... - - if (needsScrollAnchoring) { - WTF_APPEND_SCOPED_LOGGER(logger, "restoring scroll anchor"); - getScrollableArea()->scrollAnchor().restore(); - } -``` - -## Conditional ScopedLoggers - -It's often useful to create a ScopedLogger only if some condition is met. -Unfortunately, the following doesn't work correctly: - -```c++ -void foo() { - if (condition) { - WTF_CREATE_SCOPED_LOGGER(logger, "foo, with condition"); - // Oops: logger exits scope prematurely! - } - bar(); // any ScopedLogger in bar won't nest -} -``` - -To guard a ScopedLogger construction with a condition without restricting its -scope, use `WTF_CREATE_SCOPED_LOGGER_IF`: - -```c++ -void foo() { - WTF_CREATE_SCOPED_LOGGER_IF(logger, condition, "message"); - bar(); -} -``` - -## Requirements - -The ScopedLogger class and associated macros are defined in -[scoped_logger.h](scoped_logger.h). ScopedLogger can't be used outside of -Blink code yet. - -The ScopedLogger macros work in debug builds by default. They are compiled out -of release builds, unless your GN args file includes one of the following: - -* `dcheck_always_on`: enables assertions and ScopedLogger - -The macro names are cumbersome to type, but most editors can be configured to -make this easier. For example, you can add the following to a Sublime Text key -binding file to make Ctrl+Alt+L insert a ScopedLogger: - -``` - { "keys": ["ctrl+alt+l"], "command": "insert", - "args": {"characters": "WTF_CREATE_SCOPED_LOGGER(logger, \"msg\");"} - } -```
diff --git a/third_party/blink/renderer/platform/wtf/assertions.cc b/third_party/blink/renderer/platform/wtf/assertions.cc deleted file mode 100644 index c25441ec..0000000 --- a/third_party/blink/renderer/platform/wtf/assertions.cc +++ /dev/null
@@ -1,77 +0,0 @@ -/* - * Copyright (C) 2003, 2006, 2007 Apple Inc. All rights reserved. - * Copyright (C) 2007-2009 Torch Mobile, Inc. - * Copyright (C) 2011 University of Szeged. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -// The vprintf_stderr_common function triggers this error in the Mac build. -// Feel free to remove this pragma if this file builds on Mac. -// According to -// http://gcc.gnu.org/onlinedocs/gcc-4.2.1/gcc/Diagnostic-Pragmas.html#Diagnostic-Pragmas -// we need to place this directive before any data or functions are defined. -#pragma GCC diagnostic ignored "-Wmissing-format-attribute" - -#include "third_party/blink/renderer/platform/wtf/assertions.h" - -#include "build/build_config.h" - -#if BUILDFLAG(IS_MAC) -#include <asl.h> -#elif BUILDFLAG(IS_ANDROID) -#include <android/log.h> -#elif BUILDFLAG(IS_WIN) -#include <windows.h> -#endif - -PRINTF_FORMAT(1, 0) -void vprintf_stderr_common(const char* format, va_list args) { -#if BUILDFLAG(IS_MAC) - va_list copyOfArgs; - va_copy(copyOfArgs, args); - asl_vlog(0, 0, ASL_LEVEL_NOTICE, format, copyOfArgs); - va_end(copyOfArgs); -#elif BUILDFLAG(IS_ANDROID) - __android_log_vprint(ANDROID_LOG_WARN, "WebKit", format, args); -#elif BUILDFLAG(IS_WIN) - if (IsDebuggerPresent()) { - size_t size = 1024; - - do { - char* buffer = (char*)malloc(size); - if (!buffer) - break; - - if (_vsnprintf(buffer, size, format, args) != -1) { - OutputDebugStringA(buffer); - free(buffer); - break; - } - - free(buffer); - size *= 2; - } while (size > 1024); - } -#endif - vfprintf(stderr, format, args); -}
diff --git a/third_party/blink/renderer/platform/wtf/assertions.h b/third_party/blink/renderer/platform/wtf/assertions.h index ee91a3d..6f87107 100644 --- a/third_party/blink/renderer/platform/wtf/assertions.h +++ b/third_party/blink/renderer/platform/wtf/assertions.h
@@ -34,9 +34,6 @@ #include "base/logging.h" #include "third_party/blink/renderer/platform/wtf/wtf_export.h" -// New code shouldn't use this function. This function will be deprecated. -void vprintf_stderr_common(const char* format, va_list args); - #define DCHECK_AT(assertion, file, line) \ LAZY_STREAM(logging::LogMessage(file, line, #assertion).stream(), \ DCHECK_IS_ON() ? !(assertion) : false)
diff --git a/third_party/blink/renderer/platform/wtf/scoped_logger.cc b/third_party/blink/renderer/platform/wtf/scoped_logger.cc deleted file mode 100644 index 9d0b87ff..0000000 --- a/third_party/blink/renderer/platform/wtf/scoped_logger.cc +++ /dev/null
@@ -1,102 +0,0 @@ -// Copyright 2017 The Chromium Authors -// 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/platform/wtf/scoped_logger.h" - -#include "build/build_config.h" -#include "third_party/blink/renderer/platform/wtf/assertions.h" -#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h" -#include "third_party/blink/renderer/platform/wtf/thread_specific.h" - -#if DCHECK_IS_ON() - -namespace WTF { - -ScopedLogger::ScopedLogger(bool condition, const char* format, ...) - : parent_(condition ? Current() : nullptr), multiline_(false) { - if (!condition) - return; - - va_list args; - va_start(args, format); - Init(format, args); - va_end(args); -} - -ScopedLogger::~ScopedLogger() { - if (Current() == this) { - if (multiline_) - Indent(); - else - Print(" "); - Print(")\n"); - Current() = parent_; - } -} - -void ScopedLogger::SetPrintFuncForTests(PrintFunctionPtr ptr) { - print_func_ = ptr; -} - -void ScopedLogger::Init(const char* format, va_list args) { - Current() = this; - if (parent_) - parent_->WriteNewlineIfNeeded(); - Indent(); - Print("( "); - print_func_(format, args); -} - -void ScopedLogger::WriteNewlineIfNeeded() { - if (!multiline_) { - Print("\n"); - multiline_ = true; - } -} - -void ScopedLogger::Indent() { - if (parent_) { - parent_->Indent(); - PrintIndent(); - } -} - -void ScopedLogger::Log(const char* format, ...) { - if (Current() != this) - return; - - va_list args; - va_start(args, format); - - WriteNewlineIfNeeded(); - Indent(); - PrintIndent(); - print_func_(format, args); - Print("\n"); - - va_end(args); -} - -void ScopedLogger::Print(const char* format, ...) { - va_list args; - va_start(args, format); - print_func_(format, args); - va_end(args); -} - -void ScopedLogger::PrintIndent() { - Print(" "); -} - -ScopedLogger*& ScopedLogger::Current() { - DEFINE_THREAD_SAFE_STATIC_LOCAL(ThreadSpecific<ScopedLogger*>, ref, ()); - return *ref; -} - -ScopedLogger::PrintFunctionPtr ScopedLogger::print_func_ = - vprintf_stderr_common; - -} // namespace WTF - -#endif // DCHECK_IS_ON
diff --git a/third_party/blink/renderer/platform/wtf/scoped_logger.h b/third_party/blink/renderer/platform/wtf/scoped_logger.h deleted file mode 100644 index a5cf8fde..0000000 --- a/third_party/blink/renderer/platform/wtf/scoped_logger.h +++ /dev/null
@@ -1,74 +0,0 @@ -// Copyright 2017 The Chromium Authors -// 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_PLATFORM_WTF_SCOPED_LOGGER_H_ -#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_WTF_SCOPED_LOGGER_H_ - -#include "base/dcheck_is_on.h" -#include "base/gtest_prod_util.h" -#include "base/logging.h" -#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h" -#include "third_party/blink/renderer/platform/wtf/wtf_export.h" - -namespace WTF { - -#if !DCHECK_IS_ON() - -#define WTF_CREATE_SCOPED_LOGGER(...) ((void)0) -#define WTF_CREATE_SCOPED_LOGGER_IF(...) ((void)0) -#define WTF_APPEND_SCOPED_LOGGER(...) ((void)0) - -#else - -// ScopedLogger wraps log messages in parentheses, with indentation proportional -// to the number of instances. This makes it easy to see the flow of control in -// the output, particularly when instrumenting recursive functions. -// -// NOTE: This class is a debugging tool, not intended for use by checked-in -// code. Please do not remove it. -// -class WTF_EXPORT ScopedLogger { - DISALLOW_NEW(); - - public: - // The first message is passed to the constructor. Additional messages for - // the same scope can be added with log(). If condition is false, produce no - // output and do not create a scope. - PRINTF_FORMAT(3, 4) ScopedLogger(bool condition, const char* format, ...); - ScopedLogger(const ScopedLogger&) = delete; - ScopedLogger& operator=(const ScopedLogger&) = delete; - ~ScopedLogger(); - PRINTF_FORMAT(2, 3) void Log(const char* format, ...); - - private: - FRIEND_TEST_ALL_PREFIXES(ScopedLoggerTest, ScopedLogger); - using PrintFunctionPtr = void (*)(const char* format, va_list args); - - // Note: not thread safe. - static void SetPrintFuncForTests(PrintFunctionPtr); - - void Init(const char* format, va_list args); - void WriteNewlineIfNeeded(); - void Indent(); - void Print(const char* format, ...); - void PrintIndent(); - static ScopedLogger*& Current(); - - ScopedLogger* const parent_; - bool multiline_; // The ')' will go on the same line if there is only one - // entry. - static PrintFunctionPtr print_func_; -}; - -#define WTF_CREATE_SCOPED_LOGGER(name, ...) \ - WTF::ScopedLogger name(true, __VA_ARGS__) -#define WTF_CREATE_SCOPED_LOGGER_IF(name, condition, ...) \ - WTF::ScopedLogger name(condition, __VA_ARGS__) -#define WTF_APPEND_SCOPED_LOGGER(name, ...) (name.Log(__VA_ARGS__)) - -#endif // !DCHECK_IS_ON() - -} // namespace WTF - -#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_WTF_SCOPED_LOGGER_H_
diff --git a/third_party/blink/renderer/platform/wtf/scoped_logger_test.cc b/third_party/blink/renderer/platform/wtf/scoped_logger_test.cc deleted file mode 100644 index 7b4926d..0000000 --- a/third_party/blink/renderer/platform/wtf/scoped_logger_test.cc +++ /dev/null
@@ -1,49 +0,0 @@ -// Copyright 2017 The Chromium Authors -// 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/platform/wtf/scoped_logger.h" - -#include "testing/gtest/include/gtest/gtest.h" -#include "third_party/blink/renderer/platform/wtf/text/string_builder.h" - -namespace WTF { - -#if DCHECK_IS_ON() -static const int kPrinterBufferSize = 256; -static char g_buffer[kPrinterBufferSize]; -static StringBuilder g_builder; - -static void Vprint(const char* format, va_list args) { - int written = vsnprintf(g_buffer, kPrinterBufferSize, format, args); - if (written > 0 && written < kPrinterBufferSize) - g_builder.Append(g_buffer); -} - -TEST(ScopedLoggerTest, ScopedLogger) { - ScopedLogger::SetPrintFuncForTests(Vprint); - { - WTF_CREATE_SCOPED_LOGGER(a, "a1"); - { - WTF_CREATE_SCOPED_LOGGER_IF(b, false, "b1"); - { - WTF_CREATE_SCOPED_LOGGER(c, "c"); - { WTF_CREATE_SCOPED_LOGGER(d, "d %d %s", -1, "hello"); } - } - WTF_APPEND_SCOPED_LOGGER(b, "b2"); - } - WTF_APPEND_SCOPED_LOGGER(a, "a2 %.1f", 0.5); - } - - EXPECT_EQ( - "( a1\n" - " ( c\n" - " ( d -1 hello )\n" - " )\n" - " a2 0.5\n" - ")\n", - g_builder.ToString()); -} -#endif // DCHECK_IS_ON() - -} // namespace WTF
diff --git a/third_party/blink/renderer/platform/wtf/text/base64_test.cc b/third_party/blink/renderer/platform/wtf/text/base64_test.cc index 02cb777..818d6e2 100644 --- a/third_party/blink/renderer/platform/wtf/text/base64_test.cc +++ b/third_party/blink/renderer/platform/wtf/text/base64_test.cc
@@ -7,6 +7,7 @@ #include "base/containers/span.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" #include "third_party/blink/renderer/platform/wtf/vector.h" @@ -38,47 +39,61 @@ TEST(Base64Test, DecodeNoPaddingValidation) { struct { const char* in; - Vector<char> expected_out; + const char* expected_out; } kTestCases[] = { // Inputs that are multiples of 4 always succeed. - {"abcd", {'i', '\xB7', '\x1D'}}, - {"abc=", {'i', '\xB7'}}, - {"abcdefgh", {'i', '\xB7', '\x1D', 'y', '\xF8', '!'}}, + {"abcd", "i\xB7\x1D"}, + {"abc=", "i\xB7"}, + {"abcdefgh", "i\xB7\x1Dy\xF8!"}, // Lack of proper padding (to a multiple of 4) always succeeds if // len % 4 != 1. - {"abcdef", {'i', '\xB7', '\x1D', 'y'}}, - {"abc", {'i', '\xB7'}}, - {"ab", {'i'}}, + {"abcdef", "i\xB7\x1Dy"}, + {"abc", "i\xB7"}, + {"ab", "i"}, // Invalid padding is ignored if kNoPaddingValidation is set. - {"abcd=", {'i', '\xB7', '\x1D'}}, - {"abcd==", {'i', '\xB7', '\x1D'}}, - {"abcd===", {'i', '\xB7', '\x1D'}}, - {"abcd==============", {'i', '\xB7', '\x1D'}}, + {"abcd=", "i\xB7\x1D"}, + {"abcd==", "i\xB7\x1D"}, + {"abcd===", "i\xB7\x1D"}, + {"abcd==============", "i\xB7\x1D"}, + {"=", ""}, - // Whitespace should not be allow if kNoPaddingValidation is set. - {" a bcd", {}}, - {"ab\t\tc=", {}}, - {"ab c\ndefgh ", {}}, + // Whitespace should not be allowed if kNoPaddingValidation is set. + {" a bcd", nullptr}, + {"ab\t\tc=", nullptr}, + {"ab c\ndefgh ", nullptr}, // Failures that should apply in all decoding modes. - {"abc&", {}}, - {"abcde", {}}, - {"a", {}}, - {"=", {}}, + {"abc&", nullptr}, + {"abcde", nullptr}, + {"a", nullptr}, // Empty string should yield an empty result. - {"", {}}, + {"", ""}, }; for (const auto& test : kTestCases) { + SCOPED_TRACE(::testing::Message() << test.in); Vector<char> out; - bool success = Base64Decode(String(test.in), out); - if (success) { - EXPECT_EQ(test.expected_out, out) << test.in; - } else { - EXPECT_TRUE(test.expected_out.empty()) << test.in; + String in = String(test.in); + bool expected_success = test.expected_out != nullptr; + Vector<char> expected_out; + if (expected_success) { + expected_out.insert(0, test.expected_out, strlen(test.expected_out)); + } + + bool success_8bit = Base64Decode(in, out); + EXPECT_EQ(expected_success, success_8bit); + if (expected_success) { + EXPECT_EQ(expected_out, out); + } + out.clear(); + in.Ensure16Bit(); + bool success_16bit = Base64Decode(in, out); + EXPECT_EQ(expected_success, success_16bit); + if (expected_success) { + EXPECT_EQ(expected_out, out); } } } @@ -86,48 +101,61 @@ TEST(Base64Test, ForgivingBase64Decode) { struct { const char* in; - Vector<char> expected_out; + const char* expected_out; } kTestCases[] = { // Inputs that are multiples of 4 always succeed. - {"abcd", {'i', '\xB7', '\x1D'}}, - {"abc=", {'i', '\xB7'}}, - {"abcdefgh", {'i', '\xB7', '\x1D', 'y', '\xF8', '!'}}, + {"abcd", "i\xB7\x1D"}, + {"abc=", "i\xB7"}, + {"abcdefgh", "i\xB7\x1Dy\xF8!"}, // Lack of proper padding (to a multiple of 4) always succeeds if // len % 4 != 1. - {"abcdef", {'i', '\xB7', '\x1D', 'y'}}, - {"abc", {'i', '\xB7'}}, - {"ab", {'i'}}, + {"abcdef", "i\xB7\x1Dy"}, + {"abc", "i\xB7"}, + {"ab", "i"}, // Invalid padding causes failure if kForgiving is set. - {"abcd=", {}}, - {"abcd==", {}}, - {"abcd===", {}}, - {"abcd==============", {}}, + {"abcd=", nullptr}, + {"abcd==", nullptr}, + {"abcd===", nullptr}, + {"abcd==============", nullptr}, + {"=", nullptr}, // Whitespace should be allow if kForgiving is set. - {" a bcd", {'i', '\xB7', '\x1D'}}, - {"ab\t\tc=", {'i', '\xB7'}}, - {"ab c\ndefgh ", {'i', '\xB7', '\x1D', 'y', '\xF8', '!'}}, + {" a bcd", "i\xB7\x1D"}, + {"ab\t\tc=", "i\xB7"}, + {"ab c\ndefgh", "i\xB7\x1Dy\xF8!"}, // Failures that should apply in all decoding modes. - {"abc&", {}}, - {"abcde", {}}, - {"a", {}}, - {"=", {}}, + {"abc&", nullptr}, + {"abcde", nullptr}, + {"a", nullptr}, // Empty string should yield an empty result. - {"", {}}, + {"", ""}, }; for (const auto& test : kTestCases) { + SCOPED_TRACE(::testing::Message() << test.in); Vector<char> out; - bool success = - Base64Decode(String(test.in), out, Base64DecodePolicy::kForgiving); - if (success) { - EXPECT_EQ(test.expected_out, out) << test.in; - } else { - EXPECT_TRUE(test.expected_out.empty()) << test.in; + String in = String(test.in); + bool expected_success = test.expected_out != nullptr; + Vector<char> expected_out; + if (expected_success) { + expected_out.insert(0, test.expected_out, strlen(test.expected_out)); + } + + bool success_8bit = Base64Decode(in, out, Base64DecodePolicy::kForgiving); + EXPECT_EQ(expected_success, success_8bit); + if (expected_success) { + EXPECT_EQ(expected_out, out); + } + out.clear(); + in.Ensure16Bit(); + bool success_16bit = Base64Decode(in, out, Base64DecodePolicy::kForgiving); + EXPECT_EQ(expected_success, success_16bit); + if (expected_success) { + EXPECT_EQ(expected_out, out); } } }
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index d0e6059b..06368a6 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -6064,7 +6064,7 @@ # Sheriff 2021-02-15 crbug.com/1177996 [ Linux ] storage/websql/database-lock-after-reload.html [ Failure Pass ] -crbug.com/1178018 external/wpt/webaudio/the-audio-api/the-mediaelementaudiosourcenode-interface/mediaElementAudioSourceToScriptProcessorTest.html [ Failure Pass ] +crbug.com/977030 external/wpt/webaudio/the-audio-api/the-mediaelementaudiosourcenode-interface/mediaElementAudioSourceToScriptProcessorTest.html [ Failure Pass ] # Expected to fail - Chrome's WebXR Depth Sensing API implementation does not currently support `gpu-optimized` usage mode. crbug.com/1179461 [ Fuchsia ] external/wpt/webxr/depth-sensing/gpu/depth_sensing_gpu_dataUnavailable.https.html [ Failure ] @@ -7300,7 +7300,7 @@ # Sheriff 2022-06-24 crbug.com/1339211 [ Mac ] external/wpt/css/css-text-decor/text-decoration-thickness-fixed.html [ Failure Pass ] -crbug.com/1339214 [ Mac ] external/wpt/webaudio/the-audio-api/the-convolvernode-interface/realtime-conv.html [ Failure Pass ] +crbug.com/1339291 [ Mac ] external/wpt/webaudio/the-audio-api/the-convolvernode-interface/realtime-conv.html [ Failure Pass ] crbug.com/1339293 [ Linux ] http/tests/devtools/network/network-initiator.js [ Failure Pass ] crbug.com/1339293 [ Linux ] external/wpt/html/semantics/embedded-content/the-img-element/invisible-image.html [ Failure Pass ] crbug.com/1339293 [ Linux ] virtual/threaded/external/wpt/requestidlecallback/deadline-max-rAF-dynamic.html [ Failure Pass ] @@ -8151,6 +8151,7 @@ crbug.com/1393995 fast/dom/shadow/import-rule-in-shadow-tree-needs-document-style-recalc.html [ Failure Pass ] crbug.com/1379180 fast/events/event-hit-testing-fallback-to-iframe.html [ Failure Pass ] crbug.com/1394041 [ Mac11-arm64 ] virtual/gpu-rasterization/images/2-dht.html [ Failure Pass ] +crbug.com/1394151 virtual/gpu/fast/canvas/OffscreenCanvasImageRenderingPixelatedWorker.html [ Failure Pass ] # Temporarily disable test to land devtools-frontend change crrev/c/4057666 crbug.com/1385379 http/tests/devtools/elements/styles-4/styles-invalid-color-values.js [ Failure Pass ]
diff --git a/third_party/blink/web_tests/WebGPUExpectations b/third_party/blink/web_tests/WebGPUExpectations index 4fd9aa8..16bcb1f1 100644 --- a/third_party/blink/web_tests/WebGPUExpectations +++ b/third_party/blink/web_tests/WebGPUExpectations
@@ -10,9 +10,6 @@ # Workaround page loaded when content_shell starts, but not run as a test. crbug.com/1231599 wpt_internal/webgpu/000_run_me_first.https.html [ Skip ] -# VVL failure -crbug.com/1083478 [ Linux ] wpt_internal/webgpu/web_platform/reftests/canvas_size_different_with_back_buffer_size.https.html [ Crash ] - # Mac doesn't support rgba8unorm for the swapchain format (yet) crbug.com/1298618 [ Mac ] wpt_internal/webgpu/web_platform/reftests/canvas_complex_rgba8unorm_copy.https.html [ Skip ] crbug.com/1298618 [ Mac ] wpt_internal/webgpu/web_platform/reftests/canvas_complex_rgba8unorm_draw.https.html [ Skip ]
diff --git a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json index 5005cfc..3b6cf2bc 100644 --- a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json +++ b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json
@@ -83544,7 +83544,7 @@ ] ], "fieldset-002.html": [ - "aea8cec5d432e33fb86165f6db10a11c0929e8c1", + "9331b81b11979d562da007dae98a7af0f8f184a4", [ null, [ @@ -83557,7 +83557,7 @@ ] ], "fieldset-003.html": [ - "6c23a4b93e4233c40d97347d4189583eeb49c9b4", + "dbf69a403481124f3b1022f1470c14eae789f888", [ null, [ @@ -83570,7 +83570,7 @@ ] ], "fieldset-004.html": [ - "ce832f82985383bd30389a0555b3864d11c32e17", + "4b49e6a594636a405d9f7037779e385cd0c73d9b", [ null, [ @@ -136686,6 +136686,32 @@ ], {} ] + ], + "initial-letter-with-tab-rtl.html": [ + "f8a2d7a2a1cbc48e5a7fc52637a1f7cab6b5ea46", + [ + null, + [ + [ + "/css/css-inline/initial-letter/initial-letter-with-tab-rtl-ref.html", + "==" + ] + ], + {} + ] + ], + "initial-letter-with-tab.html": [ + "49b1f6b4b0e2a5c85ba7d89a2d7b46a4bcfee611", + [ + null, + [ + [ + "/css/css-inline/initial-letter/initial-letter-with-tab-ref.html", + "==" + ] + ], + {} + ] ] } }, @@ -144640,7 +144666,7 @@ }, "css-multicol": { "abspos-after-spanner-static-pos.html": [ - "9b2b996233c6a31c63471a41307f3c833a74abef", + "d257016a2519c6c30a0c352f4bd453822c89841b", [ null, [ @@ -144653,7 +144679,7 @@ ] ], "abspos-after-spanner.html": [ - "caed4169757c604b51db18ae94cc2e02c349da1f", + "98664b50cc144adf01817e98fe844d68d877dbe9", [ null, [ @@ -144692,7 +144718,7 @@ ] ], "abspos-containing-block-outside-spanner.html": [ - "ed832d39f621322064c3b6c3da390809d9cab7d5", + "1f0419d9c982588a93ad981656ca1271144756dd", [ null, [ @@ -250300,6 +250326,45 @@ {} ] ], + "mprescripts-001.html": [ + "2435b6291d5961bd7112c78bdf7c28f80a06aff0", + [ + null, + [ + [ + "/mathml/presentation-markup/scripts/mprescripts-001-ref.html", + "==" + ] + ], + {} + ] + ], + "none-001.html": [ + "f1bfb442f79b3adf3ba51a5aeaa7b6f82ff522d2", + [ + null, + [ + [ + "/mathml/presentation-markup/scripts/none-001-ref.html", + "==" + ] + ], + {} + ] + ], + "none-002.html": [ + "d1f3a3a0e125d7914bb55d5e99a897481245ed52", + [ + null, + [ + [ + "/mathml/presentation-markup/scripts/none-002-ref.html", + "==" + ] + ], + {} + ] + ], "subsup-legacy-scriptshift-attributes-001.tentative.html": [ "2f29db401db1370b3a8de2a7ab669181ac6d7cc1", [ @@ -254768,12 +254833,12 @@ ] ], "nested-svg-through-display-contents.svg": [ - "f5440303502c7b268480a949f0433e078ca80b1a", + "1be64d5242f9f65f53cd079df270c8a2232b741b", [ null, [ [ - "/svg/struct/reftests/reference/nested-svg-through-display-contents-ref.svg", + "/svg/struct/reftests/reference/green-100x100.svg", "==" ] ], @@ -276462,6 +276527,10 @@ "border-shorthand.html.ini": [ "06f49b9066c03b9f330844e535772523e9510766", [] + ], + "webkit-border-radius-valid-expected.txt": [ + "f4a10b4dc95f853268216bf256b5917e1ea4063c", + [] ] }, "reference": { @@ -278001,10 +278070,6 @@ [] ], "animation": { - "color-interpolation-expected.txt": [ - "224b3f8ba137295839a8b74e77ed74617464d171", - [] - ], "color-interpolation.html.ini": [ "f8163a3186d9920944a2013053b13cef7b9eadac", [] @@ -293734,6 +293799,10 @@ } }, "css-highlight-api": { + "HighlightRegistry-maplike-tampered-Map-prototype-expected.txt": [ + "20e81406c029fe7c3ff5153eff21867b4e1b6339", + [] + ], "idlharness.window.js.ini": [ "63108e58f25594b9dd864319a925a180053a92bd", [] @@ -295546,6 +295615,14 @@ "initial-letter-with-first-line-ref.html": [ "f3e01e14c4f92fc8fb60844fd48d2b0635a9e4ca", [] + ], + "initial-letter-with-tab-ref.html": [ + "43cba30d512bca6669def384a403f90dcb76b6d2", + [] + ], + "initial-letter-with-tab-rtl-ref.html": [ + "13f633a25981c01604f3c008e21f50b188df2110", + [] ] }, "parsing": { @@ -323097,6 +323174,10 @@ "e30f6fc97f95f78e10c0ada540fbe17528512b63", [] ], + "cross-realm-callback-report-exception-expected.txt": [ + "5de1821559c0d94eabd19f4e9524c93964a6bf63", + [] + ], "custom-element-registry": { "per-global-expected.txt": [ "99e8fe948642112db663295770cf266fb82058ef", @@ -324871,6 +324952,10 @@ "3c2cf6d6ffb861f735056c9129c4f1f49131e0e7", [] ], + "resolver-callback-interface-cross-realm.tentative-expected.txt": [ + "2d635059ca344a98aee32b2094604df2346a7ea0", + [] + ], "resolver-callback-interface-expected.txt": [ "a3e74bd621d3cbd370e1c657bc545e0b32474a60", [] @@ -356529,6 +356614,18 @@ "a4f16aa07f969e43dee4be45c48f7252e5c109ca", [] ], + "mprescripts-001-ref.html": [ + "f8631539c02fff09b865c1d98ef56d68bb03d506", + [] + ], + "none-001-ref.html": [ + "55add014151905f9e8be454ffc579f447effb9d8", + [] + ], + "none-002-ref.html": [ + "dac4dab553d2910ded75f970cacfa5d19c0a25f3", + [] + ], "subsup-2-expected.txt": [ "e966aa9a334c1f49d60eac871d9f4696a9e472db", [] @@ -372461,10 +372558,6 @@ "green-100x100.svg": [ "120941444a4898197d6b6001f9908a6cd48b62ba", [] - ], - "nested-svg-through-display-contents-ref.svg": [ - "622978f37881a4d40440595962b84bdb4c00dd91", - [] ] }, "support": { @@ -375322,7 +375415,7 @@ [] ], "README.md": [ - "90c13069bacde39c89acea37e1e0005b956be845", + "3e300818e240adaf45b577965c88206c998527cf", [] ], "resources": { @@ -375395,7 +375488,7 @@ ] }, "generate-test-wbns.sh": [ - "be854344156d593ecdab1b22c439280dff1b7274", + "418a56e0e7cdac9546e92d794b337d02970a0c14", [] ], "location": { @@ -418964,6 +419057,13 @@ {} ] ], + "anchor-position-writing-modes-002.html": [ + "15a9a639e24082c3b53bf98cadf23fa4b88232da", + [ + null, + {} + ] + ], "anchor-query-custom-property-registration.html": [ "af211a0ee5d8336dbd4b67c33a371907a5675d19", [ @@ -419041,6 +419141,13 @@ {} ] ], + "at-position-fallback-invalidation-shadow-dom.html": [ + "569278ac90f15aa40644ac082b15b36b233fcce3", + [ + null, + {} + ] + ], "at-position-fallback-invalidation.html": [ "68a0874931245741b7b35e2c517367f8733bc764", [ @@ -420508,6 +420615,13 @@ null, {} ] + ], + "webkit-border-radius-valid.html": [ + "cdf570b4e9f82a44da9cc07dfcff95a18dc158ee", + [ + null, + {} + ] ] } }, @@ -421427,7 +421541,7 @@ ] ], "color-interpolation.html": [ - "7bda888a0b4d4355e916197e3646b69d1ca1ef64", + "fd3d426bafd32eb068195eb2a665d779e5819c15", [ null, {} @@ -430069,6 +430183,13 @@ {} ] ], + "Highlight-setlike-tampered-Set-prototype.html": [ + "4c23f4850c1507c9fb3fd3c8e46ffa67df655157", + [ + null, + {} + ] + ], "Highlight-setlike.html": [ "0093f9be232b5544c635ee343e660c4ee4b489e8", [ @@ -430097,6 +430218,13 @@ {} ] ], + "HighlightRegistry-maplike-tampered-Map-prototype.html": [ + "3b38bd8f162ed108853abd1752c1e9f93841bcf2", + [ + null, + {} + ] + ], "HighlightRegistry-maplike.html": [ "d8bbe4731f6a332efbf223bd69d48244d95560ca", [ @@ -445857,6 +445985,48 @@ } ] ], + "only-child-group.html": [ + "034df41dde165f7624effddf70209472ea74a322", + [ + null, + {} + ] + ], + "only-child-image-pair.html": [ + "830b37313eaaa3165d5739b39f2ccb415886e724", + [ + null, + {} + ] + ], + "only-child-new.html": [ + "2f8a7a4023ec7ffde81a6eeda6a65ca4533540ce", + [ + null, + {} + ] + ], + "only-child-no-transition.html": [ + "7dc2bf12176d9d45dc6af80017617206f4d6dbee", + [ + null, + {} + ] + ], + "only-child-old.html": [ + "4ca6fed20ce7b2f092de2c324ad6197caed22bc9", + [ + null, + {} + ] + ], + "only-child-view-transition.html": [ + "d338a042caf994c7086d23ff6e629a70c6ebd951", + [ + null, + {} + ] + ], "parsing": { "view-transition-name-computed.html": [ "4a13ed5d2e9590b118b087d97ea30478217c9599", @@ -450958,6 +451128,13 @@ {} ] ], + "cross-realm-callback-report-exception.html": [ + "3067a7af9d273c3a027ccf978b51b07cc8c82201", + [ + null, + {} + ] + ], "custom-element-reaction-queue.html": [ "246b15a0af36cffa0b64f1d57e4208538b92bdd7", [ @@ -454615,6 +454792,13 @@ {} ] ], + "MutationObserver-cross-realm-callback-report-exception.html": [ + "7d05c045b3b7f9df6684f4e3d5179e5c8b7db3b1", + [ + null, + {} + ] + ], "MutationObserver-disconnect.html": [ "883edecf74403843b19dc6b295f3b973b9861089", [ @@ -456178,8 +456362,8 @@ {} ] ], - "resolver-callback-interface-cross-realm.html": [ - "55fbb070a3b482b1546a52eef0285f9e7e5483f0", + "resolver-callback-interface-cross-realm.tentative.html": [ + "17f7ea78c3a397aeb22d7e8d09e1a4f9611b63fb", [ null, {} @@ -480741,7 +480925,7 @@ ] ], "response-static-error.any.js": [ - "4097eab37b4c90e8c453027b99fbf4ed31a08b42", + "1f8c49ab006a489029edcb5597d06379b19c5c9a", [ "fetch/api/response/response-static-error.any.html", { @@ -489629,7 +489813,7 @@ ] ], "local-storage-initial-empty-document.tentative.https.window.js": [ - "fc58aaed908cf5ebfe67feddb218f03d05d77546", + "37678ff12b76024a9f9ac960a2df370fd283f441", [ "html/anonymous-iframe/local-storage-initial-empty-document.tentative.https.window.html", { @@ -525198,6 +525382,13 @@ {} ] ], + "toBlob-cross-realm-callback-report-exception.html": [ + "393170baad8a1a93b5d89b6f505d45c40e85a8a2", + [ + null, + {} + ] + ], "toBlob.jpeg.html": [ "1a95d4a6dd8ae73b69de1be1d9454853eef52b2c", [ @@ -525480,6 +525671,13 @@ {} ] ], + "embed-svg-navigation-resets-size.html": [ + "237c9c3646bb0ed34b27bf2279dc57304ddaea4f", + [ + null, + {} + ] + ], "historical.html": [ "9df7280bb6065eaa188c637400fdd8ef609345b7", [ @@ -537441,6 +537639,13 @@ }, "webappapis": { "animation-frames": { + "callback-cross-realm-report-exception.html": [ + "1b8aa41a6d34147b94b4a91c686c4b27dad3a5f5", + [ + null, + {} + ] + ], "callback-exception.html": [ "3867f0c41d54130d6314d74ebaec96c589f55b89", [ @@ -538598,6 +538803,13 @@ } }, "microtask-queuing": { + "queue-microtask-cross-realm-callback-report-exception.html": [ + "fa153f8f965d2be72680e1c830065dcb798fb25e", + [ + null, + {} + ] + ], "queue-microtask-exceptions.any.js": [ "01f32ac9ba14962fa99d4b263a8ca0f5a0daa161", [ @@ -539400,6 +539612,13 @@ null, {} ] + ], + "window-onerror-with-cross-frame-event-listeners-5.html": [ + "da93e782ca9c4106b0e44b4bcae68743b92666a7", + [ + null, + {} + ] ] }, "reporterror-cross-realm-method.html": [ @@ -539668,6 +539887,20 @@ {} ] ], + "setinterval-cross-realm-callback-report-exception.html": [ + "4a780fc93291b1561c23e0d15510bf6cb66fcd46", + [ + null, + {} + ] + ], + "settimeout-cross-realm-callback-report-exception.html": [ + "b4860151a6c39f9344129c1675071d4c75fb14bb", + [ + null, + {} + ] + ], "type-long-setinterval.any.js": [ "164527f18b1e6f6b41affc46ee171b08137f509c", [ @@ -541595,6 +541828,13 @@ {} ] ], + "callback-cross-realm-report-exception.html": [ + "0bec720485dc6d570a252760db4397e78c300b65", + [ + null, + {} + ] + ], "client-rect.html": [ "e85171ca7c9771cb0e53cc318c88bdfbc36362ff", [ @@ -544537,14 +544777,14 @@ }, "mrow": { "inferred-mrow-baseline.html": [ - "cc007cf81ff823890a59ccec5c285f3b23853b4b", + "0086646859afb4cf675e4cbf0ef6cdf55e27b8d5", [ null, {} ] ], "inferred-mrow-stretchy.html": [ - "a1e409a248e9075e697a2a31208f40a009e66440", + "614438deb30ff73b3e47fd2f532c12b7b1c9a6b3", [ null, {} @@ -573080,6 +573320,13 @@ {} ] ], + "callback-cross-realm-report-exception.html": [ + "75a91ec0a1762f5c0c7745568c4f179ec4ac1a32", + [ + null, + {} + ] + ], "change-layout-in-error.html": [ "9083fb48f94efe2a4d402fda2e452d72f94b1e17", [ @@ -576171,7 +576418,7 @@ ] ], "animation-timeline-computed.html": [ - "68ba1f22aacf636673674fd4820a017c3f57c45c", + "29486a02c1940288c03fb257dc72b9511d593300", [ null, {} @@ -584594,18 +584841,66 @@ ] ], "response-code-non-successful.html": [ - "00701f1471e57cf6cec6dd57747554f4b20c0c78", + "149971719cca8f842956967eb501aea310d0fdd2", [ - null, + "speculation-rules/prerender/response-code-non-successful.html?code=204", + { + "timeout": "long" + } + ], + [ + "speculation-rules/prerender/response-code-non-successful.html?code=205", + { + "timeout": "long" + } + ], + [ + "speculation-rules/prerender/response-code-non-successful.html?code=402", + { + "timeout": "long" + } + ], + [ + "speculation-rules/prerender/response-code-non-successful.html?code=404", + { + "timeout": "long" + } + ], + [ + "speculation-rules/prerender/response-code-non-successful.html?code=500", + { + "timeout": "long" + } + ], + [ + "speculation-rules/prerender/response-code-non-successful.html?code=503", { "timeout": "long" } ] ], "response-code-successful.html": [ - "cc70b8c641dfc9d09d79feaaeccb871da5ed9095", + "adf8a8932f71b5e34008c4ce47674b886fc40ed9", [ - null, + "speculation-rules/prerender/response-code-successful.html?code=200", + { + "timeout": "long" + } + ], + [ + "speculation-rules/prerender/response-code-successful.html?code=201", + { + "timeout": "long" + } + ], + [ + "speculation-rules/prerender/response-code-successful.html?code=202", + { + "timeout": "long" + } + ], + [ + "speculation-rules/prerender/response-code-successful.html?code=203", { "timeout": "long" } @@ -603860,7 +604155,7 @@ ] ], "disabled-by-permissions-policy-cross-origin.https.sub.html": [ - "785624198414abe2eeb7a7941e3601e8aa461f5e", + "773da84c0c5bdd068b3a6a103f6f218270851f5b", [ null, {}
diff --git a/third_party/blink/web_tests/external/wpt/clipboard-apis/async-custom-formats-write-fail.tentative.https.html b/third_party/blink/web_tests/external/wpt/clipboard-apis/async-custom-formats-write-fail.tentative.https.html new file mode 100644 index 0000000..8b1b42e --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/clipboard-apis/async-custom-formats-write-fail.tentative.https.html
@@ -0,0 +1,123 @@ +<!doctype html> +<meta charset="utf-8"> +<title>Async Clipboard web custom format write validation tests</title> +<link rel="help" href="https://w3c.github.io/clipboard-apis/#async-clipboard-api"> +<body>Body needed for test_driver.click()</body> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/resources/testdriver.js"></script> +<script src="/resources/testdriver-vendor.js"></script> +<script src="resources/user-activation.js"></script> +<script> +'use strict'; + +promise_test(async t => { + await test_driver.set_permission({name: 'clipboard-write'}, 'granted'); + + const customFormatArray = []; + const customFormatMap = {}; + for (let i = 0; i <= 100; i++) { + customFormatArray.push("web text/CustomFormat" + i); + const blobInput = new Blob(['input data'], {type: customFormatArray[i]}); + customFormatMap[customFormatArray[i]] = blobInput; + } + const clipboardItemInput = new ClipboardItem(customFormatMap); + await waitForUserActivation(); + await promise_rejects_dom(t, 'NotAllowedError', + navigator.clipboard.write([clipboardItemInput])); +}, 'navigator.clipboard.write() fails for more than 100 custom formats'); + +promise_test(async t => { + await test_driver.set_permission({name: 'clipboard-write'}, 'granted'); + + const format1 = 'application/x-custom-format-clipboard-test-format-1'; + const format2 = 'application/x-custom-format-clipboard-test-format-2'; + const blobInput1 = new Blob(['input data 1'], {type: format1}); + const blobInput2 = new Blob(['input data 2'], {type: format2}); + const clipboardItemInput = new ClipboardItem( + {[format1]: blobInput1, [format2]: blobInput2}); + await waitForUserActivation(); + await promise_rejects_dom(t, 'NotAllowedError', + navigator.clipboard.write([clipboardItemInput])); +}, 'navigator.clipboard.write() fails for custom formats without web prefix'); + +promise_test(async t => { + await test_driver.set_permission({name: 'clipboard-write'}, 'granted'); + + const format1 = 'web '; + const format2 = 'web a'; + const blobInput1 = new Blob(['input data 1'], {type: format1}); + const blobInput2 = new Blob(['input data 2'], {type: format2}); + const clipboardItemInput = new ClipboardItem( + {[format1]: blobInput1, [format2]: blobInput2}); + await waitForUserActivation(); + await promise_rejects_dom(t, 'NotAllowedError', + navigator.clipboard.write([clipboardItemInput])); +}, 'navigator.clipboard.write() fails for custom formats with web prefix, but invalid MIME types'); + +promise_test(async t => { + await test_driver.set_permission({name: 'clipboard-write'}, 'granted'); + + const format1 = 'web text/plain'; + const format2 = 'text/custom'; + const blobInput1 = new Blob(['input data 1'], {type: format2}); + const clipboardItemInput = new ClipboardItem( + {[format1]: blobInput1}); + await waitForUserActivation(); + await promise_rejects_dom(t, 'NotAllowedError', + navigator.clipboard.write([clipboardItemInput])); +}, 'navigator.clipboard.write() fails for custom format with web prefix, but different Blob type'); + +promise_test(async t => { + await test_driver.set_permission({name: 'clipboard-write'}, 'granted'); + + const format1 = 'web Text/plain'; + const format2 = 'text/plain'; + const blobInput1 = new Blob(['input data 1'], {type: format2}); + const clipboardItemInput = new ClipboardItem( + {[format1]: blobInput1}); + await waitForUserActivation(); + await promise_rejects_dom(t, 'NotAllowedError', + navigator.clipboard.write([clipboardItemInput])); +}, 'navigator.clipboard.write() fails for custom format with different case than the Blob type'); + +promise_test(async t => { + await test_driver.set_permission({name: 'clipboard-write'}, 'granted'); + + const format1 = 'web text/plain'; + const format2 = 'Text/plain'; + const blobInput1 = new Blob(['input data 1'], {type: format1}); + const clipboardItemInput = new ClipboardItem( + {[format2]: blobInput1}); + await waitForUserActivation(); + await promise_rejects_dom(t, 'NotAllowedError', + navigator.clipboard.write([clipboardItemInput])); +}, 'navigator.clipboard.write() fails for invalid mime type that is different than the Blob type'); + +promise_test(async t => { + await test_driver.set_permission({name: 'clipboard-write'}, 'granted'); + + const format1 = 'web Text/plain'; + const format2 = 'web text/plain'; + const blobInput1 = new Blob(['input data 1'], {type: format2}); + const clipboardItemInput = new ClipboardItem( + {[format1]: blobInput1}); + await waitForUserActivation(); + await promise_rejects_dom(t, 'NotAllowedError', + navigator.clipboard.write([clipboardItemInput])); +}, 'navigator.clipboard.write() fails for invalid mime type with web prefix and the Blob type'); + +promise_test(async t => { + await test_driver.set_permission({name: 'clipboard-write'}, 'granted'); + + const format1 = 'Text/plain'; + const format2 = 'text/plain'; + const blobInput1 = new Blob(['input data 1'], {type: format2}); + const clipboardItemInput = new ClipboardItem( + {[format1]: blobInput1}); + await waitForUserActivation(); + await promise_rejects_dom(t, 'NotAllowedError', + navigator.clipboard.write([clipboardItemInput])); +}, 'navigator.clipboard.write() fails for custom format and Blob type with different case'); + +</script>
diff --git a/third_party/blink/web_tests/external/wpt/clipboard-apis/async-custom-formats-write-read-web-prefix.tentative.https.html b/third_party/blink/web_tests/external/wpt/clipboard-apis/async-custom-formats-write-read-web-prefix.tentative.https.html new file mode 100644 index 0000000..9a6e5da6f --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/clipboard-apis/async-custom-formats-write-read-web-prefix.tentative.https.html
@@ -0,0 +1,39 @@ +<!doctype html> +<meta charset="utf-8"> +<title>Async Clipboard web custom format read/write test.</title> +<link rel="help" href="https://w3c.github.io/clipboard-apis/#async-clipboard-api"> +<body>Body needed for test_driver.click()</body> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/resources/testdriver.js"></script> +<script src="/resources/testdriver-vendor.js"></script> +<script src="resources/user-activation.js"></script> +<script> +'use strict'; + +promise_test(async t => { + await test_driver.set_permission({name: 'clipboard-read'}, 'granted'); + await test_driver.set_permission({name: 'clipboard-write'}, 'granted'); + + const format1 = 'web text/plain'; + const format2 = 'web text/plain'; + const blobInput1 = new Blob(['input data 1'], {type: format2}); + const clipboardItemInput = new ClipboardItem( + {[format1]: blobInput1}); + await waitForUserActivation(); + await navigator.clipboard.write([clipboardItemInput]); + await waitForUserActivation(); + const clipboardItems = await navigator.clipboard.read(); + assert_equals(clipboardItems.length, 1); + const clipboardItem = clipboardItems[0]; + assert_true(clipboardItem instanceof ClipboardItem); + // This test can't verify clipboardItem.types, because its size and values + // are both platform-dependent. + + const blobOutput1 = await clipboardItem.getType(format1); + assert_equals(blobOutput1.type, format1); + const data1 = await (new Response(blobOutput1)).text(); + assert_equals(data1, 'input data 1'); +}, 'navigator.clipboard.write() for custom format and Blob type with web prefix'); + +</script>
diff --git a/third_party/blink/web_tests/external/wpt/clipboard-apis/async-custom-formats-write-read-without-web-prefix.tentative.https.html b/third_party/blink/web_tests/external/wpt/clipboard-apis/async-custom-formats-write-read-without-web-prefix.tentative.https.html new file mode 100644 index 0000000..8b9d4de --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/clipboard-apis/async-custom-formats-write-read-without-web-prefix.tentative.https.html
@@ -0,0 +1,39 @@ +<!doctype html> +<meta charset="utf-8"> +<title>Async Clipboard web custom format write using Blob without web prefix test.</title> +<link rel="help" href="https://w3c.github.io/clipboard-apis/#async-clipboard-api"> +<body>Body needed for test_driver.click()</body> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/resources/testdriver.js"></script> +<script src="/resources/testdriver-vendor.js"></script> +<script src="resources/user-activation.js"></script> +<script> +'use strict'; + +promise_test(async t => { + await test_driver.set_permission({name: 'clipboard-read'}, 'granted'); + await test_driver.set_permission({name: 'clipboard-write'}, 'granted'); + + const format1 = 'web text/plain'; + const format2 = 'text/plain'; + const blobInput1 = new Blob(['input data 1'], {type: format2}); + const clipboardItemInput = new ClipboardItem( + {[format1]: blobInput1}); + await waitForUserActivation(); + await navigator.clipboard.write([clipboardItemInput]); + await waitForUserActivation(); + const clipboardItems = await navigator.clipboard.read(); + assert_equals(clipboardItems.length, 1); + const clipboardItem = clipboardItems[0]; + assert_true(clipboardItem instanceof ClipboardItem); + // This test can't verify clipboardItem.types, because its size and values + // are both platform-dependent. + + const blobOutput1 = await clipboardItem.getType(format1); + assert_equals(blobOutput1.type, format1); + const data1 = await (new Response(blobOutput1)).text(); + assert_equals(data1, 'input data 1'); +}, 'navigator.clipboard.write() for custom format with web prefix, but Blob type without web prefix'); + +</script>
diff --git a/third_party/blink/web_tests/external/wpt/clipboard-apis/async-custom-formats-write-read.tentative.https.html b/third_party/blink/web_tests/external/wpt/clipboard-apis/async-custom-formats-write-read.tentative.https.html index b0b78d0..a005f8c 100644 --- a/third_party/blink/web_tests/external/wpt/clipboard-apis/async-custom-formats-write-read.tentative.https.html +++ b/third_party/blink/web_tests/external/wpt/clipboard-apis/async-custom-formats-write-read.tentative.https.html
@@ -44,171 +44,4 @@ assert_equals(data2, 'input data 2'); }, 'Verify write and read clipboard given 2 platform-neutral custom format inputs'); -promise_test(async t => { - await test_driver.set_permission({name: 'clipboard-read'}, 'granted'); - await test_driver.set_permission({name: 'clipboard-write'}, 'granted'); - - const customFormatArray = []; - const customFormatMap = {}; - for (let i = 0; i <= 100; i++) { - customFormatArray.push("web text/CustomFormat" + i); - const blobInput = new Blob(['input data'], {type: customFormatArray[i]}); - customFormatMap[customFormatArray[i]] = blobInput; - } - const clipboardItemInput = new ClipboardItem(customFormatMap); - await waitForUserActivation(); - await promise_rejects_dom(t, 'NotAllowedError', - navigator.clipboard.write([clipboardItemInput])); -}, 'navigator.clipboard.write() fails for more than 100 custom formats'); - -promise_test(async t => { - await test_driver.set_permission({name: 'clipboard-read'}, 'granted'); - await test_driver.set_permission({name: 'clipboard-write'}, 'granted'); - - const format1 = 'application/x-custom-format-clipboard-test-format-1'; - const format2 = 'application/x-custom-format-clipboard-test-format-2'; - const blobInput1 = new Blob(['input data 1'], {type: format1}); - const blobInput2 = new Blob(['input data 2'], {type: format2}); - const clipboardItemInput = new ClipboardItem( - {[format1]: blobInput1, [format2]: blobInput2}); - await waitForUserActivation(); - await promise_rejects_dom(t, 'NotAllowedError', - navigator.clipboard.write([clipboardItemInput])); -}, 'navigator.clipboard.write() fails for custom formats without web prefix'); - -promise_test(async t => { - await test_driver.set_permission({name: 'clipboard-read'}, 'granted'); - await test_driver.set_permission({name: 'clipboard-write'}, 'granted'); - - const format1 = 'web '; - const format2 = 'web a'; - const blobInput1 = new Blob(['input data 1'], {type: format1}); - const blobInput2 = new Blob(['input data 2'], {type: format2}); - const clipboardItemInput = new ClipboardItem( - {[format1]: blobInput1, [format2]: blobInput2}); - await waitForUserActivation(); - await promise_rejects_dom(t, 'NotAllowedError', - navigator.clipboard.write([clipboardItemInput])); -}, 'navigator.clipboard.write() fails for custom formats with web prefix, but invalid MIME types'); - -promise_test(async t => { - await test_driver.set_permission({name: 'clipboard-read'}, 'granted'); - await test_driver.set_permission({name: 'clipboard-write'}, 'granted'); - - const format1 = 'web text/plain'; - const format2 = 'text/plain'; - const blobInput1 = new Blob(['input data 1'], {type: format2}); - const clipboardItemInput = new ClipboardItem( - {[format1]: blobInput1}); - await waitForUserActivation(); - await navigator.clipboard.write([clipboardItemInput]); - await waitForUserActivation(); - const clipboardItems = await navigator.clipboard.read(); - assert_equals(clipboardItems.length, 1); - const clipboardItem = clipboardItems[0]; - assert_true(clipboardItem instanceof ClipboardItem); - // This test can't verify clipboardItem.types, because its size and values - // are both platform-dependent. - - const blobOutput1 = await clipboardItem.getType(format1); - assert_equals(blobOutput1.type, format1); - const data1 = await (new Response(blobOutput1)).text(); - assert_equals(data1, 'input data 1'); -}, 'navigator.clipboard.write() for custom format with web prefix, but Blob type without web prefix'); - -promise_test(async t => { - await test_driver.set_permission({name: 'clipboard-read'}, 'granted'); - await test_driver.set_permission({name: 'clipboard-write'}, 'granted'); - - const format1 = 'web text/plain'; - const format2 = 'text/custom'; - const blobInput1 = new Blob(['input data 1'], {type: format2}); - const clipboardItemInput = new ClipboardItem( - {[format1]: blobInput1}); - await waitForUserActivation(); - await promise_rejects_dom(t, 'NotAllowedError', - navigator.clipboard.write([clipboardItemInput])); -}, 'navigator.clipboard.write() fails for custom format with web prefix, but different Blob type'); - -promise_test(async t => { - await test_driver.set_permission({name: 'clipboard-read'}, 'granted'); - await test_driver.set_permission({name: 'clipboard-write'}, 'granted'); - - const format1 = 'web Text/plain'; - const format2 = 'text/plain'; - const blobInput1 = new Blob(['input data 1'], {type: format2}); - const clipboardItemInput = new ClipboardItem( - {[format1]: blobInput1}); - await waitForUserActivation(); - await promise_rejects_dom(t, 'NotAllowedError', - navigator.clipboard.write([clipboardItemInput])); -}, 'navigator.clipboard.write() fails for custom format with different case than the Blob type'); - -promise_test(async t => { - await test_driver.set_permission({name: 'clipboard-read'}, 'granted'); - await test_driver.set_permission({name: 'clipboard-write'}, 'granted'); - - const format1 = 'web text/plain'; - const format2 = 'Text/plain'; - const blobInput1 = new Blob(['input data 1'], {type: format1}); - const clipboardItemInput = new ClipboardItem( - {[format2]: blobInput1}); - await waitForUserActivation(); - await promise_rejects_dom(t, 'NotAllowedError', - navigator.clipboard.write([clipboardItemInput])); -}, 'navigator.clipboard.write() fails for invalid mime type that is different than the Blob type'); - -promise_test(async t => { - await test_driver.set_permission({name: 'clipboard-read'}, 'granted'); - await test_driver.set_permission({name: 'clipboard-write'}, 'granted'); - - const format1 = 'web Text/plain'; - const format2 = 'web text/plain'; - const blobInput1 = new Blob(['input data 1'], {type: format2}); - const clipboardItemInput = new ClipboardItem( - {[format1]: blobInput1}); - await waitForUserActivation(); - await promise_rejects_dom(t, 'NotAllowedError', - navigator.clipboard.write([clipboardItemInput])); -}, 'navigator.clipboard.write() fails for invalid mime type with web prefix and the Blob type'); - -promise_test(async t => { - await test_driver.set_permission({name: 'clipboard-read'}, 'granted'); - await test_driver.set_permission({name: 'clipboard-write'}, 'granted'); - - const format1 = 'web text/plain'; - const format2 = 'web text/plain'; - const blobInput1 = new Blob(['input data 1'], {type: format2}); - const clipboardItemInput = new ClipboardItem( - {[format1]: blobInput1}); - await waitForUserActivation(); - await navigator.clipboard.write([clipboardItemInput]); - await waitForUserActivation(); - const clipboardItems = await navigator.clipboard.read(); - assert_equals(clipboardItems.length, 1); - const clipboardItem = clipboardItems[0]; - assert_true(clipboardItem instanceof ClipboardItem); - // This test can't verify clipboardItem.types, because its size and values - // are both platform-dependent. - - const blobOutput1 = await clipboardItem.getType(format1); - assert_equals(blobOutput1.type, format1); - const data1 = await (new Response(blobOutput1)).text(); - assert_equals(data1, 'input data 1'); -}, 'navigator.clipboard.write() for custom format and Blob type with web prefix'); - -promise_test(async t => { - await test_driver.set_permission({name: 'clipboard-read'}, 'granted'); - await test_driver.set_permission({name: 'clipboard-write'}, 'granted'); - - const format1 = 'Text/plain'; - const format2 = 'text/plain'; - const blobInput1 = new Blob(['input data 1'], {type: format2}); - const clipboardItemInput = new ClipboardItem( - {[format1]: blobInput1}); - await waitForUserActivation(); - await promise_rejects_dom(t, 'NotAllowedError', - navigator.clipboard.write([clipboardItemInput])); -}, 'navigator.clipboard.write() fails for custom format and Blob type with different case'); - </script>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-anchor-position/anchor-position-writing-modes-002.html b/third_party/blink/web_tests/external/wpt/css/css-anchor-position/anchor-position-writing-modes-002.html index 15a9a63..660e8c99 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-anchor-position/anchor-position-writing-modes-002.html +++ b/third_party/blink/web_tests/external/wpt/css/css-anchor-position/anchor-position-writing-modes-002.html
@@ -3,7 +3,7 @@ <link rel="help" href="https://drafts.csswg.org/css-anchor-1/#anchor-pos"> <link rel="author" href="mailto:kojii@chromium.org"> <script src="/resources/testharness.js"></script> -<script src="/resources/testharnessreport.js"></script><style> +<script src="/resources/testharnessreport.js"></script> <style> .htb-ltr { writing-mode: horizontal-tb; direction: ltr; } .htb-rtl { writing-mode: horizontal-tb; direction: rtl; }
diff --git a/third_party/blink/web_tests/external/wpt/css/css-backgrounds/parsing/webkit-border-radius-valid-expected.txt b/third_party/blink/web_tests/external/wpt/css/css-backgrounds/parsing/webkit-border-radius-valid-expected.txt new file mode 100644 index 0000000..f4a10b4 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-backgrounds/parsing/webkit-border-radius-valid-expected.txt
@@ -0,0 +1,28 @@ +This is a testharness.js-based test. +PASS e.style['-webkit-border-radius'] = "initial" should set the property value +PASS e.style['-webkit-border-radius'] = "inherit" should set the property value +PASS e.style['-webkit-border-radius'] = "unset" should set the property value +PASS e.style['-webkit-border-radius'] = "revert" should set the property value +PASS e.style['-webkit-border-radius'] = "1px" should set the property value +PASS e.style['-webkit-border-radius'] = "1px 5%" should set the property value +PASS e.style['-webkit-border-radius'] = "1px 2% 3px" should set the property value +PASS e.style['-webkit-border-radius'] = "1px 2% 3px 4%" should set the property value +PASS e.style['-webkit-border-radius'] = "1px / 2px" should set the property value +PASS e.style['-webkit-border-radius'] = "5em / 1px 2% 3px 4%" should set the property value +PASS e.style['-webkit-border-radius'] = "1px 2% / 3px 4px" should set the property value +PASS e.style['-webkit-border-radius'] = "1px 2px 3em / 1px 2px 3%" should set the property value +PASS e.style['-webkit-border-radius'] = "1px 2% / 2px 3em 4px 5em" should set the property value +PASS e.style['-webkit-border-radius'] = "1px 2% 3px 4% / 5em" should set the property value +PASS e.style['-webkit-border-radius'] = "1px 1px 1px 2% / 1px 2% 1px 2%" should set the property value +PASS e.style['-webkit-border-radius'] = "1px 1px 1px 1px / 1px 1px 2% 1px" should set the property value +PASS e.style['-webkit-border-radius'] = "1px 1px 2% 2%" should set the property value +PASS e.style['-webkit-border-radius'] = "1px 2% 1px 1px" should set the property value +PASS e.style['-webkit-border-radius'] = "1px 2% 2% 2% / 1px 2% 3px 2%" should set the property value +PASS e.style['-webkit-border-top-left-radius'] = "10px" should set the property value +PASS e.style['-webkit-border-top-right-radius'] = "20%" should set the property value +PASS e.style['-webkit-border-bottom-right-radius'] = "30px 40%" should set the property value +PASS e.style['-webkit-border-bottom-left-radius'] = "50% 60px" should set the property value +PASS Serialize border-radius from -webkit-border-radius: 1px 2px +FAIL Serialize -webkit-border-radius from border-radius: 1px 2px assert_array_equals: expected property 0 to be "border-top-left-radius: 1px" but got "border-top-left-radius: 1px 2px" (expected array ["border-top-left-radius: 1px", "border-top-right-radius: 2px", "border-bottom-right-radius: 1px", "border-bottom-left-radius: 2px"] got ["border-top-left-radius: 1px 2px", "border-top-right-radius: 1px 2px", "border-bottom-right-radius: 1px 2px", "border-bottom-left-radius: 1px 2px"]) +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/css/css-backgrounds/parsing/webkit-border-radius-valid.html b/third_party/blink/web_tests/external/wpt/css/css-backgrounds/parsing/webkit-border-radius-valid.html new file mode 100644 index 0000000..cdf570b --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-backgrounds/parsing/webkit-border-radius-valid.html
@@ -0,0 +1,70 @@ +<!DOCTYPE html> +<html> +<head> +<meta charset="utf-8"> +<title>Compatibility: parsing -webkit-border-radius with valid values</title> +<link rel="help" href="https://compat.spec.whatwg.org/#propdef--webkit-border-radius"> +<link rel="help" href="https://github.com/whatwg/compat/issues/133"> +<meta name="assert" content="-webkit-border-radius supports CSS Wide keywords and the full grammar '<length-percentage>{1,4} [ / <length-percentage>{1,4} ]?'."> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/css/support/parsing-testcommon.js"></script> +</head> +<body> +<div id="target"></div> +<script> +test_valid_value("-webkit-border-radius", "initial"); +test_valid_value("-webkit-border-radius", "inherit"); +test_valid_value("-webkit-border-radius", "unset"); +test_valid_value("-webkit-border-radius", "revert"); + +test_valid_value("-webkit-border-radius", "1px"); +test_valid_value("-webkit-border-radius", "1px 5%", ["1px 5%", "1px / 5%"]); +test_valid_value("-webkit-border-radius", "1px 2% 3px"); +test_valid_value("-webkit-border-radius", "1px 2% 3px 4%"); +test_valid_value("-webkit-border-radius", "1px / 2px", ["1px 2px", "1px / 2px"]); +test_valid_value("-webkit-border-radius", "5em / 1px 2% 3px 4%"); +test_valid_value("-webkit-border-radius", "1px 2% / 3px 4px"); +test_valid_value("-webkit-border-radius", "1px 2px 3em / 1px 2px 3%"); +test_valid_value("-webkit-border-radius", "1px 2% / 2px 3em 4px 5em"); +test_valid_value("-webkit-border-radius", "1px 2% 3px 4% / 5em"); + +test_valid_value("-webkit-border-radius", "1px 1px 1px 2% / 1px 2% 1px 2%", "1px 1px 1px 2% / 1px 2%"); +test_valid_value("-webkit-border-radius", "1px 1px 1px 1px / 1px 1px 2% 1px", "1px / 1px 1px 2%"); +test_valid_value("-webkit-border-radius", "1px 1px 2% 2%"); +test_valid_value("-webkit-border-radius", "1px 2% 1px 1px"); +test_valid_value("-webkit-border-radius", "1px 2% 2% 2% / 1px 2% 3px 2%", "1px 2% 2% / 1px 2% 3px"); + +test_valid_value("-webkit-border-top-left-radius", "10px"); +test_valid_value("-webkit-border-top-right-radius", "20%"); +test_valid_value("-webkit-border-bottom-right-radius", "30px 40%"); +test_valid_value("-webkit-border-bottom-left-radius", "50% 60px"); + +// Some browsers treat '-webkit-border-radius: l1 l2' as 'border-radius: l1 / l2'. +// Regardless of whether this is done, ensure that there is round-tripping. +const target = document.getElementById("target"); +const style = target.style; +const cs = getComputedStyle(target); +test(function() { + style.cssText = "-webkit-border-radius: 1px 2px"; + const oldLonghands = [...style].map(p => p + ": " + style[p]); + const value = style.getPropertyValue("border-radius"); + assert_in_array(value, ["1px 2px", "1px / 2px"]); + assert_equals(cs.getPropertyValue("border-radius"), value); + style.cssText = "border-radius: " + value; + const newLonghands = [...style].map(p => p + ": " + style[p]); + assert_array_equals(newLonghands, oldLonghands); +}, "Serialize border-radius from -webkit-border-radius: 1px 2px"); +test(function() { + style.cssText = "border-radius: 1px 2px"; + const oldLonghands = [...style].map(p => p + ": " + style[p]); + const value = style.getPropertyValue("-webkit-border-radius"); + assert_in_array(value, ["1px 2px", "1px 2px 1px"]); + assert_equals(cs.getPropertyValue("-webkit-border-radius"), value); + style.cssText = "-webkit-border-radius: " + value; + const newLonghands = [...style].map(p => p + ": " + style[p]); + assert_array_equals(newLonghands, oldLonghands); +}, "Serialize -webkit-border-radius from border-radius: 1px 2px"); +</script> +</body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-break/fieldset-002.html b/third_party/blink/web_tests/external/wpt/css/css-break/fieldset-002.html index aea8cec5..9331b81 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-break/fieldset-002.html +++ b/third_party/blink/web_tests/external/wpt/css/css-break/fieldset-002.html
@@ -1,10 +1,10 @@ <!DOCTYPE html> <link rel="author" title="Ana Sollano Kim" href="mailto:ansollan@microsoft.com"> -<link rel="help" href="href=https://www.w3.org/TR/css-break-3/#break-decoration"> +<link rel="help" href="https://www.w3.org/TR/css-break-3/#break-decoration"> <link rel="match" href="fieldset-002-ref.html"> <p>There should be a light blue fieldset that starts in the first column and ends in the third. The top border should only be in the first column, and the bottom border should only be in the third.</p> <div style="column-count:3; column-fill:auto; column-gap:10px; width:500px; height:200px;"> <fieldset style="border:10px solid pink; margin:0; padding:0; height:500px; background:lightblue;"></fieldset> -</div> \ No newline at end of file +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-break/fieldset-003.html b/third_party/blink/web_tests/external/wpt/css/css-break/fieldset-003.html index 6c23a4b..dbf69a4 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-break/fieldset-003.html +++ b/third_party/blink/web_tests/external/wpt/css/css-break/fieldset-003.html
@@ -1,6 +1,6 @@ <!DOCTYPE html> <link rel="author" title="Ana Sollano Kim" href="mailto:ansollan@microsoft.com"> -<link rel="help" href="href=https://www.w3.org/TR/css-break-3/#break-decoration"> +<link rel="help" href="https://www.w3.org/TR/css-break-3/#break-decoration"> <link rel="match" href="fieldset-003-ref.html"> <p>There should be a light blue fieldset that starts in the first column and ends in the third. Its blue violet legend should only be in the first column, @@ -10,4 +10,4 @@ <fieldset style="margin:0; border:60px solid pink; padding:0; width:100px; background:lightblue; height:10px;"> <legend style="padding:0; width:100px; height:50px; background:blueviolet;"></legend> </fieldset> -</div> \ No newline at end of file +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-break/fieldset-004.html b/third_party/blink/web_tests/external/wpt/css/css-break/fieldset-004.html index ce832f8..4b49e6a 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-break/fieldset-004.html +++ b/third_party/blink/web_tests/external/wpt/css/css-break/fieldset-004.html
@@ -1,6 +1,6 @@ <!DOCTYPE html> <link rel="author" title="Ana Sollano Kim" href="mailto:ansollan@microsoft.com"> -<link rel="help" href="href=https://www.w3.org/TR/css-break-3/#break-decoration"> +<link rel="help" href="https://www.w3.org/TR/css-break-3/#break-decoration"> <link rel="match" href="fieldset-004-ref.html"> <p>There should be a light blue fieldset that starts in the first column and ends in the third. Its blue violet legend should only be in the first column, @@ -11,4 +11,4 @@ <fieldset style="border:10px solid pink; margin:0; padding:0; height:590px; background:lightblue;"> <legend style="padding:0; margin:0; width:50px; height:300px; background:blueviolet;"></legend> </fieldset> -</div> \ No newline at end of file +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-highlight-api/Highlight-setlike-tampered-Set-prototype.html b/third_party/blink/web_tests/external/wpt/css/css-highlight-api/Highlight-setlike-tampered-Set-prototype.html new file mode 100644 index 0000000..4c23f485 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-highlight-api/Highlight-setlike-tampered-Set-prototype.html
@@ -0,0 +1,55 @@ +<!doctype html> +<title>Highlight is a setlike interface that works as expected even if Set.prototype is tampered</title> +<link rel="help" href="https://drafts.csswg.org/css-highlight-api-1/"> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> + +<body> +<script> +"use strict"; + +function tamperSetPrototype() { + delete Set.prototype.size; + + Set.prototype.entries = null; + Set.prototype.forEach = undefined; + Set.prototype.has = "foo"; + Set.prototype.keys = 0; + Set.prototype.values = Symbol(); + Set.prototype[Symbol.iterator] = 1; + Set.prototype.add = true; + Set.prototype.clear = ""; + Set.prototype.delete = -1.5; + + Object.freeze(Set.prototype); +} + +test(() => { + tamperSetPrototype(); + + const staticRange = new StaticRange({startContainer: document.body, endContainer: document.body, startOffset: 0, endOffset: 0}); + const highlight = new Highlight(staticRange); + + assert_equals(highlight.size, 1); + assert_true(highlight.has(staticRange)); + assert_equals([...highlight.entries()][0][0], staticRange); + + highlight.clear(); + assert_equals(highlight.size, 0); + + highlight.add(staticRange); + assert_equals(highlight.size, 1); + + highlight.delete(staticRange); + assert_equals(highlight.size, 0); + assert_false(highlight.has(staticRange)); + + highlight.add(staticRange); + assert_equals([...highlight.keys()][0], staticRange); + assert_equals([...highlight.values()][0], staticRange); + + let callbackCalled = false; + highlight.forEach(() => { callbackCalled = true; }); + assert_true(callbackCalled); +}, "Highlight is a setlike interface that works as expected even if Set.prototype is tampered."); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-highlight-api/HighlightRegistry-maplike-tampered-Map-prototype-expected.txt b/third_party/blink/web_tests/external/wpt/css/css-highlight-api/HighlightRegistry-maplike-tampered-Map-prototype-expected.txt new file mode 100644 index 0000000..20e81406 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-highlight-api/HighlightRegistry-maplike-tampered-Map-prototype-expected.txt
@@ -0,0 +1,4 @@ +This is a testharness.js-based test. +FAIL HighlightRegistry is a maplike interface that works as expected even if Map.prototype is tampered. HighlightRegister is not defined +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/css/css-highlight-api/HighlightRegistry-maplike-tampered-Map-prototype.html b/third_party/blink/web_tests/external/wpt/css/css-highlight-api/HighlightRegistry-maplike-tampered-Map-prototype.html new file mode 100644 index 0000000..3b38bd8f --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-highlight-api/HighlightRegistry-maplike-tampered-Map-prototype.html
@@ -0,0 +1,61 @@ +<!doctype html> +<title>HighlightRegistry is a maplike interface that works as expected even if Map.prototype is tampered</title> +<link rel="help" href="https://drafts.csswg.org/css-highlight-api-1/"> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> + +<body> +<script> +"use strict"; + +function tamperMapPrototype() { + delete Map.prototype.size; + + Map.prototype.entries = null; + Map.prototype.forEach = undefined; + Map.prototype.get = "foo"; + Map.prototype.has = 0; + Map.prototype.keys = Symbol(); + Map.prototype.values = 1; + Map.prototype[Symbol.iterator] = true; + Map.prototype.clear = false; + Map.prototype.delete = ""; + Map.prototype.set = 3.14; + + Object.freeze(Map.prototype); +} + +test(() => { + tamperMapPrototype(); + + const highlight = new Highlight(new StaticRange({startContainer: document.body, endContainer: document.body, startOffset: 0, endOffset: 0})); + const highlightRegister = new HighlightRegister(); + + assert_equals(highlightRegister.size, 0); + highlightRegister.set("foo", highlight); + assert_equals(highlightRegister.size, 1); + + assert_true(highlightRegister.has("foo")); + assert_equals([...highlightRegister.entries()][0][0], "foo"); + + highlightRegister.clear(); + assert_equals(highlightRegister.size, 0); + assert_equals(highlightRegister.get("foo"), undefined); + + highlightRegister.set("bar", highlight); + assert_equals(highlightRegister.get("bar"), highlight); + assert_equals([...highlightRegister][0][1], highlight); + + highlightRegister.delete("bar"); + assert_equals(highlightRegister.size, 0); + assert_false(highlightRegister.has("bar")); + + highlightRegister.set("baz", highlight); + assert_equals([...highlightRegister.keys()][0], "baz"); + assert_equals([...highlightRegister.values()][0], highlight); + + let callbackCalled = false; + highlightRegister.forEach(() => { callbackCalled = true; }); + assert_true(callbackCalled); +}, "HighlightRegistry is a maplike interface that works as expected even if Map.prototype is tampered."); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-multicol/abspos-after-spanner-static-pos.html b/third_party/blink/web_tests/external/wpt/css/css-multicol/abspos-after-spanner-static-pos.html index 9b2b996..d257016 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-multicol/abspos-after-spanner-static-pos.html +++ b/third_party/blink/web_tests/external/wpt/css/css-multicol/abspos-after-spanner-static-pos.html
@@ -1,6 +1,6 @@ <!DOCTYPE html> <title>Abspos element after a column spanner</title> -<link rel="help" href="href=https://drafts.csswg.org/css-multicol/"> +<link rel="help" href="https://drafts.csswg.org/css-multicol/"> <link rel="match" href="../reference/ref-filled-green-100px-square.xht"> <style> .multicol {
diff --git a/third_party/blink/web_tests/external/wpt/css/css-multicol/abspos-after-spanner.html b/third_party/blink/web_tests/external/wpt/css/css-multicol/abspos-after-spanner.html index caed416..98664b5 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-multicol/abspos-after-spanner.html +++ b/third_party/blink/web_tests/external/wpt/css/css-multicol/abspos-after-spanner.html
@@ -1,6 +1,6 @@ <!DOCTYPE html> <title>Abspos element after a column spanner</title> -<link rel="help" href="href=https://drafts.csswg.org/css-multicol/"> +<link rel="help" href="https://drafts.csswg.org/css-multicol/"> <link rel="match" href="../reference/ref-filled-green-100px-square.xht"> <style> .multicol {
diff --git a/third_party/blink/web_tests/external/wpt/css/css-multicol/abspos-containing-block-outside-spanner.html b/third_party/blink/web_tests/external/wpt/css/css-multicol/abspos-containing-block-outside-spanner.html index ed832d3..1f0419d9 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-multicol/abspos-containing-block-outside-spanner.html +++ b/third_party/blink/web_tests/external/wpt/css/css-multicol/abspos-containing-block-outside-spanner.html
@@ -1,6 +1,6 @@ <!DOCTYPE html> <title>Abspos elements nested inside a column spanner</title> -<link rel="help" href="href=https://drafts.csswg.org/css-multicol/"> +<link rel="help" href="https://drafts.csswg.org/css-multicol/"> <link rel="match" href="abspos-containing-block-outside-spanner-ref.html"> <br><br><br><br><br> <p>There should be no red.</p>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-writing-modes/forms/meter-appearance-native-computed-style.optional.html b/third_party/blink/web_tests/external/wpt/css/css-writing-modes/forms/meter-appearance-native-computed-style.optional.html new file mode 100644 index 0000000..58e1dae --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-writing-modes/forms/meter-appearance-native-computed-style.optional.html
@@ -0,0 +1,32 @@ +<!doctype html> +<link rel="author" title="Di Zhang" href="mailto:dizhangg@chromium.org"> +<link rel="help" href="https://html.spec.whatwg.org/multipage/rendering.html#the-meter-element-2"> +<title>Meter appearance native writing mode computed style</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> + +<meter value="40" min="0" max="100" style="writing-mode: horizontal-tb"></meter> +<meter value="40" min="0" max="100" style="writing-mode: vertical-lr"></meter> +<meter value="40" min="0" max="100" style="writing-mode: vertical-rl"></meter> + +<script> +test(() => { + const meter = document.querySelector(`meter[style="writing-mode: horizontal-tb"]`); + const style = getComputedStyle(meter); + assert_equals(style.blockSize, "16px"); + assert_equals(style.inlineSize, "80px"); + assert_equals(style.blockSize, style.height); + assert_equals(style.inlineSize, style.width); +}, `meter[style="writing-mode: horizontal-tb"] block size should match height and inline size should match width`); + +for (const writingMode of ["vertical-lr", "vertical-rl"]) { + test(() => { + const meter = document.querySelector(`meter[style="writing-mode: ${writingMode}"]`); + const style = getComputedStyle(meter); + assert_equals(style.blockSize, "16px"); + assert_equals(style.inlineSize, "80px"); + assert_equals(style.blockSize, style.width); + assert_equals(style.inlineSize, style.height); + }, `meter[style="writing-mode: ${writingMode}"] block size should match width and inline size should match height`); +}; +</script> \ No newline at end of file
diff --git a/third_party/blink/web_tests/external/wpt/css/css-writing-modes/forms/meter-appearance-native-horizontal.optional.html b/third_party/blink/web_tests/external/wpt/css/css-writing-modes/forms/meter-appearance-native-horizontal.optional.html new file mode 100644 index 0000000..7b25e1a9 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-writing-modes/forms/meter-appearance-native-horizontal.optional.html
@@ -0,0 +1,11 @@ +<!DOCTYPE html> +<link rel="author" title="Di Zhang" href="mailto:dizhangg@chromium.org"> +<link rel="help" href="https://html.spec.whatwg.org/#the-meter-element"> +<link rel="help" href="https://drafts.csswg.org/css-writing-modes-4/#block-flow"> +<title>Meter appearance native writing mode horizontal</title> +<meta charset="utf-8"> +<link rel="mismatch" href="meter-appearance-native-vertical.optional.html"> + +<!-- Note test description should be the same across all files to mismatch on. --> +<p>The meter element below should match the correct writing mode.</p> +<meter value="70" min="0" max="100" style="writing-mode: horizontal-tb"></meter>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-writing-modes/forms/meter-appearance-native-vertical.optional.html b/third_party/blink/web_tests/external/wpt/css/css-writing-modes/forms/meter-appearance-native-vertical.optional.html new file mode 100644 index 0000000..6beca6b --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-writing-modes/forms/meter-appearance-native-vertical.optional.html
@@ -0,0 +1,11 @@ +<!DOCTYPE html> +<link rel="author" title="Di Zhang" href="mailto:dizhangg@chromium.org"> +<link rel="help" href="https://html.spec.whatwg.org/#the-meter-element"> +<link rel="help" href="https://drafts.csswg.org/css-writing-modes-4/#block-flow"> +<title>Meter appearance native writing mode horizontal</title> +<meta charset="utf-8"> +<link rel="mismatch" href="meter-appearance-native-horizontal.optional.html"> + +<!-- Note test description should be the same across all files to mismatch on. --> +<p>The meter element below should match the correct writing mode.</p> +<meter value="70" min="0" max="100" style="writing-mode: vertical-rl"></meter>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-writing-modes/forms/progress-appearance-native-computed-style.optional.html b/third_party/blink/web_tests/external/wpt/css/css-writing-modes/forms/progress-appearance-native-computed-style.optional.html index 6bb48bf1..47cd65e 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-writing-modes/forms/progress-appearance-native-computed-style.optional.html +++ b/third_party/blink/web_tests/external/wpt/css/css-writing-modes/forms/progress-appearance-native-computed-style.optional.html
@@ -17,7 +17,7 @@ assert_equals(style.inlineSize, "160px"); assert_equals(style.blockSize, style.height); assert_equals(style.inlineSize, style.width); -}, `progress[style="writing-mode: horizontal-tb"] block size should match height and inline should match width`); +}, `progress[style="writing-mode: horizontal-tb"] block size should match height and inline size should match width`); for (const writingMode of ["vertical-lr", "vertical-rl"]) { test(() => { @@ -27,6 +27,6 @@ assert_equals(style.inlineSize, "160px"); assert_equals(style.blockSize, style.width); assert_equals(style.inlineSize, style.height); - }, `progress[style="writing-mode: ${writingMode}"] block size should match width and inline should match width`); + }, `progress[style="writing-mode: ${writingMode}"] block size should match width and inline size should match height`); }; </script> \ No newline at end of file
diff --git a/third_party/blink/web_tests/external/wpt/custom-elements/cross-realm-callback-report-exception-expected.txt b/third_party/blink/web_tests/external/wpt/custom-elements/cross-realm-callback-report-exception-expected.txt new file mode 100644 index 0000000..5de18215 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/custom-elements/cross-realm-callback-report-exception-expected.txt
@@ -0,0 +1,8 @@ +This is a testharness.js-based test. +FAIL constructor assert_array_equals: expected property 0 to be "frame1" but got "frame0" (expected array ["frame1"] got ["frame0"]) +PASS connectedCallback +PASS disconnectedCallback +PASS attributeChangedCallback +PASS adoptedCallback +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/custom-elements/cross-realm-callback-report-exception.html b/third_party/blink/web_tests/external/wpt/custom-elements/cross-realm-callback-report-exception.html new file mode 100644 index 0000000..3067a7a --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/custom-elements/cross-realm-callback-report-exception.html
@@ -0,0 +1,83 @@ +<!doctype html> +<meta charset=utf-8> +<title>Exceptions raised in constructors / lifecycle callbacks are reported in their global objects</title> +<script src=/resources/testharness.js></script> +<script src=/resources/testharnessreport.js></script> +<iframe></iframe> +<iframe></iframe> +<iframe></iframe> +<script> +setup({ allow_uncaught_exception: true }); + +window.onerror = () => { onerrorCalls.push("top"); }; +frames[0].onerror = () => { onerrorCalls.push("frame0"); }; +frames[1].onerror = () => { onerrorCalls.push("frame1"); }; +frames[2].onerror = () => { onerrorCalls.push("frame2"); }; + +const sourceThrowError = `throw new parent.frames[2].Error("PASS")`; + +test(t => { + window.onerrorCalls = []; + + const XFoo = new frames[1].Function(sourceThrowError); + frames[0].customElements.define("x-foo-constructor", XFoo); + + frames[0].document.createElement("x-foo-constructor"); + assert_array_equals(onerrorCalls, ["frame1"]); +}, "constructor"); + +test(t => { + window.onerrorCalls = []; + + const XFooConnected = class extends frames[0].HTMLElement {}; + XFooConnected.prototype.connectedCallback = new frames[1].Function(sourceThrowError); + frames[0].customElements.define("x-foo-connected", XFooConnected); + + const el = frames[0].document.createElement("x-foo-connected"); + frames[0].document.body.append(el); + + assert_array_equals(onerrorCalls, ["frame1"]); +}, "connectedCallback"); + +test(t => { + window.onerrorCalls = []; + + const XFooDisconnected = class extends frames[0].HTMLElement {}; + XFooDisconnected.prototype.disconnectedCallback = new frames[1].Function(sourceThrowError); + frames[0].customElements.define("x-foo-disconnected", XFooDisconnected); + + const el = frames[0].document.createElement("x-foo-disconnected"); + frames[0].document.body.append(el); + el.remove(); + + assert_array_equals(onerrorCalls, ["frame1"]); +}, "disconnectedCallback"); + +test(t => { + window.onerrorCalls = []; + + const XFooAttributeChanged = class extends frames[0].HTMLElement {}; + XFooAttributeChanged.observedAttributes = ["foo"]; + XFooAttributeChanged.prototype.attributeChangedCallback = new frames[1].Function(sourceThrowError); + frames[0].customElements.define("x-foo-attribute-changed", XFooAttributeChanged); + + const el = frames[0].document.createElement("x-foo-attribute-changed"); + frames[0].document.body.append(el); + el.setAttribute("foo", "bar"); + + assert_array_equals(onerrorCalls, ["frame1"]); +}, "attributeChangedCallback"); + +test(t => { + window.onerrorCalls = []; + + const XFooAdopted = class extends frames[0].HTMLElement {}; + XFooAdopted.prototype.adoptedCallback = new frames[1].Function(sourceThrowError); + frames[0].customElements.define("x-foo-adopted", XFooAdopted); + + const el = frames[0].document.createElement("x-foo-adopted"); + document.body.append(el); + + assert_array_equals(onerrorCalls, ["frame1"]); +}, "adoptedCallback"); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/dom/nodes/MutationObserver-cross-realm-callback-report-exception.html b/third_party/blink/web_tests/external/wpt/dom/nodes/MutationObserver-cross-realm-callback-report-exception.html new file mode 100644 index 0000000..7d05c045 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/dom/nodes/MutationObserver-cross-realm-callback-report-exception.html
@@ -0,0 +1,32 @@ +<!doctype html> +<meta charset=utf-8> +<title>MutationObserver reports the exception from its callback in the callback's global object</title> +<script src=/resources/testharness.js></script> +<script src=/resources/testharnessreport.js></script> +<iframe></iframe> +<iframe></iframe> +<iframe></iframe> +<script> +setup({ allow_uncaught_exception: true }); + +const onerrorCalls = []; +window.onerror = () => { onerrorCalls.push("top"); }; +frames[0].onerror = () => { onerrorCalls.push("frame0"); }; +frames[1].onerror = () => { onerrorCalls.push("frame1"); }; +frames[2].onerror = () => { onerrorCalls.push("frame2"); }; + +async_test(t => { + window.onload = t.step_func(() => { + const target = frames[0].document.body; + const mo = new frames[0].MutationObserver(new frames[1].Function(`throw new parent.frames[2].Error("PASS");`)); + + mo.observe(target, { childList: true, subtree: true }); + target.append("foo"); + + t.step_timeout(() => { + assert_array_equals(onerrorCalls, ["frame1"]); + t.done(); + }, 4); + }); +}); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/domxpath/resolver-callback-interface-cross-realm.html b/third_party/blink/web_tests/external/wpt/domxpath/resolver-callback-interface-cross-realm.html deleted file mode 100644 index 55fbb07..0000000 --- a/third_party/blink/web_tests/external/wpt/domxpath/resolver-callback-interface-cross-realm.html +++ /dev/null
@@ -1,67 +0,0 @@ -<!DOCTYPE html> -<meta charset="utf-8"> -<title>Cross-realm XPathNSResolver throws TypeError of its associated Realm</title> -<link rel="help" href="https://webidl.spec.whatwg.org/#ref-for-prepare-to-run-script"> -<script src="/resources/testharness.js"></script> -<script src="/resources/testharnessreport.js"></script> -<script src="resources/invalid_namespace_test.js"></script> - -<iframe name="resolverGlobalObject" src="resources/empty-document.html"></iframe> - -<script> -setup({ allow_uncaught_exception: true }); - -const iframeLoaded = new Promise(resolve => { window.addEventListener("load", resolve); }); - -promise_test(async t => { - await iframeLoaded; - const resolver = new resolverGlobalObject.Object; - - return promise_rejects_js(t, resolverGlobalObject.TypeError, - invalid_namespace_test(t, resolver, resolverGlobalObject) - ); -}, "XPathNSResolver is cross-realm plain object without 'lookupNamespaceURI' property"); - -promise_test(async t => { - await iframeLoaded; - const resolver = new resolverGlobalObject.Object; - resolver.lookupNamespaceURI = {}; - - return promise_rejects_js(t, resolverGlobalObject.TypeError, - invalid_namespace_test(t, resolver, resolverGlobalObject) - ); -}, "XPathNSResolver is cross-realm plain object with non-callable 'lookupNamespaceURI' property"); - -promise_test(async t => { - await iframeLoaded; - const { proxy, revoke } = Proxy.revocable(() => {}, {}); - revoke(); - - const resolver = new resolverGlobalObject.Object; - resolver.lookupNamespaceURI = proxy; - - return promise_rejects_js(t, resolverGlobalObject.TypeError, - invalid_namespace_test(t, resolver, resolverGlobalObject) - ); -}, "XPathNSResolver is cross-realm plain object with revoked Proxy as 'lookupNamespaceURI' property"); - -promise_test(async t => { - await iframeLoaded; - const { proxy, revoke } = resolverGlobalObject.Proxy.revocable({}, {}); - revoke(); - - return promise_rejects_js(t, resolverGlobalObject.TypeError, - invalid_namespace_test(t, proxy, resolverGlobalObject) - ); -}, "XPathNSResolver is cross-realm non-callable revoked Proxy"); - -promise_test(async t => { - await iframeLoaded; - const { proxy, revoke } = resolverGlobalObject.Proxy.revocable(() => {}, {}); - revoke(); - - return promise_rejects_js(t, resolverGlobalObject.TypeError, - invalid_namespace_test(t, proxy, resolverGlobalObject) - ); -}, "XPathNSResolver is cross-realm callable revoked Proxy"); -</script>
diff --git a/third_party/blink/web_tests/external/wpt/domxpath/resolver-callback-interface-cross-realm.tentative-expected.txt b/third_party/blink/web_tests/external/wpt/domxpath/resolver-callback-interface-cross-realm.tentative-expected.txt new file mode 100644 index 0000000..2d635059 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/domxpath/resolver-callback-interface-cross-realm.tentative-expected.txt
@@ -0,0 +1,8 @@ +This is a testharness.js-based test. +FAIL XPathNSResolver is cross-realm plain object without 'lookupNamespaceURI' property assert_equals: expected "object" but got "undefined" +FAIL XPathNSResolver is cross-realm plain object with non-callable 'lookupNamespaceURI' property assert_equals: expected "object" but got "undefined" +FAIL XPathNSResolver is cross-realm non-callable revoked Proxy assert_equals: expected "object" but got "undefined" +FAIL XPathNSResolver is cross-realm callable revoked Proxy assert_equals: expected "object" but got "undefined" +FAIL XPathNSResolver is cross-realm plain object with revoked Proxy as 'lookupNamespaceURI' property assert_equals: expected "object" but got "undefined" +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/domxpath/resolver-callback-interface-cross-realm.tentative.html b/third_party/blink/web_tests/external/wpt/domxpath/resolver-callback-interface-cross-realm.tentative.html new file mode 100644 index 0000000..17f7ea7 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/domxpath/resolver-callback-interface-cross-realm.tentative.html
@@ -0,0 +1,94 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>Cross-realm XPathNSResolver throws TypeError of its associated Realm</title> +<link rel="help" href="https://webidl.spec.whatwg.org/#ref-for-prepare-to-run-script"> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> + +<iframe name="evaluateGlobalObject" src="resources/empty-document.html"></iframe> +<iframe name="resolverGlobalObject" src="resources/empty-document.html"></iframe> +<iframe name="lookupNamespaceURIGlobalObject" src="resources/empty-document.html"></iframe> +<iframe name="relevantGlobalObject" src="resources/empty-document.html"></iframe> +<iframe name="incumbentGlobalObject" src="resources/empty-document.html"></iframe> + +<script> +setup({ allow_uncaught_exception: true }); + +const expectedDOMExceptionType = "NAMESPACE_ERR"; + +test_onload(() => { + const resolver = new resolverGlobalObject.Object; + + assert_reports_exception(() => { + assert_throws_dom(expectedDOMExceptionType, evaluateGlobalObject.DOMException, bind_evaluate(resolver)); + }); +}, "XPathNSResolver is cross-realm plain object without 'lookupNamespaceURI' property"); + +test_onload(() => { + const resolver = new resolverGlobalObject.Object; + resolver.lookupNamespaceURI = new lookupNamespaceURIGlobalObject.Object; + + assert_reports_exception(() => { + assert_throws_dom(expectedDOMExceptionType, evaluateGlobalObject.DOMException, bind_evaluate(resolver)); + }); +}, "XPathNSResolver is cross-realm plain object with non-callable 'lookupNamespaceURI' property"); + +test_onload(() => { + const { proxy, revoke } = resolverGlobalObject.Proxy.revocable(new resolverGlobalObject.Object, {}); + revoke(); + + assert_reports_exception(() => { + assert_throws_dom(expectedDOMExceptionType, evaluateGlobalObject.DOMException, bind_evaluate(proxy)); + }); +}, "XPathNSResolver is cross-realm non-callable revoked Proxy"); + +test_onload(() => { + const { proxy, revoke } = resolverGlobalObject.Proxy.revocable(new resolverGlobalObject.Function, {}); + revoke(); + + assert_reports_exception(() => { + assert_throws_dom(expectedDOMExceptionType, evaluateGlobalObject.DOMException, bind_evaluate(proxy)); + }); +}, "XPathNSResolver is cross-realm callable revoked Proxy"); + +test_onload(() => { + const { proxy, revoke } = lookupNamespaceURIGlobalObject.Proxy.revocable(new lookupNamespaceURIGlobalObject.Function, {}); + revoke(); + + const resolver = new resolverGlobalObject.Object; + resolver.lookupNamespaceURI = proxy; + + assert_reports_exception(() => { + assert_throws_dom(expectedDOMExceptionType, evaluateGlobalObject.DOMException, bind_evaluate(resolver)); + }); +}, "XPathNSResolver is cross-realm plain object with revoked Proxy as 'lookupNamespaceURI' property"); + +function test_onload(fn, desc) { + async_test(t => { window.addEventListener("load", t.step_func_done(fn)); }, desc); +} + +function assert_reports_exception(fn) { + let error; + const onErrorHandler = event => { + error = event.error; + event.preventDefault(); + }; + + resolverGlobalObject.addEventListener("error", onErrorHandler); + fn(); + resolverGlobalObject.removeEventListener("error", onErrorHandler); + + assert_equals(typeof error, "object"); + assert_equals(error.constructor, evaluateGlobalObject.TypeError); +} + +function bind_evaluate(resolver) { + const boundEvaluate = new incumbentGlobalObject.Function("evaluate", "relevantDocument", "resolver", ` + evaluate.call(relevantDocument, "/foo:bar", relevantDocument.documentElement, resolver); + `); + + return () => { + boundEvaluate(evaluateGlobalObject.document.evaluate, relevantGlobalObject.document, resolver); + }; +} +</script>
diff --git a/third_party/blink/web_tests/external/wpt/fetch/api/response/response-static-error.any.js b/third_party/blink/web_tests/external/wpt/fetch/api/response/response-static-error.any.js index 4097eab..1f8c49a 100644 --- a/third_party/blink/web_tests/external/wpt/fetch/api/response/response-static-error.any.js +++ b/third_party/blink/web_tests/external/wpt/fetch/api/response/response-static-error.any.js
@@ -11,6 +11,18 @@ assert_true(responseError.headers.entries().next().done, "Headers should be empty"); }, "Check response returned by static method error()"); +promise_test (async function() { + let response = await fetch("../resources/data.json"); + + try { + response.headers.append('name', 'value'); + } catch (e) { + assert_equals(e.constructor.name, "TypeError"); + } + + assert_not_equals(response.headers.get("name"), "value", "response headers should be immutable"); +}, "Ensure response headers are immutable"); + test(function() { const headers = Response.error().headers;
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-canvas-element/toBlob-cross-realm-callback-report-exception.html b/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-canvas-element/toBlob-cross-realm-callback-report-exception.html new file mode 100644 index 0000000..393170b --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-canvas-element/toBlob-cross-realm-callback-report-exception.html
@@ -0,0 +1,29 @@ +<!doctype html> +<meta charset=utf-8> +<title>toBlob() reports the exception from its callback in the callback's global object</title> +<script src=/resources/testharness.js></script> +<script src=/resources/testharnessreport.js></script> +<iframe srcdoc="<canvas></canvas>"></iframe> +<iframe></iframe> +<iframe></iframe> +<script> +setup({ allow_uncaught_exception: true }); + +const onerrorCalls = []; +window.onerror = () => { onerrorCalls.push("top"); }; +frames[0].onerror = () => { onerrorCalls.push("frame0"); }; +frames[1].onerror = () => { onerrorCalls.push("frame1"); }; +frames[2].onerror = () => { onerrorCalls.push("frame2"); }; + +async_test(t => { + window.onload = t.step_func(() => { + const canvas = frames[0].document.querySelector("canvas"); + canvas.toBlob(new frames[1].Function(`throw new parent.frames[2].Error("PASS");`)); + + t.step_timeout(() => { + assert_array_equals(onerrorCalls, ["frame1"]); + t.done(); + }, 25); + }); +}); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-embed-element/embed-svg-navigation-resets-size.html b/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-embed-element/embed-svg-navigation-resets-size.html new file mode 100644 index 0000000..237c9c3 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-embed-element/embed-svg-navigation-resets-size.html
@@ -0,0 +1,31 @@ +<!doctype html> +<meta charset=utf-8> +<title>Intrinsic sizing of SVG embedded via <embed> should disappear on navigation</title> +<script src=/resources/testharness.js></script> +<script src=/resources/testharnessreport.js></script> +<embed id="element" name="embed" src='data:image/svg+xml, + <svg xmlns="http://www.w3.org/2000/svg" + xmlns:xlink="http://www.w3.org/1999/xlink" + viewBox="0 0 1000 1000" + width="400" + height="400" + font-size="100"> + </svg>'></embed> +<script> +promise_test(async () => { + await new Promise(resolve => { + onload = resolve; + }); + + assert_equals(element.scrollWidth, 400, "The width should be determined by the embedded SVG"); + assert_equals(element.scrollHeight, 400, "The height should be determined by the embedded SVG"); + + await new Promise(resolve => { + element.onload = resolve; + element.src = "about:blank"; + }); + + assert_equals(element.scrollWidth, 300, "The width should be the default"); + assert_equals(element.scrollHeight, 150, "The height should be the default"); +}); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/html/webappapis/animation-frames/callback-cross-realm-report-exception.html b/third_party/blink/web_tests/external/wpt/html/webappapis/animation-frames/callback-cross-realm-report-exception.html new file mode 100644 index 0000000..1b8aa41 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/webappapis/animation-frames/callback-cross-realm-report-exception.html
@@ -0,0 +1,29 @@ +<!doctype html> +<meta charset=utf-8> +<title>requestAnimationFrame() reports the exception from its callback in the callback's global object</title> +<script src=/resources/testharness.js></script> +<script src=/resources/testharnessreport.js></script> +<iframe></iframe> +<iframe></iframe> +<iframe></iframe> +<script> +setup({ allow_uncaught_exception: true }); + +const onerrorCalls = []; +window.onerror = () => { onerrorCalls.push("top"); }; +frames[0].onerror = () => { onerrorCalls.push("frame0"); }; +frames[1].onerror = () => { onerrorCalls.push("frame1"); }; +frames[2].onerror = () => { onerrorCalls.push("frame2"); }; + +async_test(t => { + window.onload = t.step_func(() => { + frames[0].requestAnimationFrame(new frames[1].Function(`throw new parent.frames[2].Error("PASS");`)); + document.querySelector("iframe").height = 200; + + t.step_timeout(() => { + assert_array_equals(onerrorCalls, ["frame1"]); + t.done(); + }, 100); + }); +}); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/html/webappapis/microtask-queuing/queue-microtask-cross-realm-callback-report-exception.html b/third_party/blink/web_tests/external/wpt/html/webappapis/microtask-queuing/queue-microtask-cross-realm-callback-report-exception.html new file mode 100644 index 0000000..fa153f8f --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/webappapis/microtask-queuing/queue-microtask-cross-realm-callback-report-exception.html
@@ -0,0 +1,28 @@ +<!doctype html> +<meta charset=utf-8> +<title>queueMicrotask() reports the exception from its callback in the callback's global object</title> +<script src=/resources/testharness.js></script> +<script src=/resources/testharnessreport.js></script> +<iframe></iframe> +<iframe></iframe> +<iframe></iframe> +<script> +setup({ allow_uncaught_exception: true }); + +const onerrorCalls = []; +window.onerror = () => { onerrorCalls.push("top"); }; +frames[0].onerror = () => { onerrorCalls.push("frame0"); }; +frames[1].onerror = () => { onerrorCalls.push("frame1"); }; +frames[2].onerror = () => { onerrorCalls.push("frame2"); }; + +async_test(t => { + window.onload = t.step_func(() => { + frames[0].queueMicrotask(new frames[1].Function(`throw new parent.frames[2].Error("PASS");`)); + + t.step_timeout(() => { + assert_array_equals(onerrorCalls, ["frame1"]); + t.done(); + }, 4); + }); +}); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/html/webappapis/scripting/processing-model-2/window-onerror-with-cross-frame-event-listeners-5.html b/third_party/blink/web_tests/external/wpt/html/webappapis/scripting/processing-model-2/window-onerror-with-cross-frame-event-listeners-5.html new file mode 100644 index 0000000..da93e78 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/webappapis/scripting/processing-model-2/window-onerror-with-cross-frame-event-listeners-5.html
@@ -0,0 +1,25 @@ +<!doctype html> +<meta charset=utf-8> +<title>window.onerror listener reports the exception in global object of its callback</title> +<link rel=help href="https://dom.spec.whatwg.org/#concept-event-listener-inner-invoke"> +<script src=/resources/testharness.js></script> +<script src=/resources/testharnessreport.js></script> +<iframe></iframe> +<iframe></iframe> +<iframe></iframe> +<script> +setup({ allow_uncaught_exception: true }); + +window.onload = () => { + test(() => { + window.onerrorCalls = []; + window.onerror = () => { onerrorCalls.push("top"); }; + frames[0].onerror = new frames[1].Function(`top.onerrorCalls.push("frame0"); throw new parent.frames[2].Error("PASS");`); + frames[1].onerror = () => { onerrorCalls.push("frame1"); }; + frames[2].onerror = () => { onerrorCalls.push("frame2"); }; + + frames[0].dispatchEvent(new ErrorEvent("error", { error: new Error("foo") })); + assert_array_equals(onerrorCalls, ["frame0", "frame1"]); + }); +}; +</script>
diff --git a/third_party/blink/web_tests/external/wpt/html/webappapis/timers/setinterval-cross-realm-callback-report-exception.html b/third_party/blink/web_tests/external/wpt/html/webappapis/timers/setinterval-cross-realm-callback-report-exception.html new file mode 100644 index 0000000..4a780fc9 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/webappapis/timers/setinterval-cross-realm-callback-report-exception.html
@@ -0,0 +1,32 @@ +<!doctype html> +<meta charset=utf-8> +<title>window.setInterval() reports the exception from its callback in the callback's global object</title> +<script src=/resources/testharness.js></script> +<script src=/resources/testharnessreport.js></script> +<iframe></iframe> +<iframe></iframe> +<iframe></iframe> +<script> +setup({ allow_uncaught_exception: true }); + +const onerrorCalls = []; +window.onerror = () => { onerrorCalls.push("top"); }; +frames[0].onerror = () => { onerrorCalls.push("frame0"); }; +frames[1].onerror = () => { onerrorCalls.push("frame1"); }; +frames[2].onerror = () => { onerrorCalls.push("frame2"); }; + +async_test(t => { + window.onload = t.step_func(() => { + const id = frames[0].setInterval(new frames[1].Function(` + parent.clearThisInterval(); + throw new parent.frames[2].Error("PASS"); + `), 4); + window.clearThisInterval = () => { frames[0].clearInterval(id); }; + + t.step_timeout(() => { + assert_array_equals(onerrorCalls, ["frame1"]); + t.done(); + }, 8); + }); +}); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/html/webappapis/timers/settimeout-cross-realm-callback-report-exception.html b/third_party/blink/web_tests/external/wpt/html/webappapis/timers/settimeout-cross-realm-callback-report-exception.html new file mode 100644 index 0000000..b4860151 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/webappapis/timers/settimeout-cross-realm-callback-report-exception.html
@@ -0,0 +1,28 @@ +<!doctype html> +<meta charset=utf-8> +<title>window.setTimeout() reports the exception from its callback in the callback's global object</title> +<script src=/resources/testharness.js></script> +<script src=/resources/testharnessreport.js></script> +<iframe></iframe> +<iframe></iframe> +<iframe></iframe> +<script> +setup({ allow_uncaught_exception: true }); + +const onerrorCalls = []; +window.onerror = () => { onerrorCalls.push("top"); }; +frames[0].onerror = () => { onerrorCalls.push("frame0"); }; +frames[1].onerror = () => { onerrorCalls.push("frame1"); }; +frames[2].onerror = () => { onerrorCalls.push("frame2"); }; + +async_test(t => { + window.onload = t.step_func(() => { + frames[0].setTimeout(new frames[1].Function(`throw new parent.frames[2].Error("PASS");`), 4); + + t.step_timeout(() => { + assert_array_equals(onerrorCalls, ["frame1"]); + t.done(); + }, 8); + }); +}); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/intersection-observer/callback-cross-realm-report-exception.html b/third_party/blink/web_tests/external/wpt/intersection-observer/callback-cross-realm-report-exception.html new file mode 100644 index 0000000..0bec7204 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/intersection-observer/callback-cross-realm-report-exception.html
@@ -0,0 +1,30 @@ +<!doctype html> +<meta charset=utf-8> +<title>IntersectionObserver reports the exception from its callback in the callback's global object</title> +<script src=/resources/testharness.js></script> +<script src=/resources/testharnessreport.js></script> +<iframe srcdoc='<div style="height: 100px;">foo</div>'></iframe> +<iframe></iframe> +<iframe></iframe> +<script> +setup({ allow_uncaught_exception: true }); + +const onerrorCalls = []; +window.onerror = () => { onerrorCalls.push("top"); }; +frames[0].onerror = () => { onerrorCalls.push("frame0"); }; +frames[1].onerror = () => { onerrorCalls.push("frame1"); }; +frames[2].onerror = () => { onerrorCalls.push("frame2"); }; + +async_test(t => { + window.onload = t.step_func(() => { + const target = frames[0].document.querySelector("div"); + const io = new frames[0].IntersectionObserver(new frames[1].Function(`throw new parent.frames[2].Error("PASS");`)); + io.observe(target); + + t.step_timeout(() => { + assert_array_equals(onerrorCalls, ["frame1"]); + t.done(); + }, 25); + }); +}); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/mathml/presentation-markup/mrow/inferred-mrow-baseline.html b/third_party/blink/web_tests/external/wpt/mathml/presentation-markup/mrow/inferred-mrow-baseline.html index cc007cf..00866468 100644 --- a/third_party/blink/web_tests/external/wpt/mathml/presentation-markup/mrow/inferred-mrow-baseline.html +++ b/third_party/blink/web_tests/external/wpt/mathml/presentation-markup/mrow/inferred-mrow-baseline.html
@@ -20,13 +20,13 @@ window.addEventListener("load", runTests); function runTests() { - ["Mrow", "Sqrt", "Style", "Error", "Phantom", "Math", "Menclose", "Mpadded", "Unknown", "Mtd"].forEach((tag) => { - var x = document.getElementById("above" + tag).getBoundingClientRect(); - var y = document.getElementById("below" + tag).getBoundingClientRect(); + ["Mrow", "Sqrt", "Style", "Error", "Phantom", "Math", "Menclose", "Mpadded", "Unknown", "Mtd", "None", "Mprescripts"].forEach((tag) => { + var x = document.getElementById(`above${tag}`).getBoundingClientRect(); + var y = document.getElementById(`below${tag}`).getBoundingClientRect(); test(function() { assert_true(MathMLFeatureDetection.has_mspace()); assert_equals(x.bottom, y.top); - }, "baseline alignment inside " + tag); + }, `baseline alignment inside ${tag}`); }); done(); } @@ -50,6 +50,8 @@ ></mspace><mspace id="belowUnknown" width="10px" depth="30px" style="background: blue"></mspace></unknown></math> <math><mtable><mtr><mtd><mspace id="aboveMtd" width="10px" height="30px" style="background: purple" ></mspace><mspace id="belowMtd" width="10px" depth="30px" style="background: blue"></mspace></mtd></mtr></mtable></math> + <math><none><mspace id="aboveNone" width="10px" height="30px" style="background: purple"></mspace><mspace id="belowNone" width="10px" depth="30px" style="background: blue"></mspace></none></math> + <math><mprescripts><mspace id="aboveMprescripts" width="10px" height="30px" style="background: purple"></mspace><mspace id="belowMprescripts" width="10px" depth="30px" style="background: blue"></mspace></none></math> </p> </body> </html>
diff --git a/third_party/blink/web_tests/external/wpt/mathml/presentation-markup/mrow/inferred-mrow-stretchy.html b/third_party/blink/web_tests/external/wpt/mathml/presentation-markup/mrow/inferred-mrow-stretchy.html index a1e409a..614438de 100644 --- a/third_party/blink/web_tests/external/wpt/mathml/presentation-markup/mrow/inferred-mrow-stretchy.html +++ b/third_party/blink/web_tests/external/wpt/mathml/presentation-markup/mrow/inferred-mrow-stretchy.html
@@ -32,12 +32,12 @@ window.addEventListener("load", () => { loadAllFonts().then(runTests); }); function runTests() { - ["Mrow", "Sqrt", "Style", "Error", "Phantom", "Math", "Menclose", "Mpadded", "Unknown", "Mtd"].forEach((tag) => { - var mo = document.getElementById("mo" + tag); + ["Mrow", "Sqrt", "Style", "Error", "Phantom", "Math", "Menclose", "Mpadded", "Unknown", "Mtd", "None", "Mprescripts"].forEach((tag) => { + var mo = document.getElementById(`mo${tag}`); test(function() { assert_true(MathMLFeatureDetection.has_mspace()); assert_greater_than_equal(mo.getBoundingClientRect().height, 100); - }, "operator stretching inside " + tag); + }, `operator stretching inside ${tag}`); }); done(); } @@ -57,6 +57,8 @@ <math><mpadded lspace="10px"><mo id="moMpadded">↨</mo><mspace width="1px" height="100px" style="background: magenta"></mspace></mpadded></math> <math><unknown><mo id="moUnknown">↨</mo><mspace width="1px" height="100px" style="background: magenta"></mspace></unknown></math> <math><mtable><mtr><mtd><mo id="moMtd">↨</mo><mspace width="1px" height="100px" style="background: magenta"></mspace></mtd></mtr></mtable></math> + <math><none><mo id="moNone">↨</mo><mspace width="1px" height="100px" style="background: magenta"></mspace></none></math> + <math><mprescripts><mo id="moMprescripts">↨</mo><mspace width="1px" height="100px" style="background: magenta"></mspace></mprescripts></math> </p> </body> </html>
diff --git a/third_party/blink/web_tests/external/wpt/mathml/presentation-markup/scripts/mprescripts-001-ref.html b/third_party/blink/web_tests/external/wpt/mathml/presentation-markup/scripts/mprescripts-001-ref.html new file mode 100644 index 0000000..f863153 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/mathml/presentation-markup/scripts/mprescripts-001-ref.html
@@ -0,0 +1,19 @@ +<!DOCTYPE html> +<html> + <head> + <meta charset="utf-8"> + <title>mprescripts should render as an mrow (reference)</title> + </head> + <body> + <math> + <mrow> + <mspace width="10px" height="20px" style="background: cyan;"></mspace> + <mspace width="30px" height="10px" depth="5px" style="background: blue;"></mspace> + <mspace width="20px" height="15px" depth="30px" style="background: lightblue;"></mspace> + <mspace width="25px" depth="20px" style="background: cyan;"></mspace> + <mspace width="40px" height="5px" depth="15px" style="background: blue;"></mspace> + <mspace width="20px" height="35px" depth="5px" style="background: lightblue;"></mspace> + </mrow> + </math> + </body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/mathml/presentation-markup/scripts/mprescripts-001.html b/third_party/blink/web_tests/external/wpt/mathml/presentation-markup/scripts/mprescripts-001.html new file mode 100644 index 0000000..2435b62 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/mathml/presentation-markup/scripts/mprescripts-001.html
@@ -0,0 +1,26 @@ +<!DOCTYPE html> +<html> + <head> + <meta charset="utf-8"> + <title>mprescripts should render as an mrow</title> + <link rel="help" href="https://w3c.github.io/mathml-core/#subscripts-and-superscripts-msub-msup-msubsup"> + <meta name="assert" content="Verify that mprescripts uses mrow layout"> + <link rel="match" href="mprescripts-001-ref.html"> + </head> + <body> + <math> + <mprescripts> + <mspace width="10px" height="20px" style="background: cyan;"></mspace> + <mspace width="30px" height="10px" depth="5px" style="background: blue;"></mspace> + <mspace width="20px" height="15px" depth="30px" style="background: lightblue;"></mspace> + <mspace width="25px" depth="20px" style="background: cyan;"></mspace> + <mspace width="40px" height="5px" depth="15px" style="background: blue;"></mspace> + <mspace width="20px" height="35px" depth="5px" style="background: lightblue;"></mspace> + </mprescripts> + </math> + <script src="/mathml/support/feature-detection.js"></script> + <script> + MathMLFeatureDetection.ensure_for_match_reftest("has_mspace"); + </script> + </body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/mathml/presentation-markup/scripts/none-001-ref.html b/third_party/blink/web_tests/external/wpt/mathml/presentation-markup/scripts/none-001-ref.html new file mode 100644 index 0000000..55add01 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/mathml/presentation-markup/scripts/none-001-ref.html
@@ -0,0 +1,19 @@ +<!DOCTYPE html> +<html> + <head> + <meta charset="utf-8"> + <title>none should render as an mrow (reference)</title> + </head> + <body> + <math> + <mrow> + <mspace width="10px" height="20px" style="background: cyan;"></mspace> + <mspace width="30px" height="10px" depth="5px" style="background: blue;"></mspace> + <mspace width="20px" height="15px" depth="30px" style="background: lightblue;"></mspace> + <mspace width="25px" depth="20px" style="background: cyan;"></mspace> + <mspace width="40px" height="5px" depth="15px" style="background: blue;"></mspace> + <mspace width="20px" height="35px" depth="5px" style="background: lightblue;"></mspace> + </mrow> + </math> + </body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/mathml/presentation-markup/scripts/none-001.html b/third_party/blink/web_tests/external/wpt/mathml/presentation-markup/scripts/none-001.html new file mode 100644 index 0000000..f1bfb442 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/mathml/presentation-markup/scripts/none-001.html
@@ -0,0 +1,26 @@ +<!DOCTYPE html> +<html> + <head> + <meta charset="utf-8"> + <title>none should render as an mrow</title> + <link rel="help" href="https://w3c.github.io/mathml-core/#subscripts-and-superscripts-msub-msup-msubsup"> + <meta name="assert" content="Verify that none uses mrow layout"> + <link rel="match" href="none-001-ref.html"> + </head> + <body> + <math> + <none> + <mspace width="10px" height="20px" style="background: cyan;"></mspace> + <mspace width="30px" height="10px" depth="5px" style="background: blue;"></mspace> + <mspace width="20px" height="15px" depth="30px" style="background: lightblue;"></mspace> + <mspace width="25px" depth="20px" style="background: cyan;"></mspace> + <mspace width="40px" height="5px" depth="15px" style="background: blue;"></mspace> + <mspace width="20px" height="35px" depth="5px" style="background: lightblue;"></mspace> + </none> + </math> + <script src="/mathml/support/feature-detection.js"></script> + <script> + MathMLFeatureDetection.ensure_for_match_reftest("has_mspace"); + </script> + </body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/mathml/presentation-markup/scripts/none-002-ref.html b/third_party/blink/web_tests/external/wpt/mathml/presentation-markup/scripts/none-002-ref.html new file mode 100644 index 0000000..dac4dab --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/mathml/presentation-markup/scripts/none-002-ref.html
@@ -0,0 +1,73 @@ +<!DOCTYPE html> +<html> + <head> + <meta charset="utf-8"> + <title>none used at other places than mmultiscripts' script (reference)</title> + <link rel="stylesheet" type="text/css" href="/fonts/ahem.css" /> + <style> + math { font: 25px/1 Ahem; } + </style> + </head> + <body> + <p> + <math> + <msub> + <mrow></mrow> + <mn>2</mn> + </msub> + </math> + <math> + <msub> + <mn>1</mn> + <mrow></mrow> + </msub> + </math> + </p> + <p> + <math> + <msup> + <mrow></mrow> + <mn>2</mn> + </msup> + </math> + <math> + <msup> + <mn>1</mn> + <mrow></mrow> + </msup> + </math> + </p> + <p> + <math> + <msubsup> + <mrow></mrow> + <mn>2</mn> + <mn>3</mn> + </msubsup> + </math> + <math> + <msubsup> + <mn>1</mn> + <mrow></mrow> + <mn>3</mn> + </msubsup> + </math> + <math> + <msubsup> + <mn>1</mn> + <mn>2</mn> + <mrow></mrow> + </msubsup> + </math> + </p> + <p> + <math> + <mmultiscripts> + <mrow></mrow> + <mn>2</mn> + <mn>3</mn> + </mmultiscripts> + </math> + </p> + </body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/mathml/presentation-markup/scripts/none-002.html b/third_party/blink/web_tests/external/wpt/mathml/presentation-markup/scripts/none-002.html new file mode 100644 index 0000000..d1f3a3a --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/mathml/presentation-markup/scripts/none-002.html
@@ -0,0 +1,76 @@ +<!DOCTYPE html> +<html> + <head> + <meta charset="utf-8"> + <title>none used at other places than mmultiscripts' script</title> + <link rel="help" href="https://w3c.github.io/mathml-core/#subscripts-and-superscripts-msub-msup-msubsup"> + <meta name="assert" content="none can be used at other places than mmultiscripts' script, without triggering 'invalid markup'"> + <link rel="match" href="none-002-ref.html"> + <link rel="stylesheet" type="text/css" href="/fonts/ahem.css" /> + <style> + math { font: 25px/1 Ahem; } + </style> + </head> + <body> + <p> + <math> + <msub> + <none/> + <mn>2</mn> + </msub> + </math> + <math> + <msub> + <mn>1</mn> + <none/> + </msub> + </math> + </p> + <p> + <math> + <msup> + <none/> + <mn>2</mn> + </msup> + </math> + <math> + <msup> + <mn>1</mn> + <none/> + </msup> + </math> + </p> + <p> + <math> + <msubsup> + <none/> + <mn>2</mn> + <mn>3</mn> + </msubsup> + </math> + <math> + <msubsup> + <mn>1</mn> + <none/> + <mn>3</mn> + </msubsup> + </math> + <math> + <msubsup> + <mn>1</mn> + <mn>2</mn> + <none/> + </msubsup> + </math> + </p> + <p> + <math> + <mmultiscripts> + <none/> + <mn>2</mn> + <mn>3</mn> + </mmultiscripts> + </math> + </p> + </body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/resize-observer/callback-cross-realm-report-exception.html b/third_party/blink/web_tests/external/wpt/resize-observer/callback-cross-realm-report-exception.html new file mode 100644 index 0000000..75a91ec --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/resize-observer/callback-cross-realm-report-exception.html
@@ -0,0 +1,30 @@ +<!doctype html> +<meta charset=utf-8> +<title>ResizeObserver reports the exception from its callback in the callback's global object</title> +<script src=/resources/testharness.js></script> +<script src=/resources/testharnessreport.js></script> +<iframe srcdoc='<div style="height: 100px;">foo</div>'></iframe> +<iframe></iframe> +<iframe></iframe> +<script> +setup({ allow_uncaught_exception: true }); + +const onerrorCalls = []; +window.onerror = () => { onerrorCalls.push("top"); }; +frames[0].onerror = () => { onerrorCalls.push("frame0"); }; +frames[1].onerror = () => { onerrorCalls.push("frame1"); }; +frames[2].onerror = () => { onerrorCalls.push("frame2"); }; + +async_test(t => { + window.onload = t.step_func(() => { + const target = frames[0].document.querySelector("div"); + const io = new frames[0].ResizeObserver(new frames[1].Function(`throw new parent.frames[2].Error("PASS");`)); + io.observe(target); + + t.step_timeout(() => { + assert_array_equals(onerrorCalls, ["frame1"]); + t.done(); + }, 25); + }); +}); +</script>
diff --git a/third_party/blink/web_tests/fast/dom/HTMLMeterElement/meter-clone-expected.txt b/third_party/blink/web_tests/fast/dom/HTMLMeterElement/meter-clone-expected.txt index f8409583..20143772 100644 --- a/third_party/blink/web_tests/fast/dom/HTMLMeterElement/meter-clone-expected.txt +++ b/third_party/blink/web_tests/fast/dom/HTMLMeterElement/meter-clone-expected.txt
@@ -2,8 +2,8 @@ PASS internals.shadowPseudoId(clonedShadowRoot.firstChild) is internals.shadowPseudoId(targetShadowRoot.firstChild) PASS internals.shadowPseudoId(clonedShadowRoot.firstChild.firstChild) is internals.shadowPseudoId(targetShadowRoot.firstChild.firstChild) PASS internals.shadowPseudoId(clonedShadowRoot.firstChild.firstChild.firstChild) is internals.shadowPseudoId(targetShadowRoot.firstChild.firstChild.firstChild) -PASS clonedShadowRoot.firstChild.firstChild.firstChild.style.width is "70%" -PASS targetShadowRoot.firstChild.firstChild.firstChild.style.width is "50%" +PASS clonedShadowRoot.firstChild.firstChild.firstChild.style.inlineSize is "70%" +PASS targetShadowRoot.firstChild.firstChild.firstChild.style.inlineSize is "50%" PASS successfullyParsed is true TEST COMPLETE
diff --git a/third_party/blink/web_tests/fast/dom/HTMLMeterElement/meter-clone.html b/third_party/blink/web_tests/fast/dom/HTMLMeterElement/meter-clone.html index 636901c..4ad7030 100644 --- a/third_party/blink/web_tests/fast/dom/HTMLMeterElement/meter-clone.html +++ b/third_party/blink/web_tests/fast/dom/HTMLMeterElement/meter-clone.html
@@ -9,23 +9,23 @@ target = document.getElementById("target"); cloned = target.cloneNode(); document.body.insertBefore(cloned, target.nextSibling); - + if (!window.internals) { debug("You need internals to run this test."); return; } - + targetShadowRoot = internals.shadowRoot(target); clonedShadowRoot = internals.shadowRoot(cloned); - + shouldBe("cloned.value", "target.value"); shouldBe("internals.shadowPseudoId(clonedShadowRoot.firstChild)", "internals.shadowPseudoId(targetShadowRoot.firstChild)"); shouldBe("internals.shadowPseudoId(clonedShadowRoot.firstChild.firstChild)", "internals.shadowPseudoId(targetShadowRoot.firstChild.firstChild)"); shouldBe("internals.shadowPseudoId(clonedShadowRoot.firstChild.firstChild.firstChild)", "internals.shadowPseudoId(targetShadowRoot.firstChild.firstChild.firstChild)"); cloned.value = 70; - shouldBe("clonedShadowRoot.firstChild.firstChild.firstChild.style.width", '"70%"'); - shouldBe("targetShadowRoot.firstChild.firstChild.firstChild.style.width", '"50%"'); + shouldBe("clonedShadowRoot.firstChild.firstChild.firstChild.style.inlineSize", '"70%"'); + shouldBe("targetShadowRoot.firstChild.firstChild.firstChild.style.inlineSize", '"50%"'); })(); </script> </body>
diff --git a/third_party/blink/web_tests/fast/dom/HTMLMeterElement/meter-element-expected.png b/third_party/blink/web_tests/fast/dom/HTMLMeterElement/meter-element-expected.png index 95b569f..133f3ddd 100644 --- a/third_party/blink/web_tests/fast/dom/HTMLMeterElement/meter-element-expected.png +++ b/third_party/blink/web_tests/fast/dom/HTMLMeterElement/meter-element-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/fast/dom/HTMLMeterElement/meter-element-markup-expected.txt b/third_party/blink/web_tests/fast/dom/HTMLMeterElement/meter-element-markup-expected.txt index 1462245..e7a9d4bf 100644 --- a/third_party/blink/web_tests/fast/dom/HTMLMeterElement/meter-element-markup-expected.txt +++ b/third_party/blink/web_tests/fast/dom/HTMLMeterElement/meter-element-markup-expected.txt
@@ -14,7 +14,7 @@ | shadow:pseudoId="-webkit-meter-bar" | <div> | pseudo="-webkit-meter-optimum-value" -| style="width: 70%;" +| style="inline-size: 70%; block-size: 100%;" | shadow:pseudoId="-webkit-meter-optimum-value" | <div> | pseudo="-internal-fallback" @@ -38,7 +38,7 @@ | shadow:pseudoId="-webkit-meter-bar" | <div> | pseudo="-webkit-meter-suboptimum-value" -| style="width: 100%;" +| style="inline-size: 100%; block-size: 100%;" | shadow:pseudoId="-webkit-meter-suboptimum-value" | <div> | pseudo="-internal-fallback" @@ -62,7 +62,7 @@ | shadow:pseudoId="-webkit-meter-bar" | <div> | pseudo="-webkit-meter-even-less-good-value" -| style="width: 100%;" +| style="inline-size: 100%; block-size: 100%;" | shadow:pseudoId="-webkit-meter-even-less-good-value" | <div> | pseudo="-internal-fallback"
diff --git a/third_party/blink/web_tests/fast/dom/HTMLMeterElement/meter-writing-mode-expected.html b/third_party/blink/web_tests/fast/dom/HTMLMeterElement/meter-writing-mode-expected.html index daa6cabe..5ea86813 100644 --- a/third_party/blink/web_tests/fast/dom/HTMLMeterElement/meter-writing-mode-expected.html +++ b/third_party/blink/web_tests/fast/dom/HTMLMeterElement/meter-writing-mode-expected.html
@@ -8,8 +8,8 @@ </style> </head> <body> -<meter min=0 value=30 max=100></meter> -<meter min=0 value=30 max=100></meter> -<meter min=0 value=30 max=100></meter> +<meter min=0 value=30 max=100 style="writing-mode: vertical-lr;"></meter> +<meter min=0 value=30 max=100 style="writing-mode: vertical-lr;"></meter> +<meter min=0 value=30 max=100 style="writing-mode: horizontal-tb;"></meter> </body> </html>
diff --git a/third_party/blink/web_tests/fast/dom/HTMLMeterElement/meter-writing-mode.html b/third_party/blink/web_tests/fast/dom/HTMLMeterElement/meter-writing-mode.html index 3e14617..dd6c56b 100644 --- a/third_party/blink/web_tests/fast/dom/HTMLMeterElement/meter-writing-mode.html +++ b/third_party/blink/web_tests/fast/dom/HTMLMeterElement/meter-writing-mode.html
@@ -8,7 +8,6 @@ </style> </head> <body> -<!-- writing-mode doen't work for now. --> <meter min=0 value=30 max=100 style="-webkit-writing-mode: vertical-lr;"></meter> <meter min=0 value=30 max=100 style="-webkit-writing-mode: vertical-rl;"></meter> <meter min=0 value=30 max=100 style="-webkit-writing-mode: horizontal-tb;"></meter>
diff --git a/third_party/blink/web_tests/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.txt b/third_party/blink/web_tests/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.txt new file mode 100644 index 0000000..6b14542 --- /dev/null +++ b/third_party/blink/web_tests/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.txt
@@ -0,0 +1 @@ +CONSOLE ERROR: Uncaught TypeError: Cannot read properties of null (reading 'offsetLeft')
diff --git a/third_party/blink/web_tests/fast/forms/color-scheme/meter/meter-appearance-basic-vertical.html b/third_party/blink/web_tests/fast/forms/color-scheme/meter/meter-appearance-basic-vertical.html new file mode 100644 index 0000000..9b55442 --- /dev/null +++ b/third_party/blink/web_tests/fast/forms/color-scheme/meter/meter-appearance-basic-vertical.html
@@ -0,0 +1,85 @@ +<!DOCTYPE html> +<html> +<head> +<meta name="color-scheme" content="light dark"> +<style> + meter { writing-mode: vertical-lr; } + meter.tall { width: 30px; height: 40px; } + ul, h2, p { margin: 0.2em; display: inline-block; } + h2 { font-size: medium; } + li { margin: 0.2em; list-style-type: none; } + meter.barstyled::-webkit-meter-bar { background: gray; border-style: solid; border-width: 2px; border-color: black; } + meter.optimumvalstyled::-webkit-meter-optimum-value { background: cadetblue; border-style: solid; border-width: 2px; border-color: blue; } + meter.suboptimumvalstyled::-webkit-meter-suboptimum-value { background: cadetblue; border-style: solid; border-width: 2px; border-color: blue; } + meter.evenlessgoodvalstyled::-webkit-meter-even-less-good-value { background: cadetblue; border-style: solid; border-width: 2px; border-color: blue; } + meter#bar-paddings::-webkit-meter-bar { padding: 2px; } +</style> +</head> +<body> +<h2>No style for reference</h2> +<ul> + <li><meter min="0" max="100" low="30" high="60" optimum="100" value="80"></meter> + <meter min="0" max="100" low="30" high="60" optimum="100" value="45"></meter> + <meter min="0" max="100" low="30" high="60" optimum="100" value="25"></meter> + <meter class="tall" min="0" max="100" low="30" high="60" optimum="100" value="75"></meter> + <meter class="tall" min="0" max="100" low="30" high="60" optimum="100" value="45"></meter> + <meter class="tall" min="0" max="100" low="30" high="60" optimum="100" value="25"></meter></li> +</ul> +<h2>Providing meter styles</h2> +<ul> + <li>Check that border is created:</li> + <li>Check that padding is created:</li> + <li>Check that margin is created:</li> + <li>Check that box shadow is drawn:</li> + <li>Check that background CSS property disables -webkit-appearance:</li> +</ul> +<ul> + <meter style="border-color: #000000; border-style: solid; border-width: 5px;" min="0" max="100" low="30" high="60" optimum="100" value="80" ></meter> + <meter style="border-color: #000000; padding: 5px;" min="0" max="100" low="30" high="60" optimum="100" value="80" ></meter> + <meter style="border-color: #000000; margin: 5px;" min="0" max="100" low="30" high="60" optimum="100" value="80" ></meter> + <meter style="box-shadow: 4px 4px 10px rgba(255,0,0,0.5), inset 4px 4px 4px rgba(0,255,0,0.5);"></meter> + <meter style="background: blue; color: white;" min="0" max="100" low="30" high="60" optimum="100" value="80"></meter> +</ul> +<h2>Providing bar and/or value styles</h2> +<div> +<ul> + <li>Check that optimum value is being styled:</li> + <li>Check that suboptimum value is being styled:</li> + <li>Check that even less good value is being styled:</li> + <li>Check that meter bar is being styled:</li> + <li>Check that meter bar and optimum value is being styled:</li> + <li>Check that meter bar and optimum value is being styled:</li> + <li>Check that meter bar and optimum value is being styled:</li> +</ul> +<ul> + <meter class="optimumvalstyled" min="0" max="100" low="30" high="60" optimum="100" value="80" ></meter> + <meter class="suboptimumvalstyled" min="0" max="100" low="30" high="60" optimum="100" value="45" ></meter> + <meter class="evenlessgoodvalstyled" min="0" max="100" low="30" high="60" optimum="100" value="25" ></meter> + <meter class="barstyled" min="0" max="100" low="30" high="60" optimum="100" value="80" ></meter> + <meter class="barstyled optimumvalstyled" min="0" max="100" low="30" high="60" optimum="100" value="80" ></meter> + <meter class="barstyled suboptimumvalstyled" min="0" max="100" low="30" high="60" optimum="100" value="45" ></meter> + <meter class="barstyled evenlessgoodvalstyled" min="0" max="100" low="30" high="60" optimum="100" value="25" ></meter> +</ul> +<h2>Providing appearance none</h2> +<ul> + <li>Check that the meter disappears but the meters content is still present:</li> + <li>Check that the meter still disappears when meter is initially rendered with "meter" appearance:</li> +</ul> +<ul> + <meter style="-webkit-appearance: none" min="0" max="100" low="30" high="60" optimum="100" value="80" >80</meter> +</ul> +<h2>Providing bar paddings</h2> +<ul> + <li>Check that meter bar gets padding:</li> +</ul> +<ul> + <meter id="bar-paddings" min="0" max="100" low="30" high="60" optimum="100" value="80" ></meter> +</ul> +<script> +var noneLater = document.getElementById('appearanceNoneLater'); +noneLater.offsetLeft; // Force layout. +noneLater.setAttribute('style', '-webkit-appearance:none'); +noneLater.offsetLeft; // Force layout. +</script> +</body> +</html> \ No newline at end of file
diff --git a/third_party/blink/web_tests/fast/forms/color-scheme/meter/meter-appearance-basic.html b/third_party/blink/web_tests/fast/forms/color-scheme/meter/meter-appearance-basic.html index c0c9af9..ec043c59 100644 --- a/third_party/blink/web_tests/fast/forms/color-scheme/meter/meter-appearance-basic.html +++ b/third_party/blink/web_tests/fast/forms/color-scheme/meter/meter-appearance-basic.html
@@ -44,7 +44,7 @@ </ul> <h2>Providing appearance none</h2> <ul> - <li>Check that the meter disappears but the meters content is still present: <meter style="-webkit-appearance: none" min="0" max="100" low="30" high="60" optimum="100" value="80" >80</meter></li> + <li>Check that the meter disappears but the meters content is still present: <meter style="-webkit-appearance: none" min="0" max="100" low="30" high="60" optimum="100" value="80" >80</meter></li> <li>Check that the meter still disappears when meter is initially rendered with "meter" appearance: <meter id="appearanceNoneLater" min="0" max="100" low="30" high="60" optimum="100" value="80" >80%</meter></li> </ul> <h2>Providing bar paddings</h2>
diff --git a/third_party/blink/web_tests/flag-specific/disable-layout-ng/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png b/third_party/blink/web_tests/flag-specific/disable-layout-ng/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png new file mode 100644 index 0000000..c5587532 --- /dev/null +++ b/third_party/blink/web_tests/flag-specific/disable-layout-ng/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/flag-specific/disable-layout-ng/virtual/dark-color-scheme/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png b/third_party/blink/web_tests/flag-specific/disable-layout-ng/virtual/dark-color-scheme/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png new file mode 100644 index 0000000..c03806a --- /dev/null +++ b/third_party/blink/web_tests/flag-specific/disable-layout-ng/virtual/dark-color-scheme/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/http/tests/inspector-protocol/tracing/network-requests-expected.txt b/third_party/blink/web_tests/http/tests/inspector-protocol/tracing/network-requests-expected.txt deleted file mode 100644 index 3dd9a717..0000000 --- a/third_party/blink/web_tests/http/tests/inspector-protocol/tracing/network-requests-expected.txt +++ /dev/null
@@ -1,115 +0,0 @@ -Tests the data of Network request lifecycle trace events -Recording started -Tracing complete -Got ResourceWillSendRequest event: -Object: { - args: { - data: { - requestId: string - } - } - cat: string - name: string - ph: string - pid: number - s: string - tid: number - ts: number -} -Got ResourceSendRequest event: -Object: { - args: { - data: { - frame: string - priority: string - requestId: string - requestMethod: string - url: string - } - } - cat: string - name: string - ph: string - pid: number - s: string - tid: number - ts: number -} -Got ResourceReceiveResponse event: -Object: { - args: { - data: { - encodedDataLength: number - frame: string - fromCache: boolean - fromServiceWorker: boolean - mimeType: string - requestId: string - responseTime: number - statusCode: number - timing: { - connectEnd: number - connectStart: number - dnsEnd: number - dnsStart: number - proxyEnd: number - proxyStart: number - pushEnd: number - pushStart: number - receiveHeadersEnd: number - requestTime: number - sendEnd: number - sendStart: number - sslEnd: number - sslStart: number - workerReady: number - workerStart: number - } - } - } - cat: string - name: string - ph: string - pid: number - s: string - tid: number - ts: number -} -Got ResourceReceivedData event: -Object: { - args: { - data: { - encodedDataLength: number - frame: string - requestId: string - } - } - cat: string - name: string - ph: string - pid: number - s: string - tid: number - ts: number -} -Got ResourceFinish event: -Object: { - args: { - data: { - decodedBodyLength: number - didFail: boolean - encodedDataLength: number - finishTime: number - requestId: string - } - } - cat: string - name: string - ph: string - pid: number - s: string - tid: number - ts: number -} -All request ids are equal -
diff --git a/third_party/blink/web_tests/http/tests/inspector-protocol/tracing/network-requests.js b/third_party/blink/web_tests/http/tests/inspector-protocol/tracing/network-requests.js deleted file mode 100644 index 61e78d32..0000000 --- a/third_party/blink/web_tests/http/tests/inspector-protocol/tracing/network-requests.js +++ /dev/null
@@ -1,58 +0,0 @@ -(async function(testRunner) { - const {session, dp} = await testRunner.startBlank( - 'Tests the data of Network request lifecycle trace events'); - - const TracingHelper = - await testRunner.loadScript('../resources/tracing-test.js'); - const tracingHelper = new TracingHelper(testRunner, session); - - await tracingHelper.startTracing('devtools.timeline'); - await dp.Page.navigate( - {url: 'http://127.0.0.1:8000/inspector-protocol/resources/basic.html'}); - - - // Wait for trace events. - await new Promise(resolve => setTimeout(resolve, 1000)); - - await tracingHelper.stopTracing(/devtools.timeline/); - - - const resourceWillSendRequest = - tracingHelper.findEvent('ResourceWillSendRequest', 'I'); - const resourceSendRequest = - tracingHelper.findEvent('ResourceSendRequest', 'I'); - const resourceReceiveResponse = - tracingHelper.findEvent('ResourceReceiveResponse', 'I'); - const resourceReceivedData = - tracingHelper.findEvent('ResourceReceivedData', 'I'); - const resourceFinish = tracingHelper.findEvent('ResourceFinish', 'I'); - - - testRunner.log('Got ResourceWillSendRequest event:'); - tracingHelper.logEventShape(resourceWillSendRequest) - - testRunner.log('Got ResourceSendRequest event:'); - tracingHelper.logEventShape(resourceSendRequest) - - testRunner.log('Got ResourceReceiveResponse event:'); - tracingHelper.logEventShape(resourceReceiveResponse) - - testRunner.log('Got ResourceReceivedData event:'); - tracingHelper.logEventShape(resourceReceivedData) - - testRunner.log('Got ResourceFinish event:'); - tracingHelper.logEventShape(resourceFinish) - - const allRequestIds = [ - resourceWillSendRequest, resourceSendRequest, resourceReceiveResponse, - resourceReceivedData, resourceFinish - ].map(event => event.args.data.requestId); - - const allIdsAreEqual = allRequestIds.every(id => id === allRequestIds[0]); - - if (allIdsAreEqual) { - testRunner.log('All request ids are equal'); - } - - testRunner.completeTest(); -})
diff --git a/third_party/blink/web_tests/platform/linux/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png b/third_party/blink/web_tests/platform/linux/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png new file mode 100644 index 0000000..48c24ad --- /dev/null +++ b/third_party/blink/web_tests/platform/linux/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/controls-refresh-hc/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png b/third_party/blink/web_tests/platform/linux/virtual/controls-refresh-hc/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png new file mode 100644 index 0000000..02a47e3 --- /dev/null +++ b/third_party/blink/web_tests/platform/linux/virtual/controls-refresh-hc/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/dark-color-scheme/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png b/third_party/blink/web_tests/platform/linux/virtual/dark-color-scheme/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png new file mode 100644 index 0000000..1a0958cd --- /dev/null +++ b/third_party/blink/web_tests/platform/linux/virtual/dark-color-scheme/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac11-arm64/virtual/dark-color-scheme/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png b/third_party/blink/web_tests/platform/mac-mac11-arm64/virtual/dark-color-scheme/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png new file mode 100644 index 0000000..4fae70a --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac11-arm64/virtual/dark-color-scheme/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac12-arm64/virtual/dark-color-scheme/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png b/third_party/blink/web_tests/platform/mac-mac12-arm64/virtual/dark-color-scheme/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png new file mode 100644 index 0000000..4fae70a --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac12-arm64/virtual/dark-color-scheme/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png b/third_party/blink/web_tests/platform/mac/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png new file mode 100644 index 0000000..f3e86e63 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/virtual/controls-refresh-hc/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png b/third_party/blink/web_tests/platform/mac/virtual/controls-refresh-hc/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png new file mode 100644 index 0000000..60a73c1 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac/virtual/controls-refresh-hc/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/virtual/dark-color-scheme/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png b/third_party/blink/web_tests/platform/mac/virtual/dark-color-scheme/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png new file mode 100644 index 0000000..8d010ff --- /dev/null +++ b/third_party/blink/web_tests/platform/mac/virtual/dark-color-scheme/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png b/third_party/blink/web_tests/platform/win/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png new file mode 100644 index 0000000..398d84b --- /dev/null +++ b/third_party/blink/web_tests/platform/win/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/virtual/controls-refresh-hc/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png b/third_party/blink/web_tests/platform/win/virtual/controls-refresh-hc/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png new file mode 100644 index 0000000..d6dba75 --- /dev/null +++ b/third_party/blink/web_tests/platform/win/virtual/controls-refresh-hc/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/virtual/dark-color-scheme/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png b/third_party/blink/web_tests/platform/win/virtual/dark-color-scheme/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png new file mode 100644 index 0000000..1f0afeb --- /dev/null +++ b/third_party/blink/web_tests/platform/win/virtual/dark-color-scheme/fast/forms/color-scheme/meter/meter-appearance-basic-vertical-expected.png Binary files differ
diff --git a/third_party/nearby/README.chromium b/third_party/nearby/README.chromium index 5a441b3d..ee162426 100644 --- a/third_party/nearby/README.chromium +++ b/third_party/nearby/README.chromium
@@ -1,7 +1,7 @@ Name: Nearby Connections Library Short Name: Nearby URL: https://github.com/google/nearby -Version: 00b1a1570ef5290394b7e865a67392ae4199f4c4 +Version: 6871b9d5a6c5bf74bc1e8f893a4cc4ddef1b6491 License: Apache 2.0 License File: LICENSE Security Critical: yes
diff --git a/tools/cast3p/cast_core.version b/tools/cast3p/cast_core.version index f39f58ff..66d9d66 100644 --- a/tools/cast3p/cast_core.version +++ b/tools/cast3p/cast_core.version
@@ -1 +1 @@ -cast_20220930_0600_RC08 +cast_20221128_0600_RC01
diff --git a/tools/mb/mb_config.pyl b/tools/mb/mb_config.pyl index e3bbd52..ad2ebaa 100644 --- a/tools/mb/mb_config.pyl +++ b/tools/mb/mb_config.pyl
@@ -3271,7 +3271,7 @@ ], 'official_goma_fuchsia_x64_perf': [ - 'official', 'goma', 'minimal_symbols', 'fuchsia', 'x64', 'ffmpeg_branding_chrome', 'proprietary_codecs', 'test_isolate_no_emulator' + 'official', 'goma', 'minimal_symbols', 'fuchsia', 'x64', 'ffmpeg_branding_chrome', 'proprietary_codecs', 'test_isolate_no_emulator', 'fuchsia_chrome' ], 'official_goma_linux_perf': [
diff --git a/tools/mb/mb_config_expectations/chromium.perf.fyi.json b/tools/mb/mb_config_expectations/chromium.perf.fyi.json index aa2e6db..7d344ce 100644 --- a/tools/mb/mb_config_expectations/chromium.perf.fyi.json +++ b/tools/mb/mb_config_expectations/chromium.perf.fyi.json
@@ -63,6 +63,7 @@ "fuchsia-builder-perf-x64": { "gn_args": { "ffmpeg_branding": "Chrome", + "fuchsia_browser_type": "chrome", "is_chrome_branded": true, "is_official_build": true, "proprietary_codecs": true,
diff --git a/tools/mb/mb_config_expectations/tryserver.chromium.perf.json b/tools/mb/mb_config_expectations/tryserver.chromium.perf.json index e07f102..dca39b91 100644 --- a/tools/mb/mb_config_expectations/tryserver.chromium.perf.json +++ b/tools/mb/mb_config_expectations/tryserver.chromium.perf.json
@@ -92,6 +92,7 @@ "Fuchsia Builder Perf x64": { "gn_args": { "ffmpeg_branding": "Chrome", + "fuchsia_browser_type": "chrome", "is_chrome_branded": true, "is_official_build": true, "proprietary_codecs": true,
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index b95c261..7a98085f 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -6453,6 +6453,9 @@ label="A challenge option was selected and the server returned success"/> <int value="4" label="A challenge option was selected and the server returned failure"/> + <int value="5" + label="A challenge option was selected and the user clicked accept. No + server call is necessary."/> </enum> <enum name="AutofillCardUploadDecision"> @@ -41924,6 +41927,37 @@ <int value="2" label="BrowserObservedSignIn"/> </enum> +<enum name="FederatedClientEvent"> + <int value="0" label="kExampleReceived"/> + <int value="1" label="kGetExampleIteratorError"/> + <int value="2" label="kGetNextExampleError"/> + <int value="3" label="kUnsatisfiedConditionAbort"/> + <int value="4" label="kContributed"/> + <int value="5" label="kRejected"/> + <int value="6" label="kTaskFailedUnknownError"/> +</enum> + +<enum name="FederatedServiceEvent"> + <int value="0" label="kLibraryLoadingSuccess"/> + <int value="1" label="kDlcAlreadyInstalled"/> + <int value="2" label="kDlcInstallTriggered"/> + <int value="3" label="kDlcNewlyInstalled"/> + <int value="4" label="kDlcKnownError"/> + <int value="5" label="kDlcUnknownError"/> + <int value="6" label="kInvalidLibraryError"/> + <int value="7" label="kFunctionMissingError"/> + <int value="8" label="kTaskSkipped"/> +</enum> + +<enum name="FederatedStorageEvent"> + <int value="0" label="kConnected"/> + <int value="1" label="kDisconnected"/> + <int value="2" label="kEmptyUsernameError"/> + <int value="3" label="kDbInitError"/> + <int value="4" label="kDbIntegrityCheckError"/> + <int value="5" label="kDbCleanOutdatedDataError"/> +</enum> + <enum name="FeedAutoplayEvent"> <obsolete> Removed as of 05/2021. Replaced by FeedVideoPlayEvent. @@ -58547,6 +58581,7 @@ <int value="-1225629234" label="SyncPseudoUSSFavicons:enabled"/> <int value="-1225198073" label="ReaderModeInCCT:disabled"/> <int value="-1224962996" label="PwaImprovedSplashScreen:disabled"/> + <int value="-1224843921" label="DevToolsTabTarget:enabled"/> <int value="-1222805155" label="PdfIsolation:enabled"/> <int value="-1222757260" label="DefaultMeetWebApp:enabled"/> <int value="-1222556118" label="VirtualDesks:disabled"/> @@ -58972,6 +59007,7 @@ <int value="-981237342" label="SyncUSSAutofillWalletMetadata:disabled"/> <int value="-981033001" label="TabScrollingButtonPosition:enabled"/> <int value="-980889204" label="SharingRenameDevices:enabled"/> + <int value="-980475527" label="DevToolsTabTarget:disabled"/> <int value="-980317085" label="EnablePasswordsAccountStorage:disabled"/> <int value="-980260493" label="NTPSnippets:disabled"/> <int value="-980054107" label="DestroyProfileOnBrowserClose:enabled"/> @@ -62434,6 +62470,7 @@ <int value="1088915385" label="new-password-form-parsing:enabled"/> <int value="1089106835" label="ContextMenuPopupStyle:enabled"/> <int value="1089913432" label="VirtualDesksGestures:disabled"/> + <int value="1090324500" label="EcheLauncher:enabled"/> <int value="1090377940" label="enable-quic-https"/> <int value="1090442943" label="SemanticColorDebugOverride:enabled"/> <int value="1091157601" label="SearchNavigationPrefetch:enabled"/> @@ -63333,6 +63370,7 @@ <int value="1632112977" label="ash-disable-tablet-autohide-titlebars"/> <int value="1632176267" label="PDFViewerUpdate:enabled"/> <int value="1633456034" label="chrome-home-swipe-logic"/> + <int value="1634273054" label="OsIntegrationSubManagers:enabled"/> <int value="1634732103" label="PassiveDocumentWheelEventListeners:enabled"/> <int value="1634884226" label="AutofillAlwaysReturnCloudTokenizedCard:enabled"/> @@ -63406,6 +63444,7 @@ <int value="1671021713" label="AutofillImportDynamicForms:disabled"/> <int value="1671985641" label="WebViewVulkan:enabled"/> <int value="1672062546" label="PasswordStrengthIndicator:disabled"/> + <int value="1672637465" label="OsIntegrationSubManagers:disabled"/> <int value="1673185316" label="EarlyCodeCache:enabled"/> <int value="1673427566" label="ChromeHomeExpandButton:disabled"/> <int value="1673776797" @@ -64056,6 +64095,7 @@ <int value="2051403297" label="ShowBluetoothDeviceBattery:disabled"/> <int value="2051886966" label="PwaInstallUseBottomSheet:enabled"/> <int value="2052194225" label="ChromeOSSharingHub:disabled"/> + <int value="2053269084" label="EcheLauncher:disabled"/> <int value="2055184887" label="LocalHistoryZeroSuggestBeyondNTP:enabled"/> <int value="2056572020" label="EnableUsernameCorrection:disabled"/> <int value="2058148069" label="UseMessagesStagingUrl:enabled"/> @@ -76842,6 +76882,15 @@ <int value="3" label="Internal error"/> </enum> +<enum name="ParentAccessFlowResult"> + <int value="0" label="Initial screen"/> + <int value="1" label="Parent authentication"/> + <int value="2" label="Approval screen"/> + <int value="3" label="Access approved"/> + <int value="4" label="Access declined"/> + <int value="5" label="Error"/> +</enum> + <enum name="ParentFrameKnown"> <int value="0" label="Parent Frame Not Known"/> <int value="1" label="Parent Frame Known"/>
diff --git a/tools/metrics/histograms/metadata/arc/histograms.xml b/tools/metrics/histograms/metadata/arc/histograms.xml index 188d259..525b719 100644 --- a/tools/metrics/histograms/metadata/arc/histograms.xml +++ b/tools/metrics/histograms/metadata/arc/histograms.xml
@@ -1603,7 +1603,7 @@ </histogram> <histogram name="Arc.OptInSilentAuthCode.Reauthorization" - enum="ArcOptInSilentAuthCode" expires_after="2023-01-10"> + enum="ArcOptInSilentAuthCode" expires_after="2024-01-10"> <owner>mhasank@google.com</owner> <owner>khmel@google.com</owner> <owner>arc-core@google.com</owner>
diff --git a/tools/metrics/histograms/metadata/autofill/histograms.xml b/tools/metrics/histograms/metadata/autofill/histograms.xml index b86da56d..190f7f9 100644 --- a/tools/metrics/histograms/metadata/autofill/histograms.xml +++ b/tools/metrics/histograms/metadata/autofill/histograms.xml
@@ -1058,6 +1058,28 @@ variants="AutofillSeamlessnessVisibility"/> </histogram> +<histogram + name="Autofill.CreditCard.SuggestionAcceptanceLatencySinceShown.{CardMetadataVisible}" + units="ms" expires_after="2023-05-01"> + <owner>siyua@chromium.org</owner> + <owner>payments-autofill-team@google.com</owner> + <summary> + The latency between an Autofill credit card suggestion being shown, and when + it was selected, in milliseconds. Logged immediately when a card is selected + by the user, on the condition that any card (not necessarily the selected + card) in the suggestion list has card metadata available (even if the + metadata is not shown). + </summary> + <token key="CardMetadataVisible"> + <variant name="ArtImageShown" summary="Only art image was visible"/> + <variant name="MetadataNotShown" summary="No metadata was visible"/> + <variant name="ProductDescriptionAndArtImageShown" + summary="Both product description and art image were visible"/> + <variant name="ProductDescriptionShown" + summary="Only product description was visible"/> + </token> +</histogram> + <histogram name="Autofill.CreditCardFillingInfoBar" enum="AutofillCreditCardInfoBar" expires_after="2023-09-30"> <owner>jsaul@google.com</owner> @@ -3450,8 +3472,9 @@ <histogram name="Autofill.SaveCardRequestExpirationDateReason" enum="AutofillSaveCardRequestExpirationDateReason" - expires_after="2023-01-31"> + expires_after="2023-11-01"> <owner>jsaul@google.com</owner> + <owner>siyua@chromium.org</owner> <owner>payments-autofill-team@google.com</owner> <summary> Records the reason expiration date was explicitly requested from the user @@ -3461,9 +3484,10 @@ <histogram name="Autofill.SaveCreditCardPromptOffer{AutofillSaveCreditCardPromptDestination}" - enum="AutofillSaveCreditCardPromptOfferEnum" expires_after="2023-01-01"> + enum="AutofillSaveCreditCardPromptOfferEnum" expires_after="2023-11-01"> <owner>jsaul@google.com</owner> <owner>siyua@chromium.org</owner> + <owner>payments-autofill-team@google.com</owner> <summary> The relative frequency with which the Autofill save credit card prompt is shown or not. Logged when the flow is triggered and the prompt should be @@ -3477,9 +3501,10 @@ <histogram name="Autofill.SaveCreditCardPromptResult{AutofillSaveCreditCardPromptDestination}" - enum="AutofillSaveCreditCardPromptResultEnum" expires_after="2023-01-01"> + enum="AutofillSaveCreditCardPromptResultEnum" expires_after="2023-11-01"> <owner>jsaul@google.com</owner> <owner>siyua@chromium.org</owner> + <owner>payments-autofill-team@google.com</owner> <summary> The relative frequency with which users accept or deny the Autofill save credit card prompt. Logged when users interacted with the prompt. @@ -3636,9 +3661,10 @@ </histogram> <histogram name="Autofill.Snackbar.{SnackbarType}.ActionClicked" - enum="BooleanShown" expires_after="2022-12-01"> + enum="BooleanShown" expires_after="2023-11-01"> <owner>siashah@chromium.org</owner> <owner>jsaul@google.com</owner> + <owner>payments-autofill-team@google.com</owner> <summary> Emits true when the action button on the autofill snackbar is clicked and does not emit any value otherwise. @@ -3647,9 +3673,10 @@ </histogram> <histogram name="Autofill.Snackbar.{SnackbarType}.Shown" enum="BooleanShown" - expires_after="2022-12-01"> + expires_after="2023-11-01"> <owner>siashah@chromium.org</owner> <owner>jsaul@google.com</owner> + <owner>payments-autofill-team@google.com</owner> <summary> Emits true when the autofill snackbar is displayed and does not emit any value otherwise.
diff --git a/tools/metrics/histograms/metadata/chromeos/histograms.xml b/tools/metrics/histograms/metadata/chromeos/histograms.xml index ada2f0a3..6cfc818 100644 --- a/tools/metrics/histograms/metadata/chromeos/histograms.xml +++ b/tools/metrics/histograms/metadata/chromeos/histograms.xml
@@ -744,7 +744,7 @@ </histogram> <histogram name="ChromeOS.Debugd.Perf.{FunctionName}" units="ms" - expires_after="2023-01-01"> + expires_after="2023-07-01"> <owner>enlightened@google.com</owner> <owner>jorgelo@google.com</owner> <owner>chromeos-security-core@google.com</owner>
diff --git a/tools/metrics/histograms/metadata/cros_ml/histograms.xml b/tools/metrics/histograms/metadata/cros_ml/histograms.xml index 652d8ff..40f0aa4 100644 --- a/tools/metrics/histograms/metadata/cros_ml/histograms.xml +++ b/tools/metrics/histograms/metadata/cros_ml/histograms.xml
@@ -22,6 +22,61 @@ <histograms> +<!-- Federated Learning and Analytics histograms --> + +<variants name="FederatedPopulationName"> + <variant name="analytics_test_population" summary="for F.A. test"/> + <variant name="timezone_code_population" summary="for timezone PHH task"/> +</variants> + +<histogram name="FederatedService.ServiceEvent" enum="FederatedServiceEvent" + expires_after="2023-07-01"> + <owner>alanlxl@chromium.org</owner> + <owner>amoylan@chromium.org</owner> + <owner>cros-federated-team@google.com</owner> + <summary> + The events on FederatedService level, mainly about the fcp library loading. + </summary> +</histogram> + +<histogram name="FederatedService.StorageEvent" enum="FederatedStorageEvent" + expires_after="2023-07-01"> + <owner>alanlxl@chromium.org</owner> + <owner>amoylan@chromium.org</owner> + <owner>cros-federated-team@google.com</owner> + <summary> + The FederatedService storage related events, including DB connection, + disconnection and various errors. + </summary> +</histogram> + +<histogram name="FederatedService.{Population}.CpuTimeMicrosec" + units="microseconds" expires_after="2023-07-01"> + <owner>amoylan@chromium.org</owner> + <owner>alanlxl@chromium.org</owner> + <owner>cros-federated-team@google.com</owner> + <summary> + CPU time (for one CPU core) of {Population} successful tasks. Reported for + all users; users without high-resolution clocks will report 0 for short + requests. + </summary> + <token key="Population" variants="FederatedPopulationName"/> +</histogram> + +<histogram name="FederatedService.{Population}.Event" + enum="FederatedClientEvent" expires_after="2023-07-01"> + <owner>alanlxl@chromium.org</owner> + <owner>amoylan@chromium.org</owner> + <owner>cros-federated-team@google.com</owner> + <summary> + The event of FederatedService population {Population}, including receiving + examples, task contributed/rejected and various failure reasons. + </summary> + <token key="Population" variants="FederatedPopulationName"/> +</histogram> + +<!-- Machine Learning Service histograms --> + <histogram base="true" name="MachineLearningService.CpuTimeMicrosec" units="microseconds" expires_after="2023-01-15"> <owner>amoylan@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/extensions/histograms.xml b/tools/metrics/histograms/metadata/extensions/histograms.xml index 862491164..5d77f5dd 100644 --- a/tools/metrics/histograms/metadata/extensions/histograms.xml +++ b/tools/metrics/histograms/metadata/extensions/histograms.xml
@@ -338,15 +338,6 @@ </summary> </histogram> -<histogram name="Extensions.CheckForExternalUpdatesTime" units="ms" - expires_after="M77"> - <owner>rkaplow@chromium.org</owner> - <summary> - The amount of time that elapsed during - ExtensionService::CheckForExternalUpdates. - </summary> -</histogram> - <histogram name="Extensions.ChromeExtensionsClientInitTime2" units="microseconds" expires_after="2019-12-01"> <owner>dbertoni@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/families/histograms.xml b/tools/metrics/histograms/metadata/families/histograms.xml index b41b770..ed31a5c 100644 --- a/tools/metrics/histograms/metadata/families/histograms.xml +++ b/tools/metrics/histograms/metadata/families/histograms.xml
@@ -122,6 +122,18 @@ </summary> </histogram> +<histogram name="ChromeOS.FamilyLinkUser.FaviconAvailability" + enum="SupervisedUserFaviconAvailability" expires_after="2023-01-20"> + <owner>courtneywong@chromium.org</owner> + <owner>cros-families-eng@google.com</owner> + <summary> + Records whether the favicon is available when it is being requested. The + favicon is requested for UI related to supervised users, including the local + web approvals parent access dialog. This metric is only recorded on + ChromeOS. + </summary> +</histogram> + <histogram name="ChromeOS.FamilyLinkUser.LogSegment" enum="FamilyLinkUserLogSegment" expires_after="never"> <!-- expires-never: used internally for filtering --> @@ -138,6 +150,21 @@ </summary> </histogram> +<histogram name="ChromeOS.FamilyLinkUser.ParentAccess.FlowResult.{FlowType}" + enum="ParentAccessFlowResult" expires_after="2023-11-15"> + <owner>courtneywong@chromium.org</owner> + <owner>cros-families-eng@google.com</owner> + <summary> + Records the state at which the Parent Access dialog is closed for all parent + access flows. Allows to track the drop rate by important states during the + parent access flow. This metric is recorded for ChromeOS only. + </summary> + <token key="FlowType"> + <variant name="All"/> + <variant name="WebApprovals"/> + </token> +</histogram> + <histogram name="ChromeOS.FamilyUser.ChildUserTypeMismatchError" enum="ChildUserTypeMismatchError" expires_after="2023-01-20"> <owner>agawronska@chromium.org</owner> @@ -680,18 +707,6 @@ </summary> </histogram> -<histogram name="SupervisedUsers.FaviconAvailability" - enum="SupervisedUserFaviconAvailability" expires_after="2023-05-14"> - <owner>courtneywong@chromium.org</owner> - <owner>cros-families-eng@google.com</owner> - <summary> - Records whether the favicon is available when it is being requested. The - favicon is requested for UI related to supervised users, including the local - web approvals parent access dialog. This metric is only recorded on - ChromeOS. - </summary> -</histogram> - <histogram name="SupervisedUsers.ParentPermissionDialog" enum="SupervisedUserParentPermissionDialog" expires_after="2023-01-20"> <owner>tobyhuang@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/histogram_suffixes_list.xml b/tools/metrics/histograms/metadata/histogram_suffixes_list.xml index f3b85e02..a0f81463 100644 --- a/tools/metrics/histograms/metadata/histogram_suffixes_list.xml +++ b/tools/metrics/histograms/metadata/histogram_suffixes_list.xml
@@ -5996,7 +5996,6 @@ <suffix name="Enabled" label="Sideload Wipeout Active."/> <affected-histogram name="Extensions.ExternalExtensionEvent"/> <affected-histogram name="Extensions.InstallSource"/> - <affected-histogram name="Extensions.UpdateSource"/> </histogram_suffixes> <histogram_suffixes name="Signin_Actions" separator=".">
diff --git a/tools/metrics/histograms/metadata/navigation/histograms.xml b/tools/metrics/histograms/metadata/navigation/histograms.xml index b8fc8b9..be2c3ea 100644 --- a/tools/metrics/histograms/metadata/navigation/histograms.xml +++ b/tools/metrics/histograms/metadata/navigation/histograms.xml
@@ -681,12 +681,14 @@ </histogram> <histogram name="Navigation.EngagementTime.HTTP" units="ms" - expires_after="2022-01-09"> + expires_after="2023-11-28"> <owner>estark@chromium.org</owner> <owner>security-enamel@chromium.org</owner> <summary> The amount of time that an HTTP page was in the foreground. Recorded on - every page close/transition. + every page close/transition. This metric is exposed publicly on the HTTPS + Transparency Report at + https://transparencyreport.google.com/https/overview?hl=en. </summary> </histogram> @@ -696,7 +698,9 @@ <owner>security-enamel@chromium.org</owner> <summary> The amount of time that an HTTPS page was in the foreground. Recorded on - every page close/transition. + every page close/transition. This metric is exposed publicly on the HTTPS + Transparency Report at + https://transparencyreport.google.com/https/overview?hl=en. </summary> </histogram>
diff --git a/tools/metrics/histograms/metadata/optimization/histograms.xml b/tools/metrics/histograms/metadata/optimization/histograms.xml index 541c43c..69984d59 100644 --- a/tools/metrics/histograms/metadata/optimization/histograms.xml +++ b/tools/metrics/histograms/metadata/optimization/histograms.xml
@@ -844,6 +844,10 @@ <histogram name="OptimizationGuide.PageEntitiesModelExecutor.CreatedSuccessfully" enum="BooleanSuccess" expires_after="2023-03-26"> + <obsolete> + Renamed to OptimizationGuide.PageEntitiesModelHandler.CreatedSuccessfully in + M110. + </obsolete> <owner>sophiechang@chromium.org</owner> <owner>chrome-intelligence-core@google.com</owner> <summary> @@ -856,6 +860,10 @@ <histogram name="OptimizationGuide.PageEntitiesModelExecutor.CreationStatus" enum="OptimizationGuideEntityAnnotatorCreationStatus" expires_after="2023-03-26"> + <obsolete> + Renamed to OptimizationGuide.PageEntitiesModelHandler.CreationStatus in + M110. + </obsolete> <owner>sophiechang@chromium.org</owner> <owner>chrome-intelligence-core@google.com</owner> <summary> @@ -865,6 +873,30 @@ </summary> </histogram> +<histogram + name="OptimizationGuide.PageEntitiesModelHandler.CreatedSuccessfully" + enum="BooleanSuccess" expires_after="2023-03-26"> + <owner>sophiechang@chromium.org</owner> + <owner>chrome-intelligence-core@google.com</owner> + <summary> + Records whether the page entities model handler was created successfully + from a model file. Recorded each time it was attempted, which can be + multiple times a session if a model update was received during the session. + </summary> +</histogram> + +<histogram name="OptimizationGuide.PageEntitiesModelHandler.CreationStatus" + enum="OptimizationGuideEntityAnnotatorCreationStatus" + expires_after="2023-03-26"> + <owner>sophiechang@chromium.org</owner> + <owner>chrome-intelligence-core@google.com</owner> + <summary> + Records the status for the page entities model handler's creation. Recorded + each time it was attempted, which can be multiple times a session if a model + update was received during the session. + </summary> +</histogram> + <histogram name="OptimizationGuide.PageTextDump.AbandonedRequests" units="count" expires_after="M112"> <owner>robertogden@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/others/histograms.xml b/tools/metrics/histograms/metadata/others/histograms.xml index c2bddd6..9d393cd 100644 --- a/tools/metrics/histograms/metadata/others/histograms.xml +++ b/tools/metrics/histograms/metadata/others/histograms.xml
@@ -3401,21 +3401,6 @@ </summary> </histogram> -<histogram name="Conversion.SourceRegistration.NavigationType.{RequestType}" - enum="AttributionNavigationType" expires_after="M117"> - <owner>csharrison@chromium.org</owner> - <owner>apaseltiner@chromium.org</owner> - <owner>measurement-api-dev+metrics@google.com</owner> - <summary> - For any successfully registered {RequestType} navigation sources, records - the API surface that initiated the navigation. - </summary> - <token key="RequestType"> - <variant name="Background" summary="background"/> - <variant name="Foreground" summary="foreground"/> - </token> -</histogram> - <histogram name="Conversions.AggregatableKeysPerSource" units="keys" expires_after="M117"> <owner>linnan@chromium.org</owner> @@ -4343,6 +4328,21 @@ </summary> </histogram> +<histogram name="Conversions.SourceRegistration.NavigationType.{RequestType}" + enum="AttributionNavigationType" expires_after="M117"> + <owner>csharrison@chromium.org</owner> + <owner>apaseltiner@chromium.org</owner> + <owner>measurement-api-dev+metrics@google.com</owner> + <summary> + For any successfully registered {RequestType} navigation sources, records + the API surface that initiated the navigation. + </summary> + <token key="RequestType"> + <variant name="Background" summary="background"/> + <variant name="Foreground" summary="foreground"/> + </token> +</histogram> + <histogram name="Conversions.SourceStoredStatus" enum="ConversionStorageSourceStatus" expires_after="M117"> <obsolete>
diff --git a/tools/metrics/histograms/metadata/webapps/histograms.xml b/tools/metrics/histograms/metadata/webapps/histograms.xml index 509d1158..52c7899e 100644 --- a/tools/metrics/histograms/metadata/webapps/histograms.xml +++ b/tools/metrics/histograms/metadata/webapps/histograms.xml
@@ -862,7 +862,7 @@ </histogram> <histogram name="WebApp.Preinstalled.AppDuplicationFixApplied" units="apps" - expires_after="2023-04-16"> + expires_after="2023-12-01"> <owner>alancutter@chromium.org</owner> <owner>desktop-pwas-team@google.com</owner> <summary> @@ -878,7 +878,7 @@ </histogram> <histogram name="WebApp.Preinstalled.AppToReplaceStillDefaultInstalledCount" - units="apps" expires_after="2022-04-17"> + units="apps" expires_after="2023-12-01"> <owner>alancutter@chromium.org</owner> <owner>desktop-pwas-team@google.com</owner> <summary> @@ -894,7 +894,7 @@ </histogram> <histogram name="WebApp.Preinstalled.AppToReplaceStillInstalledCount" - units="apps" expires_after="2023-04-30"> + units="apps" expires_after="2023-12-01"> <owner>alancutter@chromium.org</owner> <owner>desktop-pwas-team@google.com</owner> <summary> @@ -911,7 +911,7 @@ </histogram> <histogram name="WebApp.Preinstalled.AppToReplaceStillInstalledInShelfCount" - units="apps" expires_after="2023-04-30"> + units="apps" expires_after="2023-12-01"> <owner>alancutter@chromium.org</owner> <owner>desktop-pwas-team@google.com</owner> <summary> @@ -927,7 +927,7 @@ </histogram> <histogram name="WebApp.Preinstalled.ConfigErrorCount" units="apps" - expires_after="2023-04-16"> + expires_after="2023-12-01"> <owner>alancutter@chromium.org</owner> <owner>desktop-pwas-team@google.com</owner> <summary> @@ -938,7 +938,7 @@ </histogram> <histogram name="WebApp.Preinstalled.CorruptUserUninstallPrefsCount" - units="apps" expires_after="2023-04-16"> + units="apps" expires_after="2023-12-01"> <owner>alancutter@chromium.org</owner> <owner>dibyapal@chromium.org</owner> <owner>desktop-pwas-team@google.com</owner> @@ -951,7 +951,7 @@ </histogram> <histogram name="WebApp.Preinstalled.DisabledCount" units="apps" - expires_after="2023-04-30"> + expires_after="2023-12-01"> <owner>alancutter@chromium.org</owner> <owner>desktop-pwas-team@google.com</owner> <summary> @@ -961,7 +961,7 @@ </histogram> <histogram name="WebApp.Preinstalled.DisabledReason" - enum="PreinstalledAppDisabledReason" expires_after="2022-12-01"> + enum="PreinstalledAppDisabledReason" expires_after="2023-12-01"> <owner>dmurph@chromium.org</owner> <owner>desktop-pwas-team@google.com</owner> <summary> @@ -972,7 +972,7 @@ </histogram> <histogram name="WebApp.Preinstalled.EnabledCount" units="apps" - expires_after="2023-03-19"> + expires_after="2023-12-01"> <owner>alancutter@chromium.org</owner> <owner>desktop-pwas-team@google.com</owner> <summary> @@ -982,7 +982,7 @@ </histogram> <histogram name="WebApp.Preinstalled.ExternalConfigMapAbsentDuringUninstall" - units="bool" expires_after="2023-07-15"> + units="bool" expires_after="2023-12-01"> <owner>phillis@chromium.org</owner> <owner>desktop-pwas-team@google.com</owner> <summary> @@ -993,7 +993,7 @@ </histogram> <histogram name="WebApp.Preinstalled.MigratingWebAppAbsentChromeAppAbsent" - units="apps" expires_after="2023-03-19"> + units="apps" expires_after="2023-12-01"> <owner>alancutter@chromium.org</owner> <owner>desktop-pwas-team@google.com</owner> <summary> @@ -1004,7 +1004,7 @@ </histogram> <histogram name="WebApp.Preinstalled.MigratingWebAppAbsentChromeAppPresent" - units="apps" expires_after="2023-03-19"> + units="apps" expires_after="2023-12-01"> <owner>alancutter@chromium.org</owner> <owner>desktop-pwas-team@google.com</owner> <summary> @@ -1015,7 +1015,7 @@ </histogram> <histogram name="WebApp.Preinstalled.MigratingWebAppPresentChromeAppAbsent" - units="apps" expires_after="2023-03-19"> + units="apps" expires_after="2023-12-01"> <owner>alancutter@chromium.org</owner> <owner>desktop-pwas-team@google.com</owner> <summary> @@ -1026,7 +1026,7 @@ </histogram> <histogram name="WebApp.Preinstalled.MigratingWebAppPresentChromeAppPresent" - units="apps" expires_after="2023-03-19"> + units="apps" expires_after="2023-12-01"> <owner>alancutter@chromium.org</owner> <owner>desktop-pwas-team@google.com</owner> <summary> @@ -1037,7 +1037,7 @@ </histogram> <histogram name="WebApp.Preinstalled.UninstallAndReplaceCount" units="apps" - expires_after="2023-04-30"> + expires_after="2023-12-01"> <owner>alancutter@chromium.org</owner> <owner>desktop-pwas-team@google.com</owner> <summary>
diff --git a/tools/metrics/structured/structured.xml b/tools/metrics/structured/structured.xml index 544a6fb..704159c 100644 --- a/tools/metrics/structured/structured.xml +++ b/tools/metrics/structured/structured.xml
@@ -227,7 +227,7 @@ <metric name="ProviderType" type="int"> <summary> Which type of search provider the launched result was created by. This comes - from the RankingItemType enum. + from the AppListSearchResultType enum. </summary> </metric> <metric name="Score" type="int">
diff --git a/tools/perf/PRESUBMIT.py b/tools/perf/PRESUBMIT.py index 4f19b91f..aff11d0 100644 --- a/tools/perf/PRESUBMIT.py +++ b/tools/perf/PRESUBMIT.py
@@ -10,6 +10,8 @@ import os +PRESUBMIT_VERSION = '2.0.0' + USE_PYTHON3 = True @@ -23,26 +25,24 @@ """ results = [] - results.extend(_CheckExpectations(input_api, output_api)) - results.extend(_CheckJson(input_api, output_api)) results.extend( _CheckPerfDataCurrentness(input_api, output_api, block_on_failure)) results.extend( _CheckPerfJsonConfigs(input_api, output_api, block_on_failure)) - results.extend(_CheckWprShaFiles(input_api, output_api)) results.extend(_CheckShardMaps(input_api, output_api, block_on_failure)) - results.extend(_CheckVersionsInSmokeTests(input_api, output_api)) - results.extend( - input_api.RunTests( - input_api.canned_checks.GetPylint( - input_api, - output_api, - extra_paths_list=_GetPathsToPrepend(input_api), - pylintrc='pylintrc', - version='2.7'))) return results +def CheckPyLint(input_api, output_api): + return input_api.RunTests( + input_api.canned_checks.GetPylint( + input_api, + output_api, + extra_paths_list=_GetPathsToPrepend(input_api), + pylintrc='pylintrc', + version='2.7')) + + def _GetPathsToPrepend(input_api): perf_dir = input_api.PresubmitLocalPath() chromium_src_dir = input_api.os_path.join(perf_dir, '..', '..') @@ -115,7 +115,8 @@ output_api.PresubmitPromptWarning(error_msg, long_text=out)) return results -def _CheckExpectations(input_api, output_api): + +def CheckExpectations(input_api, output_api): return _RunValidationScript( input_api, output_api, @@ -140,7 +141,8 @@ block_on_failure ) -def _CheckWprShaFiles(input_api, output_api): + +def CheckWprShaFiles(input_api, output_api): """Check whether the wpr sha files have matching URLs.""" wpr_archive_shas = [] for affected_file in input_api.AffectedFiles(include_deletes=False): @@ -164,7 +166,8 @@ block_on_failure ) -def _CheckJson(input_api, output_api): + +def CheckJson(input_api, output_api): """Checks whether JSON files in this change can be parsed.""" for affected_file in input_api.AffectedFiles(include_deletes=False): filename = affected_file.AbsoluteLocalPath() @@ -180,7 +183,8 @@ return [output_api.PresubmitError('Error parsing JSON in %s!' % filename)] return [] -def _CheckVersionsInSmokeTests(input_api, output_api): + +def CheckVersionsInSmokeTests(input_api, output_api): return _RunValidationScript( input_api, output_api,
diff --git a/tools/perf/core/perfetto_binary_roller/binary_deps.json b/tools/perf/core/perfetto_binary_roller/binary_deps.json index e6b2b46d..bb58b0d 100644 --- a/tools/perf/core/perfetto_binary_roller/binary_deps.json +++ b/tools/perf/core/perfetto_binary_roller/binary_deps.json
@@ -5,24 +5,24 @@ "full_remote_path": "perfetto-luci-artifacts/v31.0/linux-arm64/trace_processor_shell" }, "win": { - "hash": "a9ae080a553abd2b39f574f81afb8bfdadee9eb3", - "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/win/1af6f10d7c0429403e0f7ad4429a0023bb70c763/trace_processor_shell.exe" + "hash": "7b8e642a108d95fa8aa71a91f0841d417f9fc477", + "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/win/36fb00a3c36d9c367f50ba03c9bd9c4f5f45161b/trace_processor_shell.exe" }, "linux_arm": { "hash": "6373f26144aad58f230d11d6a91efda5a09c9873", "full_remote_path": "perfetto-luci-artifacts/v31.0/linux-arm/trace_processor_shell" }, "mac": { - "hash": "01d68bd5aee0af9d9d4f1aa1399eeb4f94f27958", - "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/mac/1af6f10d7c0429403e0f7ad4429a0023bb70c763/trace_processor_shell" + "hash": "4065b8c6761f15fab43b9e1bad6780651b9d2018", + "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/mac/c2fa74a858edfb42ccfe4a024de1dabd6b5fbabe/trace_processor_shell" }, "mac_arm64": { "hash": "5f47ee79e59d00bf3889d30ca52315522c158040", "full_remote_path": "perfetto-luci-artifacts/v31.0/mac-arm64/trace_processor_shell" }, "linux": { - "hash": "d4b785b5f6bfb57ebe334fafd151986aa3021d4d", - "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/linux/1af6f10d7c0429403e0f7ad4429a0023bb70c763/trace_processor_shell" + "hash": "a70f8f1b2deba909d96f2fa8ef491c00dcfb8bfb", + "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/linux/36fb00a3c36d9c367f50ba03c9bd9c4f5f45161b/trace_processor_shell" } }, "power_profile.sql": {
diff --git a/tools/perf/page_sets/ad_frames.py b/tools/perf/page_sets/ad_frames.py index 5c56d61..6d46565 100644 --- a/tools/perf/page_sets/ad_frames.py +++ b/tools/perf/page_sets/ad_frames.py
@@ -7,11 +7,12 @@ from telemetry import story URL_LIST = [ - 'https://ad.doubleclick.net/ddm/adi/N378.275220.MYBESTOPTION.IT4/B22225778.261324265;sz=300x250', - 'https://ad.doubleclick.net/ddm/adi/N378.275220.MYBESTOPTION.IT4/B22225778.238871593;sz=300x600', - 'https://ad.doubleclick.net/ddm/adi/N378.275220.MYBESTOPTION.IT4/B22225778.256945163;sz=320x50', - 'https://ad.doubleclick.net/ddm/adi/N378.275220.MYBESTOPTION.IT4/B8455269.127425649;sz=970x250', - 'https://ad.doubleclick.net/ddm/adi/N378.275220.MYBESTOPTION.IT4/B8455269.129556071;sz=970x250', + "https://ad.doubleclick.net/ddm/adi/N378.275220.MYBESTOPTION.IT4/B9340305.127562781;sz=970x250", + "https://ad.doubleclick.net/ddm/adi/N378.275220.MYBESTOPTION.IT4/B9340305.128470354;sz=300x600", + "https://ad.doubleclick.net/ddm/adi/N378.275220.MYBESTOPTION.IT4/B8455269.126839257;sz=970x250", + "https://ad.doubleclick.net/ddm/adi/N378.275220.MYBESTOPTION.IT4/B9340305.127461685;sz=970x250", + "https://ad.doubleclick.net/ddm/adi/N378.3159.GOOGLE3/B9340305.138620671;sz=970x250", + "https://ad.doubleclick.net/ddm/adi/N378.275220.MYBESTOPTION.IT4/B9340305.128710365;sz=970x250", ]
diff --git a/tools/perf/page_sets/data/ad_frame.json b/tools/perf/page_sets/data/ad_frame.json index fe68e2c6..fc41fbf 100644 --- a/tools/perf/page_sets/data/ad_frame.json +++ b/tools/perf/page_sets/data/ad_frame.json
@@ -1,34 +1,40 @@ { "archives": { - "fencedframe: https://ad.doubleclick.net/ddm/adi/N378.275220.MYBESTOPTION.IT4/B22225778.238871593;sz=300x600": { - "DEFAULT": "ad_frame_927a4f6e5c.wprgo" + "fencedframe: https://ad.doubleclick.net/ddm/adi/N378.275220.MYBESTOPTION.IT4/B8455269.126839257;sz=970x250": { + "DEFAULT": "ad_frame_a0b3bd2462.wprgo" }, - "fencedframe: https://ad.doubleclick.net/ddm/adi/N378.275220.MYBESTOPTION.IT4/B22225778.256945163;sz=320x50": { - "DEFAULT": "ad_frame_927a4f6e5c.wprgo" + "fencedframe: https://ad.doubleclick.net/ddm/adi/N378.275220.MYBESTOPTION.IT4/B9340305.127461685;sz=970x250": { + "DEFAULT": "ad_frame_a0b3bd2462.wprgo" }, - "fencedframe: https://ad.doubleclick.net/ddm/adi/N378.275220.MYBESTOPTION.IT4/B22225778.261324265;sz=300x250": { - "DEFAULT": "ad_frame_927a4f6e5c.wprgo" + "fencedframe: https://ad.doubleclick.net/ddm/adi/N378.275220.MYBESTOPTION.IT4/B9340305.127562781;sz=970x250": { + "DEFAULT": "ad_frame_a0b3bd2462.wprgo" }, - "fencedframe: https://ad.doubleclick.net/ddm/adi/N378.275220.MYBESTOPTION.IT4/B8455269.127425649;sz=970x250": { - "DEFAULT": "ad_frame_927a4f6e5c.wprgo" + "fencedframe: https://ad.doubleclick.net/ddm/adi/N378.275220.MYBESTOPTION.IT4/B9340305.128470354;sz=300x600": { + "DEFAULT": "ad_frame_a0b3bd2462.wprgo" }, - "fencedframe: https://ad.doubleclick.net/ddm/adi/N378.275220.MYBESTOPTION.IT4/B8455269.129556071;sz=970x250": { - "DEFAULT": "ad_frame_927a4f6e5c.wprgo" + "fencedframe: https://ad.doubleclick.net/ddm/adi/N378.275220.MYBESTOPTION.IT4/B9340305.128710365;sz=970x250": { + "DEFAULT": "ad_frame_a0b3bd2462.wprgo" }, - "iframe: https://ad.doubleclick.net/ddm/adi/N378.275220.MYBESTOPTION.IT4/B22225778.238871593;sz=300x600": { - "DEFAULT": "ad_frame_65fb07b8fb.wprgo" + "fencedframe: https://ad.doubleclick.net/ddm/adi/N378.3159.GOOGLE3/B9340305.138620671;sz=970x250": { + "DEFAULT": "ad_frame_a0b3bd2462.wprgo" }, - "iframe: https://ad.doubleclick.net/ddm/adi/N378.275220.MYBESTOPTION.IT4/B22225778.256945163;sz=320x50": { - "DEFAULT": "ad_frame_65fb07b8fb.wprgo" + "iframe: https://ad.doubleclick.net/ddm/adi/N378.275220.MYBESTOPTION.IT4/B8455269.126839257;sz=970x250": { + "DEFAULT": "ad_frame_7caea33856.wprgo" }, - "iframe: https://ad.doubleclick.net/ddm/adi/N378.275220.MYBESTOPTION.IT4/B22225778.261324265;sz=300x250": { - "DEFAULT": "ad_frame_65fb07b8fb.wprgo" + "iframe: https://ad.doubleclick.net/ddm/adi/N378.275220.MYBESTOPTION.IT4/B9340305.127461685;sz=970x250": { + "DEFAULT": "ad_frame_7caea33856.wprgo" }, - "iframe: https://ad.doubleclick.net/ddm/adi/N378.275220.MYBESTOPTION.IT4/B8455269.127425649;sz=970x250": { - "DEFAULT": "ad_frame_65fb07b8fb.wprgo" + "iframe: https://ad.doubleclick.net/ddm/adi/N378.275220.MYBESTOPTION.IT4/B9340305.127562781;sz=970x250": { + "DEFAULT": "ad_frame_7caea33856.wprgo" }, - "iframe: https://ad.doubleclick.net/ddm/adi/N378.275220.MYBESTOPTION.IT4/B8455269.129556071;sz=970x250": { - "DEFAULT": "ad_frame_65fb07b8fb.wprgo" + "iframe: https://ad.doubleclick.net/ddm/adi/N378.275220.MYBESTOPTION.IT4/B9340305.128470354;sz=300x600": { + "DEFAULT": "ad_frame_7caea33856.wprgo" + }, + "iframe: https://ad.doubleclick.net/ddm/adi/N378.275220.MYBESTOPTION.IT4/B9340305.128710365;sz=970x250": { + "DEFAULT": "ad_frame_7caea33856.wprgo" + }, + "iframe: https://ad.doubleclick.net/ddm/adi/N378.3159.GOOGLE3/B9340305.138620671;sz=970x250": { + "DEFAULT": "ad_frame_7caea33856.wprgo" } }, "description": "Describes the Web Page Replay archives for a story set. Don't edit by hand! Use record_wpr for updating.",
diff --git a/tools/perf/page_sets/data/ad_frame_65fb07b8fb.wprgo.sha1 b/tools/perf/page_sets/data/ad_frame_65fb07b8fb.wprgo.sha1 deleted file mode 100644 index 2a209c5..0000000 --- a/tools/perf/page_sets/data/ad_frame_65fb07b8fb.wprgo.sha1 +++ /dev/null
@@ -1 +0,0 @@ -65fb07b8fb18b52a5334a617f917d5f0ae70d3d6 \ No newline at end of file
diff --git a/tools/perf/page_sets/data/ad_frame_7caea33856.wprgo.sha1 b/tools/perf/page_sets/data/ad_frame_7caea33856.wprgo.sha1 new file mode 100644 index 0000000..f72f1aa --- /dev/null +++ b/tools/perf/page_sets/data/ad_frame_7caea33856.wprgo.sha1
@@ -0,0 +1 @@ +7caea33856df183749c50c3cd947edb2eb2b9758 \ No newline at end of file
diff --git a/tools/perf/page_sets/data/ad_frame_927a4f6e5c.wprgo.sha1 b/tools/perf/page_sets/data/ad_frame_927a4f6e5c.wprgo.sha1 deleted file mode 100644 index 2e0caf9..0000000 --- a/tools/perf/page_sets/data/ad_frame_927a4f6e5c.wprgo.sha1 +++ /dev/null
@@ -1 +0,0 @@ -927a4f6e5c810f753f6c65762263fce8aa34246e \ No newline at end of file
diff --git a/tools/perf/page_sets/data/ad_frame_a0b3bd2462.wprgo.sha1 b/tools/perf/page_sets/data/ad_frame_a0b3bd2462.wprgo.sha1 new file mode 100644 index 0000000..68cbb36 --- /dev/null +++ b/tools/perf/page_sets/data/ad_frame_a0b3bd2462.wprgo.sha1
@@ -0,0 +1 @@ +a0b3bd246265650a9c028b83f4ac4e88a0d81ebe \ No newline at end of file
diff --git a/ui/accessibility/BUILD.gn b/ui/accessibility/BUILD.gn index 0c93ce8..fc8b481 100644 --- a/ui/accessibility/BUILD.gn +++ b/ui/accessibility/BUILD.gn
@@ -12,13 +12,12 @@ import("//tools/json_schema_compiler/json_schema_api.gni") import("//ui/base/ui_features.gni") -if (is_android) { - import("//build/config/android/rules.gni") -} - if (is_win) { import("//build/toolchain/win/midl.gni") } +if (is_android) { + import("//build/config/android/rules.gni") +} mojom("ax_constants_mojo") { generate_java = true @@ -449,6 +448,39 @@ android_library("accessibility_features_java") { srcjar_deps = [ ":java_features_srcjar" ] } + + generate_jni("ax_jni_headers") { + sources = [ + "android/java/src/org/chromium/ui/accessibility/AccessibilityState.java", + ] + deps = [ "//base:jni_java" ] + } + + source_set("ax_base_android") { + sources = [ + "android/accessibility_state.cc", + "android/accessibility_state.h", + ] + deps = [ + ":ax_jni_headers", + "//base", + ] + } + + android_library("ax_base_java") { + sources = [ + "android/java/src/org/chromium/ui/accessibility/AccessibilityState.java", + ] + deps = [ + ":ax_base_android", + ":ax_jni_headers", + "//base:base_java", + "//base:jni_java", + "//build/android:build_java", + "//third_party/androidx:androidx_annotation_annotation_jvm_java", + ] + annotation_processor_deps = [ "//base/android/jni_generator:jni_processor" ] + } } test("accessibility_perftests") {
diff --git a/ui/accessibility/android/accessibility_state.cc b/ui/accessibility/android/accessibility_state.cc new file mode 100644 index 0000000..7d1d9b2b --- /dev/null +++ b/ui/accessibility/android/accessibility_state.cc
@@ -0,0 +1,99 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ui/accessibility/android/accessibility_state.h" + +#include <vector> + +#include "base/android/jni_android.h" +#include "base/android/jni_array.h" +#include "base/no_destructor.h" +#include "ui/accessibility/ax_jni_headers/AccessibilityState_jni.h" + +using base::android::AppendJavaStringArrayToStringVector; +using base::android::AttachCurrentThread; + +namespace ui { +// static +void AccessibilityState::RegisterObservers() { + // Setup the listeners for accessibility state changes, so we can + // inform the renderer about changes. + JNIEnv* env = AttachCurrentThread(); + ui::Java_AccessibilityState_registerObservers(env); +} + +// static +void AccessibilityState::RegisterAnimatorDurationScaleDelegate( + Delegate* delegate) { + GetDelegates().push_back(delegate); +} + +// static +void AccessibilityState::UnregisterAnimatorDurationScaleDelegate( + Delegate* delegate) { + std::vector<Delegate*> delegates = GetDelegates(); + auto it = std::find(delegates.begin(), delegates.end(), delegate); + delegates.erase(it); +} + +// static +int AccessibilityState::GetAccessibilityServiceEventTypeMask() { + JNIEnv* env = AttachCurrentThread(); + return ui::Java_AccessibilityState_getAccessibilityServiceEventTypeMask(env); +} + +// static +int AccessibilityState::GetAccessibilityServiceFeedbackTypeMask() { + JNIEnv* env = AttachCurrentThread(); + return ui::Java_AccessibilityState_getAccessibilityServiceFeedbackTypeMask( + env); +} + +// static +int AccessibilityState::GetAccessibilityServiceFlagsMask() { + JNIEnv* env = AttachCurrentThread(); + return ui::Java_AccessibilityState_getAccessibilityServiceFlagsMask(env); +} + +// static +int AccessibilityState::GetAccessibilityServiceCapabilitiesMask() { + JNIEnv* env = AttachCurrentThread(); + return ui::Java_AccessibilityState_getAccessibilityServiceCapabilitiesMask( + env); +} + +// static +std::vector<std::string> AccessibilityState::GetAccessibilityServiceIds() { + JNIEnv* env = AttachCurrentThread(); + + auto j_service_ids = + ui::Java_AccessibilityState_getAccessibilityServiceIds(env); + std::vector<std::string> service_ids; + AppendJavaStringArrayToStringVector(env, j_service_ids, &service_ids); + return service_ids; +} + +// static +bool AccessibilityState::HasSpokenFeedbackServicePresent() { + JNIEnv* env = AttachCurrentThread(); + return ui::Java_AccessibilityState_hasSpokenFeedbackServicePresent(env); +} + +// static +void AccessibilityState::NotifyAnimatorDurationScaleObservers() { + for (Delegate* delegate : GetDelegates()) + delegate->OnAnimatorDurationScaleChanged(); +} + +// static +std::vector<AccessibilityState::Delegate*> AccessibilityState::GetDelegates() { + static base::NoDestructor<std::vector<Delegate*>> delegates; + return *delegates; +} + +// static +void JNI_AccessibilityState_OnAnimatorDurationScaleChanged(JNIEnv* env) { + AccessibilityState::NotifyAnimatorDurationScaleObservers(); +} +} // namespace ui
diff --git a/ui/accessibility/android/accessibility_state.h b/ui/accessibility/android/accessibility_state.h new file mode 100644 index 0000000..9de089b --- /dev/null +++ b/ui/accessibility/android/accessibility_state.h
@@ -0,0 +1,58 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef UI_ACCESSIBILITY_ANDROID_ACCESSIBILITY_STATE_H_ +#define UI_ACCESSIBILITY_ANDROID_ACCESSIBILITY_STATE_H_ + +#include <vector> + +namespace ui { + +// Provides methods for measuring accessibility state on Android via +// org.chromium.ui.accessibility.AccessibilityState. +class AccessibilityState { + public: + // Provides an interface for clients to listen to animator duration scale + // changes. + class Delegate { + public: + // Called when the animator duration scale changes. + virtual void OnAnimatorDurationScaleChanged() = 0; + }; + + // -------------------------------------------------------------------------- + // Methods that call into AccessibilityState.java via JNI + // -------------------------------------------------------------------------- + // + // Register Java-side Android accessibility state observers and ensure + // AccessibilityState is initialized. + static void RegisterObservers(); + // Returns the event mask of all running accessibility services. + static int GetAccessibilityServiceEventTypeMask(); + // Returns the feedback type mask of all running accessibility services. + static int GetAccessibilityServiceFeedbackTypeMask(); + // Returns the flags mask of all running accessibility services. + static int GetAccessibilityServiceFlagsMask(); + // Returns the capabilities mask of all running accessibility services. + static int GetAccessibilityServiceCapabilitiesMask(); + // Returns a vector containing the IDs of all running accessibility services. + static std::vector<std::string> GetAccessibilityServiceIds(); + // Returns true if there is a spoken feedback service running. + static bool HasSpokenFeedbackServicePresent(); + + // Registers a delegate to listen to animator duration scale changes. + static void RegisterAnimatorDurationScaleDelegate(Delegate* delegate); + // Unregisters a delegate to listen to animator duration scale changes. + static void UnregisterAnimatorDurationScaleDelegate(Delegate* delegate); + // Notifies all delegates of an animator duration scale change. + static void NotifyAnimatorDurationScaleObservers(); + + private: + // Returns the static vector of Delegates. + static std::vector<Delegate*> GetDelegates(); +}; + +} // namespace ui + +#endif // UI_ACCESSIBILITY_ANDROID_ACCESSIBILITY_STATE_H_
diff --git a/content/public/android/java/src/org/chromium/content/browser/accessibility/BrowserAccessibilityState.java b/ui/accessibility/android/java/src/org/chromium/ui/accessibility/AccessibilityState.java similarity index 95% rename from content/public/android/java/src/org/chromium/content/browser/accessibility/BrowserAccessibilityState.java rename to ui/accessibility/android/java/src/org/chromium/ui/accessibility/AccessibilityState.java index 15d6b28..c4d730b 100644 --- a/content/public/android/java/src/org/chromium/content/browser/accessibility/BrowserAccessibilityState.java +++ b/ui/accessibility/android/java/src/org/chromium/ui/accessibility/AccessibilityState.java
@@ -2,12 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.content.browser.accessibility; +package org.chromium.ui.accessibility; import static android.accessibilityservice.AccessibilityServiceInfo.FEEDBACK_SPOKEN; -import static org.chromium.content.browser.accessibility.WebContentsAccessibilityImpl.TAG; - import android.accessibilityservice.AccessibilityServiceInfo; import android.content.ComponentName; import android.content.ContentResolver; @@ -37,11 +35,11 @@ import java.util.WeakHashMap; /** - * Provides utility methods relating to measuring accessibility state on the current platform (i.e. - * Android in this case). See content::BrowserAccessibilityStateImpl. + * Provides utility methods relating to measuring accessibility state on Android. See native + * counterpart in ui::accessibility::AccessibilityState. */ -@JNINamespace("content") -public class BrowserAccessibilityState { +@JNINamespace("ui") +public class AccessibilityState { /** * An interface for classes that want to be notified whenever the accessibility * state has changed, which can happen when accessibility services start or stop. @@ -50,6 +48,8 @@ public void onBrowserAccessibilityStateChanged(boolean newScreenReaderEnabledState); } + private static final String TAG = "A11yState"; + // Analysis of the most popular accessibility services on Android suggests // that any service that requests any of these three events is a screen reader // or other complete assistive technology. If none of these events are requested, @@ -302,7 +302,7 @@ // {MAX_DELAY_MILLIS} has been reached, in which case send whatever we have. if (sNextDelayMillis < MAX_DELAY_MILLIS) { ThreadUtils.getUiThreadHandler().postDelayed( - BrowserAccessibilityState::updateAccessibilityServices, sNextDelayMillis); + AccessibilityState::updateAccessibilityServices, sNextDelayMillis); sNextDelayMillis *= 2; return; } @@ -325,7 +325,7 @@ */ // TODO(mschillaci,jacklynch): Make this private and update current callers. @CalledByNative - protected static int getAccessibilityServiceEventTypeMask() { + public static int getAccessibilityServiceEventTypeMask() { if (!sInitialized) updateAccessibilityServices(); return sEventTypeMask; } @@ -377,10 +377,9 @@ ContentResolver contentResolver = ContextUtils.getApplicationContext().getContentResolver(); ServicesObserver animationDurationScaleObserver = new ServicesObserver(ThreadUtils.getUiThreadHandler(), - () -> BrowserAccessibilityStateJni.get().onAnimatorDurationScaleChanged()); - ServicesObserver accessibilityServiceObserver = - new ServicesObserver(ThreadUtils.getUiThreadHandler(), - BrowserAccessibilityState::updateAccessibilityServices); + () -> AccessibilityStateJni.get().onAnimatorDurationScaleChanged()); + ServicesObserver accessibilityServiceObserver = new ServicesObserver( + ThreadUtils.getUiThreadHandler(), AccessibilityState::updateAccessibilityServices); // We want to be notified whenever the user has updated the animator duration scale. contentResolver.registerContentObserver(
diff --git a/ui/accessibility/android/java/src/org/chromium/ui/accessibility/OWNERS b/ui/accessibility/android/java/src/org/chromium/ui/accessibility/OWNERS new file mode 100644 index 0000000..a1d1952 --- /dev/null +++ b/ui/accessibility/android/java/src/org/chromium/ui/accessibility/OWNERS
@@ -0,0 +1,4 @@ +aldietz@google.com +dtseng@google.com +jacklynch@google.com +mschillaci@google.com
diff --git a/ui/base/interaction/interaction_test_util.cc b/ui/base/interaction/interaction_test_util.cc index 4d0bde98..5b3602b2 100644 --- a/ui/base/interaction/interaction_test_util.cc +++ b/ui/base/interaction/interaction_test_util.cc
@@ -38,6 +38,18 @@ return false; } +bool InteractionTestUtil::Simulator::ActivateSurface(TrackedElement* element) { + return false; +} + +#if !BUILDFLAG(IS_IOS) +bool InteractionTestUtil::Simulator::SendAccelerator( + TrackedElement* element, + const Accelerator& accelerator) { + return false; +} +#endif + bool InteractionTestUtil::Simulator::Confirm(TrackedElement* element) { return false; } @@ -120,6 +132,31 @@ NOTREACHED(); } +void InteractionTestUtil::ActivateSurface(TrackedElement* element) { + for (const auto& simulator : simulators_) { + if (simulator->ActivateSurface(element)) + return; + } + + // If a test has requested an invalid operation on an element, then this is + // an error. + NOTREACHED(); +} + +#if !BUILDFLAG(IS_IOS) +void InteractionTestUtil::SendAccelerator(TrackedElement* element, + Accelerator accelerator) { + for (const auto& simulator : simulators_) { + if (simulator->SendAccelerator(element, accelerator)) + return; + } + + // If a test has requested an invalid operation on an element, then this is + // an error. + NOTREACHED(); +} +#endif + void InteractionTestUtil::Confirm(TrackedElement* element) { for (const auto& simulator : simulators_) { if (simulator->Confirm(element))
diff --git a/ui/base/interaction/interaction_test_util.h b/ui/base/interaction/interaction_test_util.h index e87b937..96f7d08 100644 --- a/ui/base/interaction/interaction_test_util.h +++ b/ui/base/interaction/interaction_test_util.h
@@ -8,8 +8,13 @@ #include <memory> #include <vector> +#include "build/build_config.h" #include "ui/base/interaction/element_tracker.h" +#if !BUILDFLAG(IS_IOS) +#include "ui/base/accelerators/accelerator.h" +#endif + namespace ui::test { // Platform- and framework-independent utility for delegating specific common @@ -122,6 +127,15 @@ const std::u16string& text, TextEntryMode mode); + // Activates the surface containing `element`. + [[nodiscard]] virtual bool ActivateSurface(TrackedElement* element); + +#if !BUILDFLAG(IS_IOS) + // Sends the given accelerator to the surface containing the element. + [[nodiscard]] virtual bool SendAccelerator(TrackedElement* element, + const Accelerator& accelerator); +#endif + // Sends a "confirm" input to `element`, e.g. a RETURN keypress. [[nodiscard]] virtual bool Confirm(TrackedElement* element); }; @@ -184,6 +198,15 @@ std::u16string text, TextEntryMode mode = TextEntryMode::kReplaceAll); + // Activates the surface containing `element`. + void ActivateSurface(TrackedElement* element); + +#if !BUILDFLAG(IS_IOS) + // Sends `accelerator` to the surface containing `element`. May not work if + // the surface is not active. + void SendAccelerator(TrackedElement* element, Accelerator accelerator); +#endif + // Sends a "confirm" input to `element`, e.g. a RETURN keypress. void Confirm(TrackedElement* element);
diff --git a/ui/base/interaction/interaction_test_util_unittest.cc b/ui/base/interaction/interaction_test_util_unittest.cc index 0a9299d..6bb9526 100644 --- a/ui/base/interaction/interaction_test_util_unittest.cc +++ b/ui/base/interaction/interaction_test_util_unittest.cc
@@ -11,6 +11,11 @@ #include "ui/base/ime/text_input_mode.h" #include "ui/base/interaction/element_identifier.h" #include "ui/base/interaction/element_test_util.h" +#include "ui/events/event_constants.h" + +#if !BUILDFLAG(IS_IOS) +#include "ui/base/accelerators/accelerator.h" +#endif namespace ui::test { @@ -42,6 +47,11 @@ bool(TrackedElement* element, const std::u16string& text, TextEntryMode mode)); + MOCK_METHOD1(ActivateSurface, bool(TrackedElement* element)); +#if !BUILDFLAG(IS_IOS) + MOCK_METHOD2(SendAccelerator, + bool(TrackedElement* element, const Accelerator& accelerator)); +#endif MOCK_METHOD1(Confirm, bool(TrackedElement* element)); }; @@ -122,6 +132,30 @@ InteractionTestUtil::TextEntryMode::kReplaceAll); } +TEST(InteractionTestUtilTest, ActivateSurface) { + TestElement element(kTestElementIdentifier, kTestElementContext); + InteractionTestUtil util; + auto* const mock = util.AddSimulator( + std::make_unique<testing::StrictMock<MockInteractionSimulator>>()); + + EXPECT_CALL(*mock, ActivateSurface(&element)).WillOnce(testing::Return(true)); + util.ActivateSurface(&element); +} + +#if !BUILDFLAG(IS_IOS) +TEST(InteractionTestUtilTest, SendAccelerator) { + TestElement element(kTestElementIdentifier, kTestElementContext); + InteractionTestUtil util; + auto* const mock = util.AddSimulator( + std::make_unique<testing::StrictMock<MockInteractionSimulator>>()); + + Accelerator accel(KeyboardCode::VKEY_F5, EF_SHIFT_DOWN); + EXPECT_CALL(*mock, SendAccelerator(&element, testing::Eq(accel))) + .WillOnce(testing::Return(true)); + util.SendAccelerator(&element, accel); +} +#endif // !BUILDFLAG(IS_IOS) + TEST(InteractionTestUtilTest, Confirm) { TestElement element(kTestElementIdentifier, kTestElementContext); InteractionTestUtil util;
diff --git a/ui/base/interaction/interactive_test.cc b/ui/base/interaction/interactive_test.cc index 9a924bf..4cae6e7c 100644 --- a/ui/base/interaction/interactive_test.cc +++ b/ui/base/interaction/interactive_test.cc
@@ -111,6 +111,34 @@ return builder; } +InteractionSequence::StepBuilder InteractiveTestApi::ActivateSurface( + ElementSpecifier element) { + StepBuilder builder; + internal::SpecifyElement(builder, element); + builder.SetStartCallback(base::BindOnce( + [](InteractiveTestApi* test, InteractionSequence*, TrackedElement* el) { + test->test_util().ActivateSurface(el); + }, + base::Unretained(this))); + return builder; +} + +#if !BUILDFLAG(IS_IOS) +InteractionSequence::StepBuilder InteractiveTestApi::SendAccelerator( + ElementSpecifier element, + Accelerator accelerator) { + StepBuilder builder; + internal::SpecifyElement(builder, element); + builder.SetStartCallback(base::BindOnce( + [](Accelerator accelerator, InteractiveTestApi* test, + InteractionSequence*, TrackedElement* el) { + test->test_util().SendAccelerator(el, accelerator); + }, + accelerator, base::Unretained(this))); + return builder; +} +#endif // !BUILDFLAG(IS_IOS) + InteractionSequence::StepBuilder InteractiveTestApi::Confirm( ElementSpecifier element) { StepBuilder builder;
diff --git a/ui/base/interaction/interactive_test.h b/ui/base/interaction/interactive_test.h index e119526..193dfd8 100644 --- a/ui/base/interaction/interactive_test.h +++ b/ui/base/interaction/interactive_test.h
@@ -10,6 +10,7 @@ #include <vector> #include "base/test/rectify_callback.h" +#include "build/build_config.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/abseil-cpp/absl/types/variant.h" @@ -19,6 +20,10 @@ #include "ui/base/interaction/interaction_test_util.h" #include "ui/base/interaction/interactive_test_internal.h" +#if !BUILDFLAG(IS_IOS) +#include "ui/base/accelerators/accelerator.h" +#endif + namespace ui::test { // Provides basic interactive test functionality. @@ -101,6 +106,11 @@ ElementSpecifier element, std::u16string text, TextEntryMode mode = TextEntryMode::kReplaceAll); + [[nodiscard]] StepBuilder ActivateSurface(ElementSpecifier element); +#if !BUILDFLAG(IS_IOS) + [[nodiscard]] StepBuilder SendAccelerator(ElementSpecifier element, + Accelerator accelerator); +#endif [[nodiscard]] StepBuilder Confirm(ElementSpecifier element); // Specifies a test action that is not tied to any one UI element.
diff --git a/ui/base/interaction/interactive_test_unittest.cc b/ui/base/interaction/interactive_test_unittest.cc index 1547c898..3bc1ec66 100644 --- a/ui/base/interaction/interactive_test_unittest.cc +++ b/ui/base/interaction/interactive_test_unittest.cc
@@ -9,6 +9,7 @@ #include "base/task/single_thread_task_runner.h" #include "base/test/bind.h" #include "base/test/task_environment.h" +#include "build/build_config.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/interaction/element_identifier.h" @@ -16,6 +17,10 @@ #include "ui/base/interaction/element_tracker.h" #include "ui/base/interaction/expect_call_in_scope.h" +#if !BUILDFLAG(IS_IOS) +#include "ui/base/accelerators/accelerator.h" +#endif + namespace ui::test { namespace { @@ -27,6 +32,8 @@ kSelectTab, kSelectDropdownItem, kEnterText, + kActivateSurface, + kSendAccelerator, kConfirm }; @@ -86,6 +93,19 @@ return true; } + bool ActivateSurface(TrackedElement* element) override { + DoAction(ActionType::kActivateSurface, element, InputType::kMouse); + return true; + } + +#if !BUILDFLAG(IS_IOS) + bool SendAccelerator(TrackedElement* element, + const Accelerator& accel) override { + DoAction(ActionType::kSendAccelerator, element, InputType::kKeyboard); + return true; + } +#endif + bool Confirm(TrackedElement* element) override { DoAction(ActionType::kConfirm, element, InputType::kDontCare); return true; @@ -159,7 +179,11 @@ SelectTab(kTestId4, 3U, InputType::kTouch), SelectDropdownItem(kTestId1, 2U, InputType::kDontCare), EnterText(kTestId2, u"The quick brown fox.", TextEntryMode::kAppend), - Confirm(kTestId3)); + ActivateSurface(kTestId3), +#if !BUILDFLAG(IS_IOS) + SendAccelerator(kTestId4, Accelerator()), +#endif + Confirm(kTestId1)); EXPECT_THAT(simulator()->records(), testing::ElementsAre( @@ -175,7 +199,13 @@ kTestContext1, InputType::kDontCare}, ActionRecord{ActionType::kEnterText, kTestId2, kTestContext1, InputType::kKeyboard}, - ActionRecord{ActionType::kConfirm, kTestId3, kTestContext1, + ActionRecord{ActionType::kActivateSurface, kTestId3, + kTestContext1, InputType::kMouse}, +#if !BUILDFLAG(IS_IOS) + ActionRecord{ActionType::kSendAccelerator, kTestId4, + kTestContext1, InputType::kKeyboard}, +#endif + ActionRecord{ActionType::kConfirm, kTestId1, kTestContext1, InputType::kDontCare})); } @@ -195,7 +225,11 @@ InAnyContext(Steps(SelectTab(kTestId4, 3U, InputType::kTouch), SelectDropdownItem(kTestId1, 2U, InputType::kDontCare), EnterText(kTestId2, u"The quick brown fox."), - Confirm(kTestId3)))); + ActivateSurface(kTestId3), +#if !BUILDFLAG(IS_IOS) + SendAccelerator(kTestId4, Accelerator()), +#endif + Confirm(kTestId1)))); EXPECT_THAT(simulator()->records(), testing::ElementsAre( @@ -211,7 +245,13 @@ kTestContext1, InputType::kDontCare}, ActionRecord{ActionType::kEnterText, kTestId2, kTestContext1, InputType::kKeyboard}, - ActionRecord{ActionType::kConfirm, kTestId3, kTestContext1, + ActionRecord{ActionType::kActivateSurface, kTestId3, + kTestContext1, InputType::kMouse}, +#if !BUILDFLAG(IS_IOS) + ActionRecord{ActionType::kSendAccelerator, kTestId4, + kTestContext1, InputType::kKeyboard}, +#endif + ActionRecord{ActionType::kConfirm, kTestId1, kTestContext1, InputType::kDontCare})); } @@ -228,10 +268,15 @@ kTestContext2, InAnyContext(PressButton(kTestId1, InputType::kDontCare)), InSameContext(SelectMenuItem(kTestId2, InputType::kKeyboard)), InSameContext(DoDefaultAction(kTestId3, InputType::kMouse)), - InSameContext(Steps( - SelectTab(kTestId4, 3U, InputType::kTouch), - SelectDropdownItem(kTestId1, 2U, InputType::kDontCare), - EnterText(kTestId2, u"The quick brown fox."), Confirm(kTestId3)))); + InSameContext( + Steps(SelectTab(kTestId4, 3U, InputType::kTouch), + SelectDropdownItem(kTestId1, 2U, InputType::kDontCare), + EnterText(kTestId2, u"The quick brown fox."), + ActivateSurface(kTestId3), +#if !BUILDFLAG(IS_IOS) + SendAccelerator(kTestId4, Accelerator()), +#endif + Confirm(kTestId1)))); EXPECT_THAT(simulator()->records(), testing::ElementsAre( @@ -247,7 +292,13 @@ kTestContext1, InputType::kDontCare}, ActionRecord{ActionType::kEnterText, kTestId2, kTestContext1, InputType::kKeyboard}, - ActionRecord{ActionType::kConfirm, kTestId3, kTestContext1, + ActionRecord{ActionType::kActivateSurface, kTestId3, + kTestContext1, InputType::kMouse}, +#if !BUILDFLAG(IS_IOS) + ActionRecord{ActionType::kSendAccelerator, kTestId4, + kTestContext1, InputType::kKeyboard}, +#endif + ActionRecord{ActionType::kConfirm, kTestId1, kTestContext1, InputType::kDontCare})); }
diff --git a/ui/base/win/foreground_helper.cc b/ui/base/win/foreground_helper.cc index 846fb34c..08a148f 100644 --- a/ui/base/win/foreground_helper.cc +++ b/ui/base/win/foreground_helper.cc
@@ -4,6 +4,8 @@ #include "ui/base/win/foreground_helper.h" +#include <ostream> + #include "base/logging.h" #include "ui/gfx/win/window_impl.h"
diff --git a/ui/color/color_id.h b/ui/color/color_id.h index b00b229..524f145 100644 --- a/ui/color/color_id.h +++ b/ui/color/color_id.h
@@ -240,6 +240,11 @@ E_CPONLY(kColorOverlayScrollbarStrokeHoveredLight) \ E_CPONLY(kColorProgressBar) \ E_CPONLY(kColorProgressBarPaused) \ + E_CPONLY(kColorReadAnythingBackground) \ + E_CPONLY(kColorReadAnythingBackgroundDark) \ + E_CPONLY(kColorReadAnythingBackgroundLight) \ + E_CPONLY(kColorReadAnythingBackgroundYellow) \ + E_CPONLY(kColorReadAnythingForeground) \ E_CPONLY(kColorReadAnythingForegroundDark) \ E_CPONLY(kColorReadAnythingForegroundLight) \ E_CPONLY(kColorReadAnythingForegroundYellow) \
diff --git a/ui/color/ui_color_mixer.cc b/ui/color/ui_color_mixer.cc index 51e008a..c2bf7af 100644 --- a/ui/color/ui_color_mixer.cc +++ b/ui/color/ui_color_mixer.cc
@@ -154,6 +154,15 @@ gfx::kGoogleGreyAlpha500); mixer[kColorProgressBarPaused] = {kColorDisabledForeground}; mixer[kColorProgressBar] = {kColorAccent}; + mixer[kColorReadAnythingBackground] = { + dark_mode ? kColorReadAnythingBackgroundDark + : kColorReadAnythingBackgroundLight}; + mixer[kColorReadAnythingBackgroundDark] = {gfx::kGoogleGrey900}; + mixer[kColorReadAnythingBackgroundLight] = {gfx::kGoogleGrey050}; + mixer[kColorReadAnythingBackgroundYellow] = {gfx::kGoogleYellow200}; + mixer[kColorReadAnythingForeground] = { + dark_mode ? kColorReadAnythingForegroundDark + : kColorReadAnythingForegroundLight}; mixer[kColorReadAnythingForegroundDark] = {gfx::kGoogleGrey200}; mixer[kColorReadAnythingForegroundLight] = {gfx::kGoogleGrey800}; mixer[kColorReadAnythingForegroundYellow] = {gfx::kGoogleGrey800};
diff --git a/ui/file_manager/file_manager/containers/search_container.ts b/ui/file_manager/file_manager/containers/search_container.ts index bc60a0a..2aec05b3 100644 --- a/ui/file_manager/file_manager/containers/search_container.ts +++ b/ui/file_manager/file_manager/containers/search_container.ts
@@ -8,7 +8,7 @@ import {util} from '../common/js/util.js'; import {PropStatus, SearchData, SearchFileType, SearchLocation, SearchOptions, SearchRecency, SearchStatus, State} from '../externs/ts/state.js'; import {SearchAutocompleteList} from '../foreground/js/ui/search_autocomplete_list.js'; -import {searchAction} from '../state/actions.js'; +import {updateSearch} from '../state/actions.js'; import {getStore, Store} from '../state/store.js'; import {OptionKind, SEARCH_OPTIONS_CHANGED, SearchOptionsChangedEvent, XfSearchOptionsElement} from '../widgets/xf_search_options.js'; @@ -327,8 +327,13 @@ * Updates the store state. */ private updateState_() { - // TODO(majewski): Update the store. - console.debug('Search options event', JSON.stringify(this.currentOptions_)); + if (util.isSearchV2Enabled()) { + this.store_.dispatch(updateSearch({ + query: undefined, // do not change + status: undefined, // do not change + options: this.currentOptions_, + })); + } } /** @@ -422,7 +427,11 @@ // in the CLOSING state, without ever getting to CLOSED state. if (this.inputState_ === SearchInputState.OPEN) { if (util.isSearchV2Enabled()) { - this.store_.dispatch(searchAction({status: SearchStatus.INACTIVE})); + this.store_.dispatch(updateSearch({ + query: undefined, // do not change + status: SearchStatus.INACTIVE, + options: undefined, // do not change + })); } this.inputState_ = SearchInputState.CLOSING; this.inputElement_.tabIndex = -1;
diff --git a/ui/file_manager/file_manager/foreground/js/directory_model.js b/ui/file_manager/file_manager/foreground/js/directory_model.js index 41ab9c5..e246b50 100644 --- a/ui/file_manager/file_manager/foreground/js/directory_model.js +++ b/ui/file_manager/file_manager/foreground/js/directory_model.js
@@ -18,7 +18,7 @@ import {Store} from '../../externs/ts/store.js'; import {VolumeInfo} from '../../externs/volume_info.js'; import {VolumeManager} from '../../externs/volume_manager.js'; -import {searchAction} from '../../state/actions.js'; +import {clearSearch, updateSearch} from '../../state/actions.js'; import {changeDirectory} from '../../state/actions/current_directory.js'; import {getStore} from '../../state/store.js'; @@ -1118,7 +1118,7 @@ changeDirectoryEntry(dirEntry, opt_callback) { // Increment the sequence value. const sequence = ++this.changeDirectorySequence_; - this.clearSearch_(); + this.stopActiveSearch_(); // When switching to MyFiles volume, we should use a FilesAppEntry if // available because it returns UI-only entries too, like Linux files and @@ -1577,7 +1577,7 @@ */ search(query, onSearchRescan) { this.lastSearchQuery_ = query; - this.clearSearch_(); + this.stopActiveSearch_(); const currentDirEntry = this.getCurrentDirEntry(); if (!currentDirEntry) { // Not yet initialized. Do nothing. @@ -1610,14 +1610,14 @@ } this.store_.dispatch( - searchAction({query: query, status: PropStatus.STARTED})); + updateSearch({query: query, status: PropStatus.STARTED})); this.onSearchCompleted_ = (...args) => { // Notify the caller via callback, for non-store based callers. onSearchRescan(...args); // Notify the store-aware parts. this.store_.dispatch( - searchAction({query: query, status: PropStatus.SUCCESS})); + updateSearch({query: query, status: PropStatus.SUCCESS})); }; this.addEventListener('scan-completed', this.onSearchCompleted_); this.clearAndScan_(newDirContents, callback); @@ -1629,7 +1629,7 @@ * its canceling. * @private */ - clearSearch_() { + stopActiveSearch_() { if (!this.isSearching()) { return; } @@ -1640,7 +1640,7 @@ } if (this.store_.getState()?.search?.query) { - this.store_.dispatch(searchAction({})); + this.store_.dispatch(clearSearch()); } }
diff --git a/ui/file_manager/file_manager/foreground/js/file_manager.js b/ui/file_manager/file_manager/foreground/js/file_manager.js index bc53a40..9d94d03 100644 --- a/ui/file_manager/file_manager/foreground/js/file_manager.js +++ b/ui/file_manager/file_manager/foreground/js/file_manager.js
@@ -27,7 +27,7 @@ import {FakeEntry, FilesAppDirEntry} from '../../externs/files_app_entry_interfaces.js'; import {ForegroundWindow} from '../../externs/foreground_window.js'; import {PropStatus} from '../../externs/ts/state.js'; -import {searchAction} from '../../state/actions.js'; +import {updateSearch} from '../../state/actions.js'; import {getStore} from '../../state/store.js'; import {ActionsController} from './actions_controller.js'; @@ -1373,8 +1373,11 @@ const searchQuery = this.launchParams_.searchQuery; if (searchQuery) { metrics.startInterval('Load.ProcessInitialSearchQuery'); - getStore().dispatch( - searchAction({query: searchQuery, status: PropStatus.STARTED})); + getStore().dispatch(updateSearch({ + query: searchQuery, + status: PropStatus.STARTED, + options: undefined, + })); // Show a spinner, as the crossover search function call could be slow. const hideSpinnerCallback = this.spinnerController_.show(); const queryMatchedDirEntry =
diff --git a/ui/file_manager/file_manager/state/actions.ts b/ui/file_manager/file_manager/state/actions.ts index 8e5fef74..050401e 100644 --- a/ui/file_manager/file_manager/state/actions.ts +++ b/ui/file_manager/file_manager/state/actions.ts
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import {PropStatus, SearchOptions} from '../externs/ts/state.js'; +import {SearchData} from '../externs/ts/state.js'; import {BaseAction} from '../lib/base_store.js'; import {ClearStaleCachedEntriesAction} from './actions/all_entries.js'; @@ -31,23 +31,34 @@ /** Action to update the search state. */ export interface SearchAction extends BaseAction { type: ActionType.SEARCH; - payload: { - query?: string, - status?: PropStatus, - options?: SearchOptions, - }; + payload: SearchData; } -export function searchAction( - {query, status, options}: - {query?: string, status?: PropStatus, options?: SearchOptions}): - SearchAction { +/** + * Generates a search action based on the supplied data. + * Query, status and options can be adjusted independently of each other. + */ +export function updateSearch(data: SearchData): SearchAction { return { type: ActionType.SEARCH, payload: { - query: query, - status, - options, + query: data.query, + status: data.status, + options: data.options, + }, + }; +} + +/** + * Clears all search settings. + */ +export function clearSearch(): SearchAction { + return { + type: ActionType.SEARCH, + payload: { + query: undefined, + status: undefined, + options: undefined, }, }; }
diff --git a/ui/file_manager/file_manager/state/reducers/search.ts b/ui/file_manager/file_manager/state/reducers/search.ts index 1080753b..3df770cb 100644 --- a/ui/file_manager/file_manager/state/reducers/search.ts +++ b/ui/file_manager/file_manager/state/reducers/search.ts
@@ -2,14 +2,37 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import {State} from '../../externs/ts/state.js'; +import {SearchData, State} from '../../externs/ts/state.js'; import {SearchAction} from '../actions.js'; export function search(state: State, action: SearchAction): State { - const search = { - query: action.payload.query, - status: action.payload.status, - options: action.payload.options, + const payload = action.payload; + const blankSearch = { + query: undefined, + status: undefined, + options: undefined, }; + // Special case: if none of the fields are set, the action clears the search + // state in the store. + if (Object.values(payload).every(field => field === undefined)) { + return { + ...state, + search: blankSearch, + }; + } + const currentSearch = state.search || blankSearch; + // Create a clone of current search. We must not modify the original object, + // as store customers are free to cache it and check for changes. If we modify + // the original object the check for changes incorrectly return false. + const search: SearchData = {...currentSearch}; + if (payload.query) { + search.query = payload.query; + } + if (payload.status) { + search.status = payload.status; + } + if (payload.options) { + search.options = payload.options; + } return {...state, search}; }
diff --git a/ui/file_manager/file_manager/state/reducers/search_unittest.ts b/ui/file_manager/file_manager/state/reducers/search_unittest.ts new file mode 100644 index 0000000..6b48fe4 --- /dev/null +++ b/ui/file_manager/file_manager/state/reducers/search_unittest.ts
@@ -0,0 +1,72 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import {assertDeepEquals, assertFalse} from 'chrome://webui-test/chromeos/chai_assert.js'; + +import {PropStatus, SearchData, SearchFileType, SearchLocation, SearchRecency} from '../../externs/ts/state.js'; +import {clearSearch, updateSearch} from '../actions.js'; +import {getEmptyState, getStore, Store} from '../store.js'; + +let store: Store; + +export function setUp() { + store = getStore(); + store.init(getEmptyState()); +} + +export function testSearchAction() { + const firstState = store.getState().search; + const want: SearchData = { + query: undefined, + status: undefined, + options: undefined, + }; + assertDeepEquals( + want, firstState, + `${JSON.stringify(want)} != ${JSON.stringify(firstState)}`); + + // Change the options only. + const currentOptions = { + location: SearchLocation.THIS_FOLDER, + recency: SearchRecency.ANYTIME, + type: SearchFileType.ALL_TYPES, + }; + store.dispatch(updateSearch({ + query: undefined, + status: undefined, + options: currentOptions, + })); + + // Checks that the search action mutated only options. + want.options = currentOptions; + const secondState = store.getState().search; + assertDeepEquals( + want, secondState, + `${JSON.stringify(want)} != ${JSON.stringify(secondState)}`); + // Check that changing options does not mutate firstState. + assertFalse(firstState === secondState); + + // Change query and status, and verify that options did not change. + want.query = 'query'; + want.status = PropStatus.STARTED; + store.dispatch(updateSearch({ + query: want.query, + status: want.status, + options: undefined, + })); + const thirdState = store.getState().search; + assertDeepEquals( + want, thirdState, + `${JSON.stringify(want)} != ${JSON.stringify(thirdState)}`); + + // Clear search. + store.dispatch(clearSearch()); + const fourthState = store.getState().search; + want.query = undefined; + want.status = undefined; + want.options = undefined; + assertDeepEquals( + want, fourthState, + `${JSON.stringify(want)} != ${JSON.stringify(fourthState)}`); +}
diff --git a/ui/file_manager/file_names.gni b/ui/file_manager/file_names.gni index 96cd0c8..6469f1fd 100644 --- a/ui/file_manager/file_names.gni +++ b/ui/file_manager/file_names.gni
@@ -311,6 +311,7 @@ "file_manager/state/for_tests.ts", "file_manager/state/reducers/all_entries_unittest.ts", "file_manager/state/reducers/current_directory_unittest.ts", + "file_manager/state/reducers/search_unittest.ts", # Widgets: "file_manager/widgets/xf_breadcrumb_unittest.ts",
diff --git a/ui/gfx/win/msg_util.h b/ui/gfx/win/msg_util.h index 305e6f0..45d41b6 100644 --- a/ui/gfx/win/msg_util.h +++ b/ui/gfx/win/msg_util.h
@@ -5,6 +5,8 @@ #ifndef UI_GFX_WIN_MSG_UTIL_H_ #define UI_GFX_WIN_MSG_UTIL_H_ +#include <ostream> + #include "base/memory/weak_ptr.h" #include "base/notreached.h" #include "ui/gfx/geometry/point.h"
diff --git a/ui/views/interaction/interaction_test_util_views.cc b/ui/views/interaction/interaction_test_util_views.cc index a2e09d18..8fd8079 100644 --- a/ui/views/interaction/interaction_test_util_views.cc +++ b/ui/views/interaction/interaction_test_util_views.cc
@@ -37,6 +37,7 @@ #include "ui/views/controls/tabbed_pane/tabbed_pane.h" #include "ui/views/controls/textfield/textfield.h" #include "ui/views/interaction/element_tracker_views.h" +#include "ui/views/test/widget_test.h" #include "ui/views/view.h" #include "ui/views/view_observer.h" #include "ui/views/view_tracker.h" @@ -488,6 +489,31 @@ return false; } +bool InteractionTestUtilSimulatorViews::ActivateSurface( + ui::TrackedElement* element) { + if (!element->IsA<TrackedElementViews>()) + return false; + + auto* const widget = element->AsA<TrackedElementViews>()->view()->GetWidget(); + views::test::WidgetActivationWaiter waiter(widget, true); + widget->Activate(); + waiter.Wait(); + return true; +} + +bool InteractionTestUtilSimulatorViews::SendAccelerator( + ui::TrackedElement* element, + const ui::Accelerator& accelerator) { + if (!element->IsA<TrackedElementViews>()) + return false; + + element->AsA<TrackedElementViews>() + ->view() + ->GetFocusManager() + ->ProcessAccelerator(accelerator); + return true; +} + bool InteractionTestUtilSimulatorViews::Confirm(ui::TrackedElement* element) { if (!element->IsA<TrackedElementViews>()) return false;
diff --git a/ui/views/interaction/interaction_test_util_views.h b/ui/views/interaction/interaction_test_util_views.h index 3535d96..f0c8f9f 100644 --- a/ui/views/interaction/interaction_test_util_views.h +++ b/ui/views/interaction/interaction_test_util_views.h
@@ -43,6 +43,9 @@ bool EnterText(ui::TrackedElement* element, const std::u16string& text, TextEntryMode mode) override; + bool ActivateSurface(ui::TrackedElement* element) override; + bool SendAccelerator(ui::TrackedElement* element, + const ui::Accelerator& accelerator) override; bool Confirm(ui::TrackedElement* element) override; // Convenience method for tests that need to simulate a button press and have
diff --git a/ui/views/interaction/interaction_test_util_views_unittest.cc b/ui/views/interaction/interaction_test_util_views_unittest.cc index e9644e7..b69300f 100644 --- a/ui/views/interaction/interaction_test_util_views_unittest.cc +++ b/ui/views/interaction/interaction_test_util_views_unittest.cc
@@ -15,6 +15,7 @@ #include "testing/gtest/include/gtest/gtest.h" #include "ui/accessibility/ax_action_data.h" #include "ui/accessibility/ax_enums.mojom-shared.h" +#include "ui/base/accelerators/accelerator.h" #include "ui/base/interaction/element_identifier.h" #include "ui/base/interaction/element_tracker.h" #include "ui/base/interaction/expect_call_in_scope.h" @@ -80,6 +81,29 @@ bool activated_ = false; }; +class AcceleratorView : public View { + public: + explicit AcceleratorView(ui::Accelerator accelerator) + : accelerator_(accelerator) { + AddAccelerator(accelerator); + } + + bool AcceleratorPressed(const ui::Accelerator& accelerator) override { + EXPECT_EQ(accelerator_, accelerator); + EXPECT_FALSE(pressed_); + pressed_ = true; + return true; + } + + bool CanHandleAccelerators() const override { return true; } + + bool pressed() const { return pressed_; } + + private: + const ui::Accelerator accelerator_; + bool pressed_ = false; +}; + } // namespace class InteractionTestUtilViewsTest @@ -411,6 +435,37 @@ EXPECT_EQ(u"ef1234cd", box->GetText()); } +TEST_F(InteractionTestUtilViewsTest, ActivateSurface) { + // Create a bubble that will close on deactivation. + auto dialog_ptr = std::make_unique<BubbleDialogDelegateView>( + contents_, BubbleBorder::Arrow::TOP_LEFT); + dialog_ptr->set_close_on_deactivate(true); + auto* widget = BubbleDialogDelegateView::CreateBubble(std::move(dialog_ptr)); + WidgetVisibleWaiter shown_waiter(widget); + widget->Show(); + shown_waiter.Wait(); + + // Activating the primary widget should close the bubble again. + WidgetDestroyedWaiter closed_waiter(widget); + auto* const view_el = + ElementTrackerViews::GetInstance()->GetElementForView(contents_, true); + test_util_->ActivateSurface(view_el); + closed_waiter.Wait(); +} + +TEST_F(InteractionTestUtilViewsTest, SendAccelerator) { + ui::Accelerator accel(ui::VKEY_F5, ui::EF_SHIFT_DOWN); + ui::Accelerator accel2(ui::VKEY_F6, ui::EF_NONE); + auto* const view = + contents_->AddChildView(std::make_unique<AcceleratorView>(accel)); + auto* const view_el = + ElementTrackerViews::GetInstance()->GetElementForView(view, true); + test_util_->SendAccelerator(view_el, accel2); + EXPECT_FALSE(view->pressed()); + test_util_->SendAccelerator(view_el, accel); + EXPECT_TRUE(view->pressed()); +} + TEST_F(InteractionTestUtilViewsTest, Confirm) { UNCALLED_MOCK_CALLBACK(base::OnceClosure, accept);